Keep compiler happy
[org-mode.git] / lisp / org.el
blob1fb0afc53108bcaf84a9fea338df99a53eb37acf
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.32trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.32trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let* ((version org-version)
106 (git-version)
107 (dir (concat (file-name-directory (locate-library "org")) "../" )))
108 (if (and (file-exists-p (expand-file-name ".git" dir))
109 (executable-find "git"))
110 (let ((pwd (substring (pwd) 10)))
111 (cd dir)
112 (if (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
113 (save-excursion
114 (set-buffer "*Shell Command Output*")
115 (goto-char (point-min))
116 (re-search-forward "[^\n]+")
117 (setq git-version (match-string 0))
118 (subst-char-in-string ?- ?. git-version t)
119 (shell-command "git diff-index --name-only HEAD --")
120 (unless (eql 1 (point-max))
121 (setq git-version (concat git-version ".dirty")))
122 (setq version (concat version " (" git-version ")")))
123 (cd pwd))))
124 (setq version (format "Org-mode version %s" version))
125 (if here (insert version))
126 (message version)
127 version))
129 ;;; Compatibility constants
131 ;;; The custom variables
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
140 (defcustom org-mode-hook nil
141 "Mode hook for Org-mode, run after the mode was turned on."
142 :group 'org
143 :type 'hook)
145 (defcustom org-load-hook nil
146 "Hook that is run after org.el has been loaded."
147 :group 'org
148 :type 'hook)
150 (defvar org-modules) ; defined below
151 (defvar org-modules-loaded nil
152 "Have the modules been loaded already?")
154 (defun org-load-modules-maybe (&optional force)
155 "Load all extensions listed in `org-modules'."
156 (when (or force (not org-modules-loaded))
157 (mapc (lambda (ext)
158 (condition-case nil (require ext)
159 (error (message "Problems while trying to load feature `%s'" ext))))
160 org-modules)
161 (setq org-modules-loaded t)))
163 (defun org-set-modules (var value)
164 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
165 (set var value)
166 (when (featurep 'org)
167 (org-load-modules-maybe 'force)))
169 (when (org-bound-and-true-p org-modules)
170 (let ((a (member 'org-infojs org-modules)))
171 (and a (setcar a 'org-jsinfo))))
173 (defcustom org-modules '(org-bbdb org-bibtex org-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 " gnus: Links to GNUS folders/messages" org-gnus)
193 (const :tag " id: Global IDs for identifying entries" org-id)
194 (const :tag " info: Links to Info nodes" org-info)
195 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
196 (const :tag " habit: Track your consistency with habits" org-habit)
197 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
198 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
199 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
200 (const :tag " mew Links to Mew folders/messages" org-mew)
201 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
202 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
203 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
204 (const :tag " vm: Links to VM folders/messages" org-vm)
205 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
206 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
207 (const :tag " mouse: Additional mouse support" org-mouse)
209 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
210 (const :tag "C annotation-helper: Call Remember directly from Browser\n\t\t\t(OBSOLETE, use org-protocol)" org-annotation-helper)
211 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
212 (const :tag "C browser-url: Store link, directly from Browser\n\t\t\t(OBSOLETE, use org-protocol)" org-browser-url)
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 mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
229 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
230 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
231 (const :tag "C mtags: Support for muse-like tags" org-mtags)
232 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
233 (const :tag "C R: Computation using the R language" org-R)
234 (const :tag "C registry: A registry for Org-mode links" org-registry)
235 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
236 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
237 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
238 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
239 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
240 (const :tag "C track: Keep up with Org-mode development" org-track)
241 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
243 (defcustom org-support-shift-select nil
244 "Non-nil means, make shift-cursor commands select text when possible.
246 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
247 selecting a region, or enlarge thusly regions started in this way.
248 In Org-mode, in special contexts, these same keys are used for other
249 purposes, important enough to compete with shift selection. Org tries
250 to balance these needs by supporting `shift-select-mode' outside these
251 special contexts, under control of this variable.
253 The default of this variable is nil, to avoid confusing behavior. Shifted
254 cursor keys will then execute Org commands in the following contexts:
255 - on a headline, changing TODO state (left/right) and priority (up/down)
256 - on a time stamp, changing the time
257 - in a plain list item, changing the bullet type
258 - in a property definition line, switching between allowed values
259 - in the BEGIN line of a clock table (changing the time block).
260 Outside these contexts, the commands will throw an error.
262 When this variable is t and the cursor is not in a special context,
263 Org-mode will support shift-selection for making and enlarging regions.
264 To make this more effective, the bullet cycling will no longer happen
265 anywhere in an item line, but only if the cursor is exactly on the bullet.
267 If you set this variable to the symbol `always', then the keys
268 will not be special in headlines, property lines, and item lines, to make
269 shift selection work there as well. If this is what you want, you can
270 use the following alternative commands: `C-c C-t' and `C-c ,' to
271 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
272 TODO sets, `C-c -' to cycle item bullet types, and properties can be
273 edited by hand or in column view.
275 However, when the cursor is on a timestamp, shift-cursor commands
276 will still edit the time stamp - this is just too good to give up.
278 XEmacs user should have this variable set to nil, because shift-select-mode
279 is Emacs 23 only."
280 :group 'org
281 :type '(choice
282 (const :tag "Never" nil)
283 (const :tag "When outside special context" t)
284 (const :tag "Everywhere except timestamps" always)))
286 (defgroup org-startup nil
287 "Options concerning startup of Org-mode."
288 :tag "Org Startup"
289 :group 'org)
291 (defcustom org-startup-folded t
292 "Non-nil means, entering Org-mode will switch to OVERVIEW.
293 This can also be configured on a per-file basis by adding one of
294 the following lines anywhere in the buffer:
296 #+STARTUP: fold (or `overview', this is equivalent)
297 #+STARTUP: nofold (or `showall', this is equivalent)
298 #+STARTUP: content
299 #+STARTUP: showeverything"
300 :group 'org-startup
301 :type '(choice
302 (const :tag "nofold: show all" nil)
303 (const :tag "fold: overview" t)
304 (const :tag "content: all headlines" content)
305 (const :tag "show everything, even drawers" showeverything)))
307 (defcustom org-startup-truncated t
308 "Non-nil means, entering Org-mode will set `truncate-lines'.
309 This is useful since some lines containing links can be very long and
310 uninteresting. Also tables look terrible when wrapped."
311 :group 'org-startup
312 :type 'boolean)
314 (defcustom org-startup-indented nil
315 "Non-nil means, turn on `org-indent-mode' on startup.
316 This can also be configured on a per-file basis by adding one of
317 the following lines anywhere in the buffer:
319 #+STARTUP: indent
320 #+STARTUP: noindent"
321 :group 'org-structure
322 :type '(choice
323 (const :tag "Not" nil)
324 (const :tag "Globally (slow on startup in large files)" t)))
326 (defcustom org-startup-align-all-tables nil
327 "Non-nil means, align all tables when visiting a file.
328 This is useful when the column width in tables is forced with <N> cookies
329 in table fields. Such tables will look correct only after the first re-align.
330 This can also be configured on a per-file basis by adding one of
331 the following lines anywhere in the buffer:
332 #+STARTUP: align
333 #+STARTUP: noalign"
334 :group 'org-startup
335 :type 'boolean)
337 (defcustom org-insert-mode-line-in-empty-file nil
338 "Non-nil means insert the first line setting Org-mode in empty files.
339 When the function `org-mode' is called interactively in an empty file, this
340 normally means that the file name does not automatically trigger Org-mode.
341 To ensure that the file will always be in Org-mode in the future, a
342 line enforcing Org-mode will be inserted into the buffer, if this option
343 has been set."
344 :group 'org-startup
345 :type 'boolean)
347 (defcustom org-replace-disputed-keys nil
348 "Non-nil means use alternative key bindings for some keys.
349 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
350 These keys are also used by other packages like shift-selection-mode'
351 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
352 If you want to use Org-mode together with one of these other modes,
353 or more generally if you would like to move some Org-mode commands to
354 other keys, set this variable and configure the keys with the variable
355 `org-disputed-keys'.
357 This option is only relevant at load-time of Org-mode, and must be set
358 *before* org.el is loaded. Changing it requires a restart of Emacs to
359 become effective."
360 :group 'org-startup
361 :type 'boolean)
363 (defcustom org-use-extra-keys nil
364 "Non-nil means use extra key sequence definitions for certain
365 commands. This happens automatically if you run XEmacs or if
366 window-system is nil. This variable lets you do the same
367 manually. You must set it before loading org.
369 Example: on Carbon Emacs 22 running graphically, with an external
370 keyboard on a Powerbook, the default way of setting M-left might
371 not work for either Alt or ESC. Setting this variable will make
372 it work for ESC."
373 :group 'org-startup
374 :type 'boolean)
376 (if (fboundp 'defvaralias)
377 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
379 (defcustom org-disputed-keys
380 '(([(shift up)] . [(meta p)])
381 ([(shift down)] . [(meta n)])
382 ([(shift left)] . [(meta -)])
383 ([(shift right)] . [(meta +)])
384 ([(control shift right)] . [(meta shift +)])
385 ([(control shift left)] . [(meta shift -)]))
386 "Keys for which Org-mode and other modes compete.
387 This is an alist, cars are the default keys, second element specifies
388 the alternative to use when `org-replace-disputed-keys' is t.
390 Keys can be specified in any syntax supported by `define-key'.
391 The value of this option takes effect only at Org-mode's startup,
392 therefore you'll have to restart Emacs to apply it after changing."
393 :group 'org-startup
394 :type 'alist)
396 (defun org-key (key)
397 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
398 Or return the original if not disputed."
399 (if org-replace-disputed-keys
400 (let* ((nkey (key-description key))
401 (x (org-find-if (lambda (x)
402 (equal (key-description (car x)) nkey))
403 org-disputed-keys)))
404 (if x (cdr x) key))
405 key))
407 (defun org-find-if (predicate seq)
408 (catch 'exit
409 (while seq
410 (if (funcall predicate (car seq))
411 (throw 'exit (car seq))
412 (pop seq)))))
414 (defun org-defkey (keymap key def)
415 "Define a key, possibly translated, as returned by `org-key'."
416 (define-key keymap (org-key key) def))
418 (defcustom org-ellipsis nil
419 "The ellipsis to use in the Org-mode outline.
420 When nil, just use the standard three dots. When a string, use that instead,
421 When a face, use the standard 3 dots, but with the specified face.
422 The change affects only Org-mode (which will then use its own display table).
423 Changing this requires executing `M-x org-mode' in a buffer to become
424 effective."
425 :group 'org-startup
426 :type '(choice (const :tag "Default" nil)
427 (face :tag "Face" :value org-warning)
428 (string :tag "String" :value "...#")))
430 (defvar org-display-table nil
431 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
433 (defgroup org-keywords nil
434 "Keywords in Org-mode."
435 :tag "Org Keywords"
436 :group 'org)
438 (defcustom org-deadline-string "DEADLINE:"
439 "String to mark deadline entries.
440 A deadline is this string, followed by a time stamp. Should be a word,
441 terminated by a colon. You can insert a schedule keyword and
442 a timestamp with \\[org-deadline].
443 Changes become only effective after restarting Emacs."
444 :group 'org-keywords
445 :type 'string)
447 (defcustom org-scheduled-string "SCHEDULED:"
448 "String to mark scheduled TODO entries.
449 A schedule is this string, followed by a time stamp. Should be a word,
450 terminated by a colon. You can insert a schedule keyword and
451 a timestamp with \\[org-schedule].
452 Changes become only effective after restarting Emacs."
453 :group 'org-keywords
454 :type 'string)
456 (defcustom org-closed-string "CLOSED:"
457 "String used as the prefix for timestamps logging closing a TODO entry."
458 :group 'org-keywords
459 :type 'string)
461 (defcustom org-clock-string "CLOCK:"
462 "String used as prefix for timestamps clocking work hours on an item."
463 :group 'org-keywords
464 :type 'string)
466 (defcustom org-comment-string "COMMENT"
467 "Entries starting with this keyword will never be exported.
468 An entry can be toggled between COMMENT and normal with
469 \\[org-toggle-comment].
470 Changes become only effective after restarting Emacs."
471 :group 'org-keywords
472 :type 'string)
474 (defcustom org-quote-string "QUOTE"
475 "Entries starting with this keyword will be exported in fixed-width font.
476 Quoting applies only to the text in the entry following the headline, and does
477 not extend beyond the next headline, even if that is lower level.
478 An entry can be toggled between QUOTE and normal with
479 \\[org-toggle-fixed-width-section]."
480 :group 'org-keywords
481 :type 'string)
483 (defconst org-repeat-re
484 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
485 "Regular expression for specifying repeated events.
486 After a match, group 1 contains the repeat expression.")
488 (defgroup org-structure nil
489 "Options concerning the general structure of Org-mode files."
490 :tag "Org Structure"
491 :group 'org)
493 (defgroup org-reveal-location nil
494 "Options about how to make context of a location visible."
495 :tag "Org Reveal Location"
496 :group 'org-structure)
498 (defconst org-context-choice
499 '(choice
500 (const :tag "Always" t)
501 (const :tag "Never" nil)
502 (repeat :greedy t :tag "Individual contexts"
503 (cons
504 (choice :tag "Context"
505 (const agenda)
506 (const org-goto)
507 (const occur-tree)
508 (const tags-tree)
509 (const link-search)
510 (const mark-goto)
511 (const bookmark-jump)
512 (const isearch)
513 (const default))
514 (boolean))))
515 "Contexts for the reveal options.")
517 (defcustom org-show-hierarchy-above '((default . t))
518 "Non-nil means, show full hierarchy when revealing a location.
519 Org-mode often shows locations in an org-mode file which might have
520 been invisible before. When this is set, the hierarchy of headings
521 above the exposed location is shown.
522 Turning this off for example for sparse trees makes them very compact.
523 Instead of t, this can also be an alist specifying this option for different
524 contexts. Valid contexts are
525 agenda when exposing an entry from the agenda
526 org-goto when using the command `org-goto' on key C-c C-j
527 occur-tree when using the command `org-occur' on key C-c /
528 tags-tree when constructing a sparse tree based on tags matches
529 link-search when exposing search matches associated with a link
530 mark-goto when exposing the jump goal of a mark
531 bookmark-jump when exposing a bookmark location
532 isearch when exiting from an incremental search
533 default default for all contexts not set explicitly"
534 :group 'org-reveal-location
535 :type org-context-choice)
537 (defcustom org-show-following-heading '((default . nil))
538 "Non-nil means, show following heading when revealing a location.
539 Org-mode often shows locations in an org-mode file which might have
540 been invisible before. When this is set, the heading following the
541 match is shown.
542 Turning this off for example for sparse trees makes them very compact,
543 but makes it harder to edit the location of the match. In such a case,
544 use the command \\[org-reveal] to show more context.
545 Instead of t, this can also be an alist specifying this option for different
546 contexts. See `org-show-hierarchy-above' for valid contexts."
547 :group 'org-reveal-location
548 :type org-context-choice)
550 (defcustom org-show-siblings '((default . nil) (isearch t))
551 "Non-nil means, show all sibling heading when revealing a location.
552 Org-mode often shows locations in an org-mode file which might have
553 been invisible before. When this is set, the sibling of the current entry
554 heading are all made visible. If `org-show-hierarchy-above' is t,
555 the same happens on each level of the hierarchy above the current entry.
557 By default this is on for the isearch context, off for all other contexts.
558 Turning this off for example for sparse trees makes them very compact,
559 but makes it harder to edit the location of the match. In such a case,
560 use the command \\[org-reveal] to show more context.
561 Instead of t, this can also be an alist specifying this option for different
562 contexts. See `org-show-hierarchy-above' for valid contexts."
563 :group 'org-reveal-location
564 :type org-context-choice)
566 (defcustom org-show-entry-below '((default . nil))
567 "Non-nil means, show the entry below a headline when revealing a location.
568 Org-mode often shows locations in an org-mode file which might have
569 been invisible before. When this is set, the text below the headline that is
570 exposed is also shown.
572 By default this is off for all contexts.
573 Instead of t, this can also be an alist specifying this option for different
574 contexts. See `org-show-hierarchy-above' for valid contexts."
575 :group 'org-reveal-location
576 :type org-context-choice)
578 (defcustom org-indirect-buffer-display 'other-window
579 "How should indirect tree buffers be displayed?
580 This applies to indirect buffers created with the commands
581 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
582 Valid values are:
583 current-window Display in the current window
584 other-window Just display in another window.
585 dedicated-frame Create one new frame, and re-use it each time.
586 new-frame Make a new frame each time. Note that in this case
587 previously-made indirect buffers are kept, and you need to
588 kill these buffers yourself."
589 :group 'org-structure
590 :group 'org-agenda-windows
591 :type '(choice
592 (const :tag "In current window" current-window)
593 (const :tag "In current frame, other window" other-window)
594 (const :tag "Each time a new frame" new-frame)
595 (const :tag "One dedicated frame" dedicated-frame)))
597 (defcustom org-use-speed-commands nil
598 "Non-nil means, activate single letter commands at beginning of a headline."
599 :group 'org-structure
600 :type 'boolean)
602 (defcustom org-speed-commands-user nil
603 "Alist of additional speed commands.
604 This list will be checked before `org-speed-commands-default'
605 when the variable `org-use-speed-commands' is non-nil
606 and when the cursor is at the beginning of a headline.
607 The car if each entry is a string with a single letter, which must
608 be assigned to `self-insert-command' in the global map.
609 The cdr is either a command to be called interactively, a function
610 to be called, or a form to be evaluated."
611 :group 'org-structure
612 :type '(repeat
613 (cons
614 (string "Command letter")
615 (choice
616 (function)
617 (sexp)))))
619 (defgroup org-cycle nil
620 "Options concerning visibility cycling in Org-mode."
621 :tag "Org Cycle"
622 :group 'org-structure)
624 (defcustom org-cycle-skip-children-state-if-no-children t
625 "Non-nil means, skip CHILDREN state in entries that don't have any."
626 :group 'org-cycle
627 :type 'boolean)
629 (defcustom org-cycle-max-level nil
630 "Maximum level which should still be subject to visibility cycling.
631 Levels higher than this will, for cycling, be treated as text, not a headline.
632 When `org-odd-levels-only' is set, a value of N in this variable actually
633 means 2N-1 stars as the limiting headline.
634 When nil, cycle all levels.
635 Note that the limiting level of cycling is also influenced by
636 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
637 `org-inlinetask-min-level' is, cycling will be limited to levels one less
638 than its value."
639 :group 'org-cycle
640 :type '(choice
641 (const :tag "No limit" nil)
642 (integer :tag "Maximum level")))
644 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
645 "Names of drawers. Drawers are not opened by cycling on the headline above.
646 Drawers only open with a TAB on the drawer line itself. A drawer looks like
647 this:
648 :DRAWERNAME:
649 .....
650 :END:
651 The drawer \"PROPERTIES\" is special for capturing properties through
652 the property API.
654 Drawers can be defined on the per-file basis with a line like:
656 #+DRAWERS: HIDDEN STATE PROPERTIES"
657 :group 'org-structure
658 :group 'org-cycle
659 :type '(repeat (string :tag "Drawer Name")))
661 (defcustom org-hide-block-startup nil
662 "Non-nil means, , entering Org-mode will fold all blocks.
663 This can also be set in on a per-file basis with
665 #+STARTUP: hideblocks
666 #+STARTUP: showblocks"
667 :group 'org-startup
668 :group 'org-cycle
669 :type 'boolean)
671 (defcustom org-cycle-global-at-bob nil
672 "Cycle globally if cursor is at beginning of buffer and not at a headline.
673 This makes it possible to do global cycling without having to use S-TAB or
674 C-u TAB. For this special case to work, the first line of the buffer
675 must not be a headline - it may be empty or some other text. When used in
676 this way, `org-cycle-hook' is disables temporarily, to make sure the
677 cursor stays at the beginning of the buffer.
678 When this option is nil, don't do anything special at the beginning
679 of the buffer."
680 :group 'org-cycle
681 :type 'boolean)
683 (defcustom org-cycle-level-after-item/entry-creation t
684 "Non-nil means, cycle entry level or item indentation in new empty entries.
686 When the cursor is at the end of an empty headline, i.e with only stars
687 and maybe a TODO keyword, TAB will then switch the entry to become a child,
688 and then all possible anchestor states, before returning to the original state.
689 This makes data entry extremely fast: M-RET to create a new hedline,
690 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
692 When the cursor is at the end of an empty plain list item, one TAB will
693 make it a subitem, two or more tabs will back up to make this an item
694 higher up in the item hierarchy."
695 :group 'org-cycle
696 :type 'boolean)
698 (defcustom org-cycle-emulate-tab t
699 "Where should `org-cycle' emulate TAB.
700 nil Never
701 white Only in completely white lines
702 whitestart Only at the beginning of lines, before the first non-white char
703 t Everywhere except in headlines
704 exc-hl-bol Everywhere except at the start of a headline
705 If TAB is used in a place where it does not emulate TAB, the current subtree
706 visibility is cycled."
707 :group 'org-cycle
708 :type '(choice (const :tag "Never" nil)
709 (const :tag "Only in completely white lines" white)
710 (const :tag "Before first char in a line" whitestart)
711 (const :tag "Everywhere except in headlines" t)
712 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
715 (defcustom org-cycle-separator-lines 2
716 "Number of empty lines needed to keep an empty line between collapsed trees.
717 If you leave an empty line between the end of a subtree and the following
718 headline, this empty line is hidden when the subtree is folded.
719 Org-mode will leave (exactly) one empty line visible if the number of
720 empty lines is equal or larger to the number given in this variable.
721 So the default 2 means, at least 2 empty lines after the end of a subtree
722 are needed to produce free space between a collapsed subtree and the
723 following headline.
725 If the number is negative, and the number of empty lines is at least -N,
726 all empty lines are shown.
728 Special case: when 0, never leave empty lines in collapsed view."
729 :group 'org-cycle
730 :type 'integer)
731 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
733 (defcustom org-pre-cycle-hook nil
734 "Hook that is run before visibility cycling is happening.
735 The function(s) in this hook must accept a single argument which indicates
736 the new state that will be set right after running this hook. The
737 argument is a symbol. Before a global state change, it can have the values
738 `overview', `content', or `all'. Before a local state change, it can have
739 the values `folded', `children', or `subtree'."
740 :group 'org-cycle
741 :type 'hook)
743 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
744 org-cycle-hide-drawers
745 org-cycle-show-empty-lines
746 org-optimize-window-after-visibility-change)
747 "Hook that is run after `org-cycle' has changed the buffer visibility.
748 The function(s) in this hook must accept a single argument which indicates
749 the new state that was set by the most recent `org-cycle' command. The
750 argument is a symbol. After a global state change, it can have the values
751 `overview', `content', or `all'. After a local state change, it can have
752 the values `folded', `children', or `subtree'."
753 :group 'org-cycle
754 :type 'hook)
756 (defgroup org-edit-structure nil
757 "Options concerning structure editing in Org-mode."
758 :tag "Org Edit Structure"
759 :group 'org-structure)
761 (defcustom org-odd-levels-only nil
762 "Non-nil means, skip even levels and only use odd levels for the outline.
763 This has the effect that two stars are being added/taken away in
764 promotion/demotion commands. It also influences how levels are
765 handled by the exporters.
766 Changing it requires restart of `font-lock-mode' to become effective
767 for fontification also in regions already fontified.
768 You may also set this on a per-file basis by adding one of the following
769 lines to the buffer:
771 #+STARTUP: odd
772 #+STARTUP: oddeven"
773 :group 'org-edit-structure
774 :group 'org-font-lock
775 :type 'boolean)
777 (defcustom org-adapt-indentation t
778 "Non-nil means, adapt indentation to outline node level.
780 When this variable is set, Org assumes that you write outlines by
781 indenting text in each node to align with the headline (after the stars).
782 The following issues are influenced by this variable:
784 - When this is set and the *entire* text in an entry is indented, the
785 indentation is increased by one space in a demotion command, and
786 decreased by one in a promotion command. If any line in the entry
787 body starts with text at column 0, indentation is not changed at all.
789 - Property drawers and planning information is inserted indented when
790 this variable s set. When nil, they will not be indented.
792 - TAB indents a line relative to context. The lines below a headline
793 will be indented when this variable is set.
795 Note that this is all about true indentation, by adding and removing
796 space characters. See also `org-indent.el' which does level-dependent
797 indentation in a virtual way, i.e. at display time in Emacs."
798 :group 'org-edit-structure
799 :type 'boolean)
801 (defcustom org-special-ctrl-a/e nil
802 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
804 When t, `C-a' will bring back the cursor to the beginning of the
805 headline text, i.e. after the stars and after a possible TODO keyword.
806 In an item, this will be the position after the bullet.
807 When the cursor is already at that position, another `C-a' will bring
808 it to the beginning of the line.
810 `C-e' will jump to the end of the headline, ignoring the presence of tags
811 in the headline. A second `C-e' will then jump to the true end of the
812 line, after any tags. This also means that, when this variable is
813 non-nil, `C-e' also will never jump beyond the end of the heading of a
814 folded section, i.e. not after the ellipses.
816 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
817 going to the true line boundary first. Only a directly following, identical
818 keypress will bring the cursor to the special positions.
820 This may also be a cons cell where the behavior for `C-a' and `C-e' is
821 set separately."
822 :group 'org-edit-structure
823 :type '(choice
824 (const :tag "off" nil)
825 (const :tag "on: after stars/bullet and before tags first" t)
826 (const :tag "reversed: true line boundary first" reversed)
827 (cons :tag "Set C-a and C-e separately"
828 (choice :tag "Special C-a"
829 (const :tag "off" nil)
830 (const :tag "on: after stars/bullet first" t)
831 (const :tag "reversed: before stars/bullet first" reversed))
832 (choice :tag "Special C-e"
833 (const :tag "off" nil)
834 (const :tag "on: before tags first" t)
835 (const :tag "reversed: after tags first" reversed)))))
836 (if (fboundp 'defvaralias)
837 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
839 (defcustom org-special-ctrl-k nil
840 "Non-nil means `C-k' will behave specially in headlines.
841 When nil, `C-k' will call the default `kill-line' command.
842 When t, the following will happen while the cursor is in the headline:
844 - When the cursor is at the beginning of a headline, kill the entire
845 line and possible the folded subtree below the line.
846 - When in the middle of the headline text, kill the headline up to the tags.
847 - When after the headline text, kill the tags."
848 :group 'org-edit-structure
849 :type 'boolean)
851 (defcustom org-yank-folded-subtrees t
852 "Non-nil means, when yanking subtrees, fold them.
853 If the kill is a single subtree, or a sequence of subtrees, i.e. if
854 it starts with a heading and all other headings in it are either children
855 or siblings, then fold all the subtrees. However, do this only if no
856 text after the yank would be swallowed into a folded tree by this action."
857 :group 'org-edit-structure
858 :type 'boolean)
860 (defcustom org-yank-adjusted-subtrees nil
861 "Non-nil means, when yanking subtrees, adjust the level.
862 With this setting, `org-paste-subtree' is used to insert the subtree, see
863 this function for details."
864 :group 'org-edit-structure
865 :type 'boolean)
867 (defcustom org-M-RET-may-split-line '((default . t))
868 "Non-nil means, M-RET will split the line at the cursor position.
869 When nil, it will go to the end of the line before making a
870 new line.
871 You may also set this option in a different way for different
872 contexts. Valid contexts are:
874 headline when creating a new headline
875 item when creating a new item
876 table in a table field
877 default the value to be used for all contexts not explicitly
878 customized"
879 :group 'org-structure
880 :group 'org-table
881 :type '(choice
882 (const :tag "Always" t)
883 (const :tag "Never" nil)
884 (repeat :greedy t :tag "Individual contexts"
885 (cons
886 (choice :tag "Context"
887 (const headline)
888 (const item)
889 (const table)
890 (const default))
891 (boolean)))))
894 (defcustom org-insert-heading-respect-content nil
895 "Non-nil means, insert new headings after the current subtree.
896 When nil, the new heading is created directly after the current line.
897 The commands \\[org-insert-heading-respect-content] and
898 \\[org-insert-todo-heading-respect-content] turn this variable on
899 for the duration of the command."
900 :group 'org-structure
901 :type 'boolean)
903 (defcustom org-blank-before-new-entry '((heading . auto)
904 (plain-list-item . auto))
905 "Should `org-insert-heading' leave a blank line before new heading/item?
906 The value is an alist, with `heading' and `plain-list-item' as car,
907 and a boolean flag as cdr. For plain lists, if the variable
908 `org-empty-line-terminates-plain-lists' is set, the setting here
909 is ignored and no empty line is inserted, to keep the list in tact."
910 :group 'org-edit-structure
911 :type '(list
912 (cons (const heading)
913 (choice (const :tag "Never" nil)
914 (const :tag "Always" t)
915 (const :tag "Auto" auto)))
916 (cons (const plain-list-item)
917 (choice (const :tag "Never" nil)
918 (const :tag "Always" t)
919 (const :tag "Auto" auto)))))
921 (defcustom org-insert-heading-hook nil
922 "Hook being run after inserting a new heading."
923 :group 'org-edit-structure
924 :type 'hook)
926 (defcustom org-enable-fixed-width-editor t
927 "Non-nil means, lines starting with \":\" are treated as fixed-width.
928 This currently only means, they are never auto-wrapped.
929 When nil, such lines will be treated like ordinary lines.
930 See also the QUOTE keyword."
931 :group 'org-edit-structure
932 :type 'boolean)
935 (defcustom org-goto-auto-isearch t
936 "Non-nil means, typing characters in org-goto starts incremental search."
937 :group 'org-edit-structure
938 :type 'boolean)
940 (defgroup org-sparse-trees nil
941 "Options concerning sparse trees in Org-mode."
942 :tag "Org Sparse Trees"
943 :group 'org-structure)
945 (defcustom org-highlight-sparse-tree-matches t
946 "Non-nil means, highlight all matches that define a sparse tree.
947 The highlights will automatically disappear the next time the buffer is
948 changed by an edit command."
949 :group 'org-sparse-trees
950 :type 'boolean)
952 (defcustom org-remove-highlights-with-change t
953 "Non-nil means, any change to the buffer will remove temporary highlights.
954 Such highlights are created by `org-occur' and `org-clock-display'.
955 When nil, `C-c C-c needs to be used to get rid of the highlights.
956 The highlights created by `org-preview-latex-fragment' always need
957 `C-c C-c' to be removed."
958 :group 'org-sparse-trees
959 :group 'org-time
960 :type 'boolean)
963 (defcustom org-occur-hook '(org-first-headline-recenter)
964 "Hook that is run after `org-occur' has constructed a sparse tree.
965 This can be used to recenter the window to show as much of the structure
966 as possible."
967 :group 'org-sparse-trees
968 :type 'hook)
970 (defgroup org-imenu-and-speedbar nil
971 "Options concerning imenu and speedbar in Org-mode."
972 :tag "Org Imenu and Speedbar"
973 :group 'org-structure)
975 (defcustom org-imenu-depth 2
976 "The maximum level for Imenu access to Org-mode headlines.
977 This also applied for speedbar access."
978 :group 'org-imenu-and-speedbar
979 :type 'integer)
981 (defgroup org-table nil
982 "Options concerning tables in Org-mode."
983 :tag "Org Table"
984 :group 'org)
986 (defcustom org-enable-table-editor 'optimized
987 "Non-nil means, lines starting with \"|\" are handled by the table editor.
988 When nil, such lines will be treated like ordinary lines.
990 When equal to the symbol `optimized', the table editor will be optimized to
991 do the following:
992 - Automatic overwrite mode in front of whitespace in table fields.
993 This makes the structure of the table stay in tact as long as the edited
994 field does not exceed the column width.
995 - Minimize the number of realigns. Normally, the table is aligned each time
996 TAB or RET are pressed to move to another field. With optimization this
997 happens only if changes to a field might have changed the column width.
998 Optimization requires replacing the functions `self-insert-command',
999 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1000 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1001 very good at guessing when a re-align will be necessary, but you can always
1002 force one with \\[org-ctrl-c-ctrl-c].
1004 If you would like to use the optimized version in Org-mode, but the
1005 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1007 This variable can be used to turn on and off the table editor during a session,
1008 but in order to toggle optimization, a restart is required.
1010 See also the variable `org-table-auto-blank-field'."
1011 :group 'org-table
1012 :type '(choice
1013 (const :tag "off" nil)
1014 (const :tag "on" t)
1015 (const :tag "on, optimized" optimized)))
1017 (defcustom org-self-insert-cluster-for-undo t
1018 "Non-nil means cluster self-insert commands for undo when possible.
1019 If this is set, then, like in the Emacs command loop, 20 consequtive
1020 characters will be undone together.
1021 This is configurable, because there is some impact on typing performance."
1022 :group 'org-table
1023 :type 'boolean)
1025 (defcustom org-table-tab-recognizes-table.el t
1026 "Non-nil means, TAB will automatically notice a table.el table.
1027 When it sees such a table, it moves point into it and - if necessary -
1028 calls `table-recognize-table'."
1029 :group 'org-table-editing
1030 :type 'boolean)
1032 (defgroup org-link nil
1033 "Options concerning links in Org-mode."
1034 :tag "Org Link"
1035 :group 'org)
1037 (defvar org-link-abbrev-alist-local nil
1038 "Buffer-local version of `org-link-abbrev-alist', which see.
1039 The value of this is taken from the #+LINK lines.")
1040 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1042 (defcustom org-link-abbrev-alist nil
1043 "Alist of link abbreviations.
1044 The car of each element is a string, to be replaced at the start of a link.
1045 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1046 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1048 [[linkkey:tag][description]]
1050 The 'linkkey' must be a word word, starting with a letter, followed
1051 by letters, numbers, '-' or '_'.
1053 If REPLACE is a string, the tag will simply be appended to create the link.
1054 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1055 the placeholder \"%h\" will cause a url-encoded version of the tag to
1056 be inserted at that point (see the function `url-hexify-string').
1058 REPLACE may also be a function that will be called with the tag as the
1059 only argument to create the link, which should be returned as a string.
1061 See the manual for examples."
1062 :group 'org-link
1063 :type '(repeat
1064 (cons
1065 (string :tag "Protocol")
1066 (choice
1067 (string :tag "Format")
1068 (function)))))
1070 (defcustom org-descriptive-links t
1071 "Non-nil means, hide link part and only show description of bracket links.
1072 Bracket links are like [[link][description]]. This variable sets the initial
1073 state in new org-mode buffers. The setting can then be toggled on a
1074 per-buffer basis from the Org->Hyperlinks menu."
1075 :group 'org-link
1076 :type 'boolean)
1078 (defcustom org-link-file-path-type 'adaptive
1079 "How the path name in file links should be stored.
1080 Valid values are:
1082 relative Relative to the current directory, i.e. the directory of the file
1083 into which the link is being inserted.
1084 absolute Absolute path, if possible with ~ for home directory.
1085 noabbrev Absolute path, no abbreviation of home directory.
1086 adaptive Use relative path for files in the current directory and sub-
1087 directories of it. For other files, use an absolute path."
1088 :group 'org-link
1089 :type '(choice
1090 (const relative)
1091 (const absolute)
1092 (const noabbrev)
1093 (const adaptive)))
1095 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1096 "Types of links that should be activated in Org-mode files.
1097 This is a list of symbols, each leading to the activation of a certain link
1098 type. In principle, it does not hurt to turn on most link types - there may
1099 be a small gain when turning off unused link types. The types are:
1101 bracket The recommended [[link][description]] or [[link]] links with hiding.
1102 angular Links in angular brackets that may contain whitespace like
1103 <bbdb:Carsten Dominik>.
1104 plain Plain links in normal text, no whitespace, like http://google.com.
1105 radio Text that is matched by a radio target, see manual for details.
1106 tag Tag settings in a headline (link to tag search).
1107 date Time stamps (link to calendar).
1108 footnote Footnote labels.
1110 Changing this variable requires a restart of Emacs to become effective."
1111 :group 'org-link
1112 :type '(set :greedy t
1113 (const :tag "Double bracket links (new style)" bracket)
1114 (const :tag "Angular bracket links (old style)" angular)
1115 (const :tag "Plain text links" plain)
1116 (const :tag "Radio target matches" radio)
1117 (const :tag "Tags" tag)
1118 (const :tag "Timestamps" date)
1119 (const :tag "Footnotes" footnote)))
1121 (defcustom org-make-link-description-function nil
1122 "Function to use to generate link descriptions from links. If
1123 nil the link location will be used. This function must take two
1124 parameters; the first is the link and the second the description
1125 org-insert-link has generated, and should return the description
1126 to use."
1127 :group 'org-link
1128 :type 'function)
1130 (defgroup org-link-store nil
1131 "Options concerning storing links in Org-mode."
1132 :tag "Org Store Link"
1133 :group 'org-link)
1135 (defcustom org-email-link-description-format "Email %c: %.30s"
1136 "Format of the description part of a link to an email or usenet message.
1137 The following %-escapes will be replaced by corresponding information:
1139 %F full \"From\" field
1140 %f name, taken from \"From\" field, address if no name
1141 %T full \"To\" field
1142 %t first name in \"To\" field, address if no name
1143 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1144 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1145 %s subject
1146 %m message-id.
1148 You may use normal field width specification between the % and the letter.
1149 This is for example useful to limit the length of the subject.
1151 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1152 :group 'org-link-store
1153 :type 'string)
1155 (defcustom org-from-is-user-regexp
1156 (let (r1 r2)
1157 (when (and user-mail-address (not (string= user-mail-address "")))
1158 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1159 (when (and user-full-name (not (string= user-full-name "")))
1160 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1161 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1162 "Regexp matched against the \"From:\" header of an email or usenet message.
1163 It should match if the message is from the user him/herself."
1164 :group 'org-link-store
1165 :type 'regexp)
1167 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1168 "Non-nil means, storing a link to an Org file will use entry IDs.
1170 Note that before this variable is even considered, org-id must be loaded,
1171 so please customize `org-modules' and turn it on.
1173 The variable can have the following values:
1175 t Create an ID if needed to make a link to the current entry.
1177 create-if-interactive
1178 If `org-store-link' is called directly (interactively, as a user
1179 command), do create an ID to support the link. But when doing the
1180 job for remember, only use the ID if it already exists. The
1181 purpose of this setting is to avoid proliferation of unwanted
1182 IDs, just because you happen to be in an Org file when you
1183 call `org-remember' that automatically and preemptively
1184 creates a link. If you do want to get an ID link in a remember
1185 template to an entry not having an ID, create it first by
1186 explicitly creating a link to it, using `C-c C-l' first.
1188 create-if-interactive-and-no-custom-id
1189 Like create-if-interactive, but do not create an ID if there is
1190 a CUSTOM_ID property defined in the entry. This is the default.
1192 use-existing
1193 Use existing ID, do not create one.
1195 nil Never use an ID to make a link, instead link using a text search for
1196 the headline text."
1197 :group 'org-link-store
1198 :type '(choice
1199 (const :tag "Create ID to make link" t)
1200 (const :tag "Create if storing link interactively"
1201 create-if-interactive)
1202 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1203 create-if-interactive-and-no-custom-id)
1204 (const :tag "Only use existing" use-existing)
1205 (const :tag "Do not use ID to create link" nil)))
1207 (defcustom org-context-in-file-links t
1208 "Non-nil means, file links from `org-store-link' contain context.
1209 A search string will be added to the file name with :: as separator and
1210 used to find the context when the link is activated by the command
1211 `org-open-at-point'.
1212 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1213 negates this setting for the duration of the command."
1214 :group 'org-link-store
1215 :type 'boolean)
1217 (defcustom org-keep-stored-link-after-insertion nil
1218 "Non-nil means, keep link in list for entire session.
1220 The command `org-store-link' adds a link pointing to the current
1221 location to an internal list. These links accumulate during a session.
1222 The command `org-insert-link' can be used to insert links into any
1223 Org-mode file (offering completion for all stored links). When this
1224 option is nil, every link which has been inserted once using \\[org-insert-link]
1225 will be removed from the list, to make completing the unused links
1226 more efficient."
1227 :group 'org-link-store
1228 :type 'boolean)
1230 (defgroup org-link-follow nil
1231 "Options concerning following links in Org-mode."
1232 :tag "Org Follow Link"
1233 :group 'org-link)
1235 (defcustom org-link-translation-function nil
1236 "Function to translate links with different syntax to Org syntax.
1237 This can be used to translate links created for example by the Planner
1238 or emacs-wiki packages to Org syntax.
1239 The function must accept two parameters, a TYPE containing the link
1240 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1241 which is everything after the link protocol. It should return a cons
1242 with possibly modified values of type and path.
1243 Org contains a function for this, so if you set this variable to
1244 `org-translate-link-from-planner', you should be able follow many
1245 links created by planner."
1246 :group 'org-link-follow
1247 :type 'function)
1249 (defcustom org-follow-link-hook nil
1250 "Hook that is run after a link has been followed."
1251 :group 'org-link-follow
1252 :type 'hook)
1254 (defcustom org-tab-follows-link nil
1255 "Non-nil means, on links TAB will follow the link.
1256 Needs to be set before org.el is loaded.
1257 This really should not be used, it does not make sense, and the
1258 implementation is bad."
1259 :group 'org-link-follow
1260 :type 'boolean)
1262 (defcustom org-return-follows-link nil
1263 "Non-nil means, on links RET will follow the link.
1264 Needs to be set before org.el is loaded."
1265 :group 'org-link-follow
1266 :type 'boolean)
1268 (defcustom org-mouse-1-follows-link
1269 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1270 "Non-nil means, mouse-1 on a link will follow the link.
1271 A longer mouse click will still set point. Does not work on XEmacs.
1272 Needs to be set before org.el is loaded."
1273 :group 'org-link-follow
1274 :type 'boolean)
1276 (defcustom org-mark-ring-length 4
1277 "Number of different positions to be recorded in the ring
1278 Changing this requires a restart of Emacs to work correctly."
1279 :group 'org-link-follow
1280 :type 'integer)
1282 (defcustom org-link-frame-setup
1283 '((vm . vm-visit-folder-other-frame)
1284 (gnus . gnus-other-frame)
1285 (file . find-file-other-window))
1286 "Setup the frame configuration for following links.
1287 When following a link with Emacs, it may often be useful to display
1288 this link in another window or frame. This variable can be used to
1289 set this up for the different types of links.
1290 For VM, use any of
1291 `vm-visit-folder'
1292 `vm-visit-folder-other-frame'
1293 For Gnus, use any of
1294 `gnus'
1295 `gnus-other-frame'
1296 `org-gnus-no-new-news'
1297 For FILE, use any of
1298 `find-file'
1299 `find-file-other-window'
1300 `find-file-other-frame'
1301 For the calendar, use the variable `calendar-setup'.
1302 For BBDB, it is currently only possible to display the matches in
1303 another window."
1304 :group 'org-link-follow
1305 :type '(list
1306 (cons (const vm)
1307 (choice
1308 (const vm-visit-folder)
1309 (const vm-visit-folder-other-window)
1310 (const vm-visit-folder-other-frame)))
1311 (cons (const gnus)
1312 (choice
1313 (const gnus)
1314 (const gnus-other-frame)
1315 (const org-gnus-no-new-news)))
1316 (cons (const file)
1317 (choice
1318 (const find-file)
1319 (const find-file-other-window)
1320 (const find-file-other-frame)))))
1322 (defcustom org-display-internal-link-with-indirect-buffer nil
1323 "Non-nil means, use indirect buffer to display infile links.
1324 Activating internal links (from one location in a file to another location
1325 in the same file) normally just jumps to the location. When the link is
1326 activated with a C-u prefix (or with mouse-3), the link is displayed in
1327 another window. When this option is set, the other window actually displays
1328 an indirect buffer clone of the current buffer, to avoid any visibility
1329 changes to the current buffer."
1330 :group 'org-link-follow
1331 :type 'boolean)
1333 (defcustom org-open-non-existing-files nil
1334 "Non-nil means, `org-open-file' will open non-existing files.
1335 When nil, an error will be generated.
1336 This variable applies only to external applications because they
1337 might choke on non-existing files. If the link is to a file that
1338 will be openend in Emacs, the variable is ignored."
1339 :group 'org-link-follow
1340 :type 'boolean)
1342 (defcustom org-open-directory-means-index-dot-org nil
1343 "Non-nil means, a link to a directory really means to index.org.
1344 When nil, following a directory link will run dired or open a finder/explorer
1345 window on that directory."
1346 :group 'org-link-follow
1347 :type 'boolean)
1349 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1350 "Function and arguments to call for following mailto links.
1351 This is a list with the first element being a lisp function, and the
1352 remaining elements being arguments to the function. In string arguments,
1353 %a will be replaced by the address, and %s will be replaced by the subject
1354 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1355 :group 'org-link-follow
1356 :type '(choice
1357 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1358 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1359 (const :tag "message-mail" (message-mail "%a" "%s"))
1360 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1362 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1363 "Non-nil means, ask for confirmation before executing shell links.
1364 Shell links can be dangerous: just think about a link
1366 [[shell:rm -rf ~/*][Google Search]]
1368 This link would show up in your Org-mode document as \"Google Search\",
1369 but really it would remove your entire home directory.
1370 Therefore we advise against setting this variable to nil.
1371 Just change it to `y-or-n-p' if you want to confirm with a
1372 single keystroke rather than having to type \"yes\"."
1373 :group 'org-link-follow
1374 :type '(choice
1375 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1376 (const :tag "with y-or-n (faster)" y-or-n-p)
1377 (const :tag "no confirmation (dangerous)" nil)))
1379 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1380 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1381 Elisp links can be dangerous: just think about a link
1383 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1385 This link would show up in your Org-mode document as \"Google Search\",
1386 but really it would remove your entire home directory.
1387 Therefore we advise against setting this variable to nil.
1388 Just change it to `y-or-n-p' if you want to confirm with a
1389 single keystroke rather than having to type \"yes\"."
1390 :group 'org-link-follow
1391 :type '(choice
1392 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1393 (const :tag "with y-or-n (faster)" y-or-n-p)
1394 (const :tag "no confirmation (dangerous)" nil)))
1396 (defconst org-file-apps-defaults-gnu
1397 '((remote . emacs)
1398 (system . mailcap)
1399 (t . mailcap))
1400 "Default file applications on a UNIX or GNU/Linux system.
1401 See `org-file-apps'.")
1403 (defconst org-file-apps-defaults-macosx
1404 '((remote . emacs)
1405 (t . "open %s")
1406 (system . "open %s")
1407 ("ps.gz" . "gv %s")
1408 ("eps.gz" . "gv %s")
1409 ("dvi" . "xdvi %s")
1410 ("fig" . "xfig %s"))
1411 "Default file applications on a MacOS X system.
1412 The system \"open\" is known as a default, but we use X11 applications
1413 for some files for which the OS does not have a good default.
1414 See `org-file-apps'.")
1416 (defconst org-file-apps-defaults-windowsnt
1417 (list
1418 '(remote . emacs)
1419 (cons t
1420 (list (if (featurep 'xemacs)
1421 'mswindows-shell-execute
1422 'w32-shell-execute)
1423 "open" 'file))
1424 (cons 'system
1425 (list (if (featurep 'xemacs)
1426 'mswindows-shell-execute
1427 'w32-shell-execute)
1428 "open" 'file)))
1429 "Default file applications on a Windows NT system.
1430 The system \"open\" is used for most files.
1431 See `org-file-apps'.")
1433 (defcustom org-file-apps
1435 (auto-mode . emacs)
1436 ("\\.mm\\'" . default)
1437 ("\\.x?html?\\'" . default)
1438 ("\\.pdf\\'" . default)
1440 "External applications for opening `file:path' items in a document.
1441 Org-mode uses system defaults for different file types, but
1442 you can use this variable to set the application for a given file
1443 extension. The entries in this list are cons cells where the car identifies
1444 files and the cdr the corresponding command. Possible values for the
1445 file identifier are
1446 \"regex\" Regular expression matched against the file name. For backward
1447 compatibility, this can also be a string with only alphanumeric
1448 characters, which is then interpreted as an extension.
1449 `directory' Matches a directory
1450 `remote' Matches a remote file, accessible through tramp or efs.
1451 Remote files most likely should be visited through Emacs
1452 because external applications cannot handle such paths.
1453 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1454 so all files Emacs knows how to handle. Using this with
1455 command `emacs' will open most files in Emacs. Beware that this
1456 will also open html files inside Emacs, unless you add
1457 (\"html\" . default) to the list as well.
1458 t Default for files not matched by any of the other options.
1459 `system' The system command to open files, like `open' on Windows
1460 and Mac OS X, and mailcap under GNU/Linux. This is the command
1461 that will be selected if you call `C-c C-o' with a double
1462 `C-u C-u' prefix.
1464 Possible values for the command are:
1465 `emacs' The file will be visited by the current Emacs process.
1466 `default' Use the default application for this file type, which is the
1467 association for t in the list, most likely in the system-specific
1468 part.
1469 This can be used to overrule an unwanted setting in the
1470 system-specific variable.
1471 `system' Use the system command for opening files, like \"open\".
1472 This command is specified by the entry whose car is `system'.
1473 Most likely, the system-specific version of this variable
1474 does define this command, but you can overrule/replace it
1475 here.
1476 string A command to be executed by a shell; %s will be replaced
1477 by the path to the file.
1478 sexp A Lisp form which will be evaluated. The file path will
1479 be available in the Lisp variable `file'.
1480 For more examples, see the system specific constants
1481 `org-file-apps-defaults-macosx'
1482 `org-file-apps-defaults-windowsnt'
1483 `org-file-apps-defaults-gnu'."
1484 :group 'org-link-follow
1485 :type '(repeat
1486 (cons (choice :value ""
1487 (string :tag "Extension")
1488 (const :tag "System command to open files" system)
1489 (const :tag "Default for unrecognized files" t)
1490 (const :tag "Remote file" remote)
1491 (const :tag "Links to a directory" directory)
1492 (const :tag "Any files that have Emacs modes"
1493 auto-mode))
1494 (choice :value ""
1495 (const :tag "Visit with Emacs" emacs)
1496 (const :tag "Use default" default)
1497 (const :tag "Use the system command" system)
1498 (string :tag "Command")
1499 (sexp :tag "Lisp form")))))
1501 (defgroup org-refile nil
1502 "Options concerning refiling entries in Org-mode."
1503 :tag "Org Refile"
1504 :group 'org)
1506 (defcustom org-directory "~/org"
1507 "Directory with org files.
1508 This is just a default location to look for Org files. There is no need
1509 at all to put your files into this directory. It is only used in the
1510 following situations:
1512 1. When a remember template specifies a target file that is not an
1513 absolute path. The path will then be interpreted relative to
1514 `org-directory'
1515 2. When a remember note is filed away in an interactive way (when exiting the
1516 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1517 with `org-directory' as the default path."
1518 :group 'org-refile
1519 :group 'org-remember
1520 :type 'directory)
1522 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1523 "Default target for storing notes.
1524 Used by the hooks for remember.el. This can be a string, or nil to mean
1525 the value of `remember-data-file'.
1526 You can set this on a per-template basis with the variable
1527 `org-remember-templates'."
1528 :group 'org-refile
1529 :group 'org-remember
1530 :type '(choice
1531 (const :tag "Default from remember-data-file" nil)
1532 file))
1534 (defcustom org-goto-interface 'outline
1535 "The default interface to be used for `org-goto'.
1536 Allowed values are:
1537 outline The interface shows an outline of the relevant file
1538 and the correct heading is found by moving through
1539 the outline or by searching with incremental search.
1540 outline-path-completion Headlines in the current buffer are offered via
1541 completion. This is the interface also used by
1542 the refile command."
1543 :group 'org-refile
1544 :type '(choice
1545 (const :tag "Outline" outline)
1546 (const :tag "Outline-path-completion" outline-path-completion)))
1548 (defcustom org-goto-max-level 5
1549 "Maximum level to be considered when running org-goto with refile interface."
1550 :group 'org-refile
1551 :type 'integer)
1553 (defcustom org-reverse-note-order nil
1554 "Non-nil means, store new notes at the beginning of a file or entry.
1555 When nil, new notes will be filed to the end of a file or entry.
1556 This can also be a list with cons cells of regular expressions that
1557 are matched against file names, and values."
1558 :group 'org-remember
1559 :group 'org-refile
1560 :type '(choice
1561 (const :tag "Reverse always" t)
1562 (const :tag "Reverse never" nil)
1563 (repeat :tag "By file name regexp"
1564 (cons regexp boolean))))
1566 (defcustom org-refile-targets nil
1567 "Targets for refiling entries with \\[org-refile].
1568 This is list of cons cells. Each cell contains:
1569 - a specification of the files to be considered, either a list of files,
1570 or a symbol whose function or variable value will be used to retrieve
1571 a file name or a list of file names. If you use `org-agenda-files' for
1572 that, all agenda files will be scanned for targets. Nil means, consider
1573 headings in the current buffer.
1574 - A specification of how to find candidate refile targets. This may be
1575 any of:
1576 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1577 This tag has to be present in all target headlines, inheritance will
1578 not be considered.
1579 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1580 todo keyword.
1581 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1582 headlines that are refiling targets.
1583 - a cons cell (:level . N). Any headline of level N is considered a target.
1584 Note that, when `org-odd-levels-only' is set, level corresponds to
1585 order in hierarchy, not to the number of stars.
1586 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1587 Note that, when `org-odd-levels-only' is set, level corresponds to
1588 order in hierarchy, not to the number of stars.
1590 You can set the variable `org-refile-target-verify-function' to a function
1591 to verify each headline found by the simple critery above.
1593 When this variable is nil, all top-level headlines in the current buffer
1594 are used, equivalent to the value `((nil . (:level . 1))'."
1595 :group 'org-refile
1596 :type '(repeat
1597 (cons
1598 (choice :value org-agenda-files
1599 (const :tag "All agenda files" org-agenda-files)
1600 (const :tag "Current buffer" nil)
1601 (function) (variable) (file))
1602 (choice :tag "Identify target headline by"
1603 (cons :tag "Specific tag" (const :value :tag) (string))
1604 (cons :tag "TODO keyword" (const :value :todo) (string))
1605 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1606 (cons :tag "Level number" (const :value :level) (integer))
1607 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1609 (defcustom org-refile-target-verify-function nil
1610 "Function to verify if the headline at point should be a refile target.
1611 The function will be called without arguments, with point at the
1612 beginning of the headline. It should return t and leave point
1613 where it is if the headline is a valid target for refiling.
1615 If the target should not be selected, the function must return nil.
1616 In addition to this, it may move point to a place from where the search
1617 should be continued. For example, the function may decide that the entire
1618 subtree of the current entry should be excluded and move point to the end
1619 of the subtree."
1620 :group 'org-refile
1621 :type 'function)
1623 (defcustom org-refile-use-outline-path nil
1624 "Non-nil means, provide refile targets as paths.
1625 So a level 3 headline will be available as level1/level2/level3.
1627 When the value is `file', also include the file name (without directory)
1628 into the path. In this case, you can also stop the completion after
1629 the file name, to get entries inserted as top level in the file.
1631 When `full-file-path', include the full file path."
1632 :group 'org-refile
1633 :type '(choice
1634 (const :tag "Not" nil)
1635 (const :tag "Yes" t)
1636 (const :tag "Start with file name" file)
1637 (const :tag "Start with full file path" full-file-path)))
1639 (defcustom org-outline-path-complete-in-steps t
1640 "Non-nil means, complete the outline path in hierarchical steps.
1641 When Org-mode uses the refile interface to select an outline path
1642 \(see variable `org-refile-use-outline-path'), the completion of
1643 the path can be done is a single go, or if can be done in steps down
1644 the headline hierarchy. Going in steps is probably the best if you
1645 do not use a special completion package like `ido' or `icicles'.
1646 However, when using these packages, going in one step can be very
1647 fast, while still showing the whole path to the entry."
1648 :group 'org-refile
1649 :type 'boolean)
1651 (defcustom org-refile-allow-creating-parent-nodes nil
1652 "Non-nil means, allow to create new nodes as refile targets.
1653 New nodes are then created by adding \"/new node name\" to the completion
1654 of an existing node. When the value of this variable is `confirm',
1655 new node creation must be confirmed by the user (recommended)
1656 When nil, the completion must match an existing entry.
1658 Note that, if the new heading is not seen by the criteria
1659 listed in `org-refile-targets', multiple instances of the same
1660 heading would be created by trying again to file under the new
1661 heading."
1662 :group 'org-refile
1663 :type '(choice
1664 (const :tag "Never" nil)
1665 (const :tag "Always" t)
1666 (const :tag "Prompt for confirmation" confirm)))
1668 (defgroup org-todo nil
1669 "Options concerning TODO items in Org-mode."
1670 :tag "Org TODO"
1671 :group 'org)
1673 (defgroup org-progress nil
1674 "Options concerning Progress logging in Org-mode."
1675 :tag "Org Progress"
1676 :group 'org-time)
1678 (defvar org-todo-interpretation-widgets
1680 (:tag "Sequence (cycling hits every state)" sequence)
1681 (:tag "Type (cycling directly to DONE)" type))
1682 "The available interpretation symbols for customizing
1683 `org-todo-keywords'.
1684 Interested libraries should add to this list.")
1686 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1687 "List of TODO entry keyword sequences and their interpretation.
1688 \\<org-mode-map>This is a list of sequences.
1690 Each sequence starts with a symbol, either `sequence' or `type',
1691 indicating if the keywords should be interpreted as a sequence of
1692 action steps, or as different types of TODO items. The first
1693 keywords are states requiring action - these states will select a headline
1694 for inclusion into the global TODO list Org-mode produces. If one of
1695 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1696 signify that no further action is necessary. If \"|\" is not found,
1697 the last keyword is treated as the only DONE state of the sequence.
1699 The command \\[org-todo] cycles an entry through these states, and one
1700 additional state where no keyword is present. For details about this
1701 cycling, see the manual.
1703 TODO keywords and interpretation can also be set on a per-file basis with
1704 the special #+SEQ_TODO and #+TYP_TODO lines.
1706 Each keyword can optionally specify a character for fast state selection
1707 \(in combination with the variable `org-use-fast-todo-selection')
1708 and specifiers for state change logging, using the same syntax
1709 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1710 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1711 indicates to record a time stamp each time this state is selected.
1713 Each keyword may also specify if a timestamp or a note should be
1714 recorded when entering or leaving the state, by adding additional
1715 characters in the parenthesis after the keyword. This looks like this:
1716 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1717 record only the time of the state change. With X and Y being either
1718 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1719 Y when leaving the state if and only if the *target* state does not
1720 define X. You may omit any of the fast-selection key or X or /Y,
1721 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1723 For backward compatibility, this variable may also be just a list
1724 of keywords - in this case the interpretation (sequence or type) will be
1725 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1726 :group 'org-todo
1727 :group 'org-keywords
1728 :type '(choice
1729 (repeat :tag "Old syntax, just keywords"
1730 (string :tag "Keyword"))
1731 (repeat :tag "New syntax"
1732 (cons
1733 (choice
1734 :tag "Interpretation"
1735 ;;Quick and dirty way to see
1736 ;;`org-todo-interpretations'. This takes the
1737 ;;place of item arguments
1738 :convert-widget
1739 (lambda (widget)
1740 (widget-put widget
1741 :args (mapcar
1742 #'(lambda (x)
1743 (widget-convert
1744 (cons 'const x)))
1745 org-todo-interpretation-widgets))
1746 widget))
1747 (repeat
1748 (string :tag "Keyword"))))))
1750 (defvar org-todo-keywords-1 nil
1751 "All TODO and DONE keywords active in a buffer.")
1752 (make-variable-buffer-local 'org-todo-keywords-1)
1753 (defvar org-todo-keywords-for-agenda nil)
1754 (defvar org-done-keywords-for-agenda nil)
1755 (defvar org-drawers-for-agenda nil)
1756 (defvar org-todo-keyword-alist-for-agenda nil)
1757 (defvar org-tag-alist-for-agenda nil)
1758 (defvar org-agenda-contributing-files nil)
1759 (defvar org-not-done-keywords nil)
1760 (make-variable-buffer-local 'org-not-done-keywords)
1761 (defvar org-done-keywords nil)
1762 (make-variable-buffer-local 'org-done-keywords)
1763 (defvar org-todo-heads nil)
1764 (make-variable-buffer-local 'org-todo-heads)
1765 (defvar org-todo-sets nil)
1766 (make-variable-buffer-local 'org-todo-sets)
1767 (defvar org-todo-log-states nil)
1768 (make-variable-buffer-local 'org-todo-log-states)
1769 (defvar org-todo-kwd-alist nil)
1770 (make-variable-buffer-local 'org-todo-kwd-alist)
1771 (defvar org-todo-key-alist nil)
1772 (make-variable-buffer-local 'org-todo-key-alist)
1773 (defvar org-todo-key-trigger nil)
1774 (make-variable-buffer-local 'org-todo-key-trigger)
1776 (defcustom org-todo-interpretation 'sequence
1777 "Controls how TODO keywords are interpreted.
1778 This variable is in principle obsolete and is only used for
1779 backward compatibility, if the interpretation of todo keywords is
1780 not given already in `org-todo-keywords'. See that variable for
1781 more information."
1782 :group 'org-todo
1783 :group 'org-keywords
1784 :type '(choice (const sequence)
1785 (const type)))
1787 (defcustom org-use-fast-todo-selection t
1788 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1789 This variable describes if and under what circumstances the cycling
1790 mechanism for TODO keywords will be replaced by a single-key, direct
1791 selection scheme.
1793 When nil, fast selection is never used.
1795 When the symbol `prefix', it will be used when `org-todo' is called with
1796 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1797 in an agenda buffer.
1799 When t, fast selection is used by default. In this case, the prefix
1800 argument forces cycling instead.
1802 In all cases, the special interface is only used if access keys have actually
1803 been assigned by the user, i.e. if keywords in the configuration are followed
1804 by a letter in parenthesis, like TODO(t)."
1805 :group 'org-todo
1806 :type '(choice
1807 (const :tag "Never" nil)
1808 (const :tag "By default" t)
1809 (const :tag "Only with C-u C-c C-t" prefix)))
1811 (defcustom org-provide-todo-statistics t
1812 "Non-nil means, update todo statistics after insert and toggle.
1813 ALL-HEADLINES means update todo statistics by including headlines
1814 with no TODO keyword as well, counting them as not done.
1815 A list of TODO keywords means the same, but skip keywords that are
1816 not in this list.
1818 When this is set, todo statistics is updated in the parent of the
1819 current entry each time a todo state is changed."
1820 :group 'org-todo
1821 :type '(choice
1822 (const :tag "Yes, only for TODO entries" t)
1823 (const :tag "Yes, including all entries" 'all-headlines)
1824 (repeat :tag "Yes, for TODOs in this list"
1825 (string :tag "TODO keyword"))
1826 (other :tag "No TODO statistics" nil)))
1828 (defcustom org-hierarchical-todo-statistics t
1829 "Non-nil means, TODO statistics covers just direct children.
1830 When nil, all entries in the subtree are considered.
1831 This has only an effect if `org-provide-todo-statistics' is set.
1832 To set this to nil for only a single subtree, use a COOKIE_DATA
1833 property and include the word \"recursive\" into the value."
1834 :group 'org-todo
1835 :type 'boolean)
1837 (defcustom org-after-todo-state-change-hook nil
1838 "Hook which is run after the state of a TODO item was changed.
1839 The new state (a string with a TODO keyword, or nil) is available in the
1840 Lisp variable `state'."
1841 :group 'org-todo
1842 :type 'hook)
1844 (defvar org-blocker-hook nil
1845 "Hook for functions that are allowed to block a state change.
1847 Each function gets as its single argument a property list, see
1848 `org-trigger-hook' for more information about this list.
1850 If any of the functions in this hook returns nil, the state change
1851 is blocked.")
1853 (defvar org-trigger-hook nil
1854 "Hook for functions that are triggered by a state change.
1856 Each function gets as its single argument a property list with at least
1857 the following elements:
1859 (:type type-of-change :position pos-at-entry-start
1860 :from old-state :to new-state)
1862 Depending on the type, more properties may be present.
1864 This mechanism is currently implemented for:
1866 TODO state changes
1867 ------------------
1868 :type todo-state-change
1869 :from previous state (keyword as a string), or nil, or a symbol
1870 'todo' or 'done', to indicate the general type of state.
1871 :to new state, like in :from")
1873 (defcustom org-enforce-todo-dependencies nil
1874 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1875 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1876 be blocked if any prior sibling is not yet done.
1877 Finally, if the parent is blocked because of ordered siblings of its own,
1878 the child will also be blocked.
1879 This variable needs to be set before org.el is loaded, and you need to
1880 restart Emacs after a change to make the change effective. The only way
1881 to change is while Emacs is running is through the customize interface."
1882 :set (lambda (var val)
1883 (set var val)
1884 (if val
1885 (add-hook 'org-blocker-hook
1886 'org-block-todo-from-children-or-siblings-or-parent)
1887 (remove-hook 'org-blocker-hook
1888 'org-block-todo-from-children-or-siblings-or-parent)))
1889 :group 'org-todo
1890 :type 'boolean)
1892 (defcustom org-enforce-todo-checkbox-dependencies nil
1893 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1894 When this is nil, checkboxes have no influence on switching TODO states.
1895 When non-nil, you first need to check off all check boxes before the TODO
1896 entry can be switched to DONE.
1897 This variable needs to be set before org.el is loaded, and you need to
1898 restart Emacs after a change to make the change effective. The only way
1899 to change is while Emacs is running is through the customize interface."
1900 :set (lambda (var val)
1901 (set var val)
1902 (if val
1903 (add-hook 'org-blocker-hook
1904 'org-block-todo-from-checkboxes)
1905 (remove-hook 'org-blocker-hook
1906 'org-block-todo-from-checkboxes)))
1907 :group 'org-todo
1908 :type 'boolean)
1910 (defcustom org-treat-insert-todo-heading-as-state-change nil
1911 "Non-nil means, inserting a TODO heading is treated as state change.
1912 So when the command \\[org-insert-todo-heading] is used, state change
1913 logging will apply if appropriate. When nil, the new TODO item will
1914 be inserted directly, and no logging will take place."
1915 :group 'org-todo
1916 :type 'boolean)
1918 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1919 "Non-nil means, switching TODO states with S-cursor counts as state change.
1920 This is the default behavior. However, setting this to nil allows a
1921 convenient way to select a TODO state and bypass any logging associated
1922 with that."
1923 :group 'org-todo
1924 :type 'boolean)
1926 (defcustom org-todo-state-tags-triggers nil
1927 "Tag changes that should be triggered by TODO state changes.
1928 This is a list. Each entry is
1930 (state-change (tag . flag) .......)
1932 State-change can be a string with a state, and empty string to indicate the
1933 state that has no TODO keyword, or it can be one of the symbols `todo'
1934 or `done', meaning any not-done or done state, respectively."
1935 :group 'org-todo
1936 :group 'org-tags
1937 :type '(repeat
1938 (cons (choice :tag "When changing to"
1939 (const :tag "Not-done state" todo)
1940 (const :tag "Done state" done)
1941 (string :tag "State"))
1942 (repeat
1943 (cons :tag "Tag action"
1944 (string :tag "Tag")
1945 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1947 (defcustom org-log-done nil
1948 "Information to record when a task moves to the DONE state.
1950 Possible values are:
1952 nil Don't add anything, just change the keyword
1953 time Add a time stamp to the task
1954 note Prompt a closing note and add it with template `org-log-note-headings'
1956 This option can also be set with on a per-file-basis with
1958 #+STARTUP: nologdone
1959 #+STARTUP: logdone
1960 #+STARTUP: lognotedone
1962 You can have local logging settings for a subtree by setting the LOGGING
1963 property to one or more of these keywords."
1964 :group 'org-todo
1965 :group 'org-progress
1966 :type '(choice
1967 (const :tag "No logging" nil)
1968 (const :tag "Record CLOSED timestamp" time)
1969 (const :tag "Record CLOSED timestamp with closing note." note)))
1971 ;; Normalize old uses of org-log-done.
1972 (cond
1973 ((eq org-log-done t) (setq org-log-done 'time))
1974 ((and (listp org-log-done) (memq 'done org-log-done))
1975 (setq org-log-done 'note)))
1977 (defcustom org-log-note-clock-out nil
1978 "Non-nil means, record a note when clocking out of an item.
1979 This can also be configured on a per-file basis by adding one of
1980 the following lines anywhere in the buffer:
1982 #+STARTUP: lognoteclock-out
1983 #+STARTUP: nolognoteclock-out"
1984 :group 'org-todo
1985 :group 'org-progress
1986 :type 'boolean)
1988 (defcustom org-log-done-with-time t
1989 "Non-nil means, the CLOSED time stamp will contain date and time.
1990 When nil, only the date will be recorded."
1991 :group 'org-progress
1992 :type 'boolean)
1994 (defcustom org-log-note-headings
1995 '((done . "CLOSING NOTE %t")
1996 (state . "State %-12s from %-12S %t")
1997 (note . "Note taken on %t")
1998 (clock-out . ""))
1999 "Headings for notes added to entries.
2000 The value is an alist, with the car being a symbol indicating the note
2001 context, and the cdr is the heading to be used. The heading may also be the
2002 empty string.
2003 %t in the heading will be replaced by a time stamp.
2004 %s will be replaced by the new TODO state, in double quotes.
2005 %S will be replaced by the old TODO state, in double quotes.
2006 %u will be replaced by the user name.
2007 %U will be replaced by the full user name."
2008 :group 'org-todo
2009 :group 'org-progress
2010 :type '(list :greedy t
2011 (cons (const :tag "Heading when closing an item" done) string)
2012 (cons (const :tag
2013 "Heading when changing todo state (todo sequence only)"
2014 state) string)
2015 (cons (const :tag "Heading when just taking a note" note) string)
2016 (cons (const :tag "Heading when clocking out" clock-out) string)))
2018 (unless (assq 'note org-log-note-headings)
2019 (push '(note . "%t") org-log-note-headings))
2021 (defcustom org-log-into-drawer nil
2022 "Non-nil means, insert state change notes and time stamps into a drawer.
2023 When nil, state changes notes will be inserted after the headline and
2024 any scheduling and clock lines, but not inside a drawer.
2026 The value of this variable should be the name of the drawer to use.
2027 LOGBOOK is proposed at the default drawer for this purpose, you can
2028 also set this to a string to define the drawer of your choice.
2030 A value of t is also allowed, representing \"LOGBOOK\".
2032 If this variable is set, `org-log-state-notes-insert-after-drawers'
2033 will be ignored.
2035 You can set the property LOG_INTO_DRAWER to overrule this setting for
2036 a subtree."
2037 :group 'org-todo
2038 :group 'org-progress
2039 :type '(choice
2040 (const :tag "Not into a drawer" nil)
2041 (const :tag "LOGBOOK" t)
2042 (string :tag "Other")))
2044 (if (fboundp 'defvaralias)
2045 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2047 (defun org-log-into-drawer ()
2048 "Return the value of `org-log-into-drawer', but let properties overrule.
2049 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2050 used instead of the default value."
2051 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2052 (cond
2053 ((or (not p) (equal p "nil")) org-log-into-drawer)
2054 ((equal p "t") "LOGBOOK")
2055 (t p))))
2057 (defcustom org-log-state-notes-insert-after-drawers nil
2058 "Non-nil means, insert state change notes after any drawers in entry.
2059 Only the drawers that *immediately* follow the headline and the
2060 deadline/scheduled line are skipped.
2061 When nil, insert notes right after the heading and perhaps the line
2062 with deadline/scheduling if present.
2064 This variable will have no effect if `org-log-into-drawer' is
2065 set."
2066 :group 'org-todo
2067 :group 'org-progress
2068 :type 'boolean)
2070 (defcustom org-log-states-order-reversed t
2071 "Non-nil means, the latest state change note will be directly after heading.
2072 When nil, the notes will be orderer according to time."
2073 :group 'org-todo
2074 :group 'org-progress
2075 :type 'boolean)
2077 (defcustom org-log-repeat 'time
2078 "Non-nil means, record moving through the DONE state when triggering repeat.
2079 An auto-repeating task is immediately switched back to TODO when
2080 marked DONE. If you are not logging state changes (by adding \"@\"
2081 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2082 record a closing note, there will be no record of the task moving
2083 through DONE. This variable forces taking a note anyway.
2085 nil Don't force a record
2086 time Record a time stamp
2087 note Record a note
2089 This option can also be set with on a per-file-basis with
2091 #+STARTUP: logrepeat
2092 #+STARTUP: lognoterepeat
2093 #+STARTUP: nologrepeat
2095 You can have local logging settings for a subtree by setting the LOGGING
2096 property to one or more of these keywords."
2097 :group 'org-todo
2098 :group 'org-progress
2099 :type '(choice
2100 (const :tag "Don't force a record" nil)
2101 (const :tag "Force recording the DONE state" time)
2102 (const :tag "Force recording a note with the DONE state" note)))
2105 (defgroup org-priorities nil
2106 "Priorities in Org-mode."
2107 :tag "Org Priorities"
2108 :group 'org-todo)
2110 (defcustom org-enable-priority-commands t
2111 "Non-nil means, priority commands are active.
2112 When nil, these commands will be disabled, so that you never accidentally
2113 set a priority."
2114 :group 'org-priorities
2115 :type 'boolean)
2117 (defcustom org-highest-priority ?A
2118 "The highest priority of TODO items. A character like ?A, ?B etc.
2119 Must have a smaller ASCII number than `org-lowest-priority'."
2120 :group 'org-priorities
2121 :type 'character)
2123 (defcustom org-lowest-priority ?C
2124 "The lowest priority of TODO items. A character like ?A, ?B etc.
2125 Must have a larger ASCII number than `org-highest-priority'."
2126 :group 'org-priorities
2127 :type 'character)
2129 (defcustom org-default-priority ?B
2130 "The default priority of TODO items.
2131 This is the priority an item get if no explicit priority is given."
2132 :group 'org-priorities
2133 :type 'character)
2135 (defcustom org-priority-start-cycle-with-default t
2136 "Non-nil means, start with default priority when starting to cycle.
2137 When this is nil, the first step in the cycle will be (depending on the
2138 command used) one higher or lower that the default priority."
2139 :group 'org-priorities
2140 :type 'boolean)
2142 (defgroup org-time nil
2143 "Options concerning time stamps and deadlines in Org-mode."
2144 :tag "Org Time"
2145 :group 'org)
2147 (defcustom org-insert-labeled-timestamps-at-point nil
2148 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2149 When nil, these labeled time stamps are forces into the second line of an
2150 entry, just after the headline. When scheduling from the global TODO list,
2151 the time stamp will always be forced into the second line."
2152 :group 'org-time
2153 :type 'boolean)
2155 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2156 "Formats for `format-time-string' which are used for time stamps.
2157 It is not recommended to change this constant.")
2159 (defcustom org-time-stamp-rounding-minutes '(0 5)
2160 "Number of minutes to round time stamps to.
2161 These are two values, the first applies when first creating a time stamp.
2162 The second applies when changing it with the commands `S-up' and `S-down'.
2163 When changing the time stamp, this means that it will change in steps
2164 of N minutes, as given by the second value.
2166 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2167 numbers should be factors of 60, so for example 5, 10, 15.
2169 When this is larger than 1, you can still force an exact time-stamp by using
2170 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2171 and by using a prefix arg to `S-up/down' to specify the exact number
2172 of minutes to shift."
2173 :group 'org-time
2174 :get '(lambda (var) ; Make sure all entries have 5 elements
2175 (if (integerp (default-value var))
2176 (list (default-value var) 5)
2177 (default-value var)))
2178 :type '(list
2179 (integer :tag "when inserting times")
2180 (integer :tag "when modifying times")))
2182 ;; Normalize old customizations of this variable.
2183 (when (integerp org-time-stamp-rounding-minutes)
2184 (setq org-time-stamp-rounding-minutes
2185 (list org-time-stamp-rounding-minutes
2186 org-time-stamp-rounding-minutes)))
2188 (defcustom org-display-custom-times nil
2189 "Non-nil means, overlay custom formats over all time stamps.
2190 The formats are defined through the variable `org-time-stamp-custom-formats'.
2191 To turn this on on a per-file basis, insert anywhere in the file:
2192 #+STARTUP: customtime"
2193 :group 'org-time
2194 :set 'set-default
2195 :type 'sexp)
2196 (make-variable-buffer-local 'org-display-custom-times)
2198 (defcustom org-time-stamp-custom-formats
2199 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2200 "Custom formats for time stamps. See `format-time-string' for the syntax.
2201 These are overlayed over the default ISO format if the variable
2202 `org-display-custom-times' is set. Time like %H:%M should be at the
2203 end of the second format. The custom formats are also honored by export
2204 commands, if custom time display is turned on at the time of export."
2205 :group 'org-time
2206 :type 'sexp)
2208 (defun org-time-stamp-format (&optional long inactive)
2209 "Get the right format for a time string."
2210 (let ((f (if long (cdr org-time-stamp-formats)
2211 (car org-time-stamp-formats))))
2212 (if inactive
2213 (concat "[" (substring f 1 -1) "]")
2214 f)))
2216 (defcustom org-time-clocksum-format "%d:%02d"
2217 "The format string used when creating CLOCKSUM lines, or when
2218 org-mode generates a time duration."
2219 :group 'org-time
2220 :type 'string)
2222 (defcustom org-time-clocksum-use-fractional nil
2223 "If non-nil, \\[org-clock-display] uses fractional times.
2224 org-mode generates a time duration."
2225 :group 'org-time
2226 :type 'boolean)
2228 (defcustom org-time-clocksum-fractional-format "%.2f"
2229 "The format string used when creating CLOCKSUM lines, or when
2230 org-mode generates a time duration."
2231 :group 'org-time
2232 :type 'string)
2234 (defcustom org-deadline-warning-days 14
2235 "No. of days before expiration during which a deadline becomes active.
2236 This variable governs the display in sparse trees and in the agenda.
2237 When 0 or negative, it means use this number (the absolute value of it)
2238 even if a deadline has a different individual lead time specified.
2240 Custom commands can set this variable in the options section."
2241 :group 'org-time
2242 :group 'org-agenda-daily/weekly
2243 :type 'integer)
2245 (defcustom org-read-date-prefer-future t
2246 "Non-nil means, assume future for incomplete date input from user.
2247 This affects the following situations:
2248 1. The user gives a month but not a year.
2249 For example, if it is april and you enter \"feb 2\", this will be read
2250 as feb 2, *next* year. \"May 5\", however, will be this year.
2251 2. The user gives a day, but no month.
2252 For example, if today is the 15th, and you enter \"3\", Org-mode will
2253 read this as the third of *next* month. However, if you enter \"17\",
2254 it will be considered as *this* month.
2256 If you set this variable to the symbol `time', then also the following
2257 will work:
2259 3. If the user gives a time, but no day. If the time is before now,
2260 to will be interpreted as tomorrow.
2262 Currently none of this works for ISO week specifications.
2264 When this option is nil, the current day, month and year will always be
2265 used as defaults."
2266 :group 'org-time
2267 :type '(choice
2268 (const :tag "Never" nil)
2269 (const :tag "Check month and day" t)
2270 (const :tag "Check month, day, and time" time)))
2272 (defcustom org-read-date-display-live t
2273 "Non-nil means, display current interpretation of date prompt live.
2274 This display will be in an overlay, in the minibuffer."
2275 :group 'org-time
2276 :type 'boolean)
2278 (defcustom org-read-date-popup-calendar t
2279 "Non-nil means, pop up a calendar when prompting for a date.
2280 In the calendar, the date can be selected with mouse-1. However, the
2281 minibuffer will also be active, and you can simply enter the date as well.
2282 When nil, only the minibuffer will be available."
2283 :group 'org-time
2284 :type 'boolean)
2285 (if (fboundp 'defvaralias)
2286 (defvaralias 'org-popup-calendar-for-date-prompt
2287 'org-read-date-popup-calendar))
2289 (defcustom org-read-date-minibuffer-setup-hook nil
2290 "Hook to be used to set up keys for the date/time interface.
2291 Add key definitions to `minibuffer-local-map', which will be a temporary
2292 copy."
2293 :group 'org-time
2294 :type 'hook)
2296 (defcustom org-extend-today-until 0
2297 "The hour when your day really ends. Must be an integer.
2298 This has influence for the following applications:
2299 - When switching the agenda to \"today\". It it is still earlier than
2300 the time given here, the day recognized as TODAY is actually yesterday.
2301 - When a date is read from the user and it is still before the time given
2302 here, the current date and time will be assumed to be yesterday, 23:59.
2303 Also, timestamps inserted in remember templates follow this rule.
2305 IMPORTANT: This is a feature whose implementation is and likely will
2306 remain incomplete. Really, it is only here because past midnight seems to
2307 be the favorite working time of John Wiegley :-)"
2308 :group 'org-time
2309 :type 'integer)
2311 (defcustom org-edit-timestamp-down-means-later nil
2312 "Non-nil means, S-down will increase the time in a time stamp.
2313 When nil, S-up will increase."
2314 :group 'org-time
2315 :type 'boolean)
2317 (defcustom org-calendar-follow-timestamp-change t
2318 "Non-nil means, make the calendar window follow timestamp changes.
2319 When a timestamp is modified and the calendar window is visible, it will be
2320 moved to the new date."
2321 :group 'org-time
2322 :type 'boolean)
2324 (defgroup org-tags nil
2325 "Options concerning tags in Org-mode."
2326 :tag "Org Tags"
2327 :group 'org)
2329 (defcustom org-tag-alist nil
2330 "List of tags allowed in Org-mode files.
2331 When this list is nil, Org-mode will base TAG input on what is already in the
2332 buffer.
2333 The value of this variable is an alist, the car of each entry must be a
2334 keyword as a string, the cdr may be a character that is used to select
2335 that tag through the fast-tag-selection interface.
2336 See the manual for details."
2337 :group 'org-tags
2338 :type '(repeat
2339 (choice
2340 (cons (string :tag "Tag name")
2341 (character :tag "Access char"))
2342 (list :tag "Start radio group"
2343 (const :startgroup)
2344 (option (string :tag "Group description")))
2345 (list :tag "End radio group"
2346 (const :endgroup)
2347 (option (string :tag "Group description")))
2348 (const :tag "New line" (:newline)))))
2350 (defcustom org-tag-persistent-alist nil
2351 "List of tags that will always appear in all Org-mode files.
2352 This is in addition to any in buffer settings or customizations
2353 of `org-tag-alist'.
2354 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2355 The value of this variable is an alist, the car of each entry must be a
2356 keyword as a string, the cdr may be a character that is used to select
2357 that tag through the fast-tag-selection interface.
2358 See the manual for details.
2359 To disable these tags on a per-file basis, insert anywhere in the file:
2360 #+STARTUP: noptag"
2361 :group 'org-tags
2362 :type '(repeat
2363 (choice
2364 (cons (string :tag "Tag name")
2365 (character :tag "Access char"))
2366 (const :tag "Start radio group" (:startgroup))
2367 (const :tag "End radio group" (:endgroup))
2368 (const :tag "New line" (:newline)))))
2370 (defvar org-file-tags nil
2371 "List of tags that can be inherited by all entries in the file.
2372 The tags will be inherited if the variable `org-use-tag-inheritance'
2373 says they should be.
2374 This variable is populated from #+FILETAGS lines.")
2376 (defcustom org-use-fast-tag-selection 'auto
2377 "Non-nil means, use fast tag selection scheme.
2378 This is a special interface to select and deselect tags with single keys.
2379 When nil, fast selection is never used.
2380 When the symbol `auto', fast selection is used if and only if selection
2381 characters for tags have been configured, either through the variable
2382 `org-tag-alist' or through a #+TAGS line in the buffer.
2383 When t, fast selection is always used and selection keys are assigned
2384 automatically if necessary."
2385 :group 'org-tags
2386 :type '(choice
2387 (const :tag "Always" t)
2388 (const :tag "Never" nil)
2389 (const :tag "When selection characters are configured" 'auto)))
2391 (defcustom org-fast-tag-selection-single-key nil
2392 "Non-nil means, fast tag selection exits after first change.
2393 When nil, you have to press RET to exit it.
2394 During fast tag selection, you can toggle this flag with `C-c'.
2395 This variable can also have the value `expert'. In this case, the window
2396 displaying the tags menu is not even shown, until you press C-c again."
2397 :group 'org-tags
2398 :type '(choice
2399 (const :tag "No" nil)
2400 (const :tag "Yes" t)
2401 (const :tag "Expert" expert)))
2403 (defvar org-fast-tag-selection-include-todo nil
2404 "Non-nil means, fast tags selection interface will also offer TODO states.
2405 This is an undocumented feature, you should not rely on it.")
2407 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2408 "The column to which tags should be indented in a headline.
2409 If this number is positive, it specifies the column. If it is negative,
2410 it means that the tags should be flushright to that column. For example,
2411 -80 works well for a normal 80 character screen."
2412 :group 'org-tags
2413 :type 'integer)
2415 (defcustom org-auto-align-tags t
2416 "Non-nil means, realign tags after pro/demotion of TODO state change.
2417 These operations change the length of a headline and therefore shift
2418 the tags around. With this options turned on, after each such operation
2419 the tags are again aligned to `org-tags-column'."
2420 :group 'org-tags
2421 :type 'boolean)
2423 (defcustom org-use-tag-inheritance t
2424 "Non-nil means, tags in levels apply also for sublevels.
2425 When nil, only the tags directly given in a specific line apply there.
2426 This may also be a list of tags that should be inherited, or a regexp that
2427 matches tags that should be inherited. Additional control is possible
2428 with the variable `org-tags-exclude-from-inheritance' which gives an
2429 explicit list of tags to be excluded from inheritance., even if the value of
2430 `org-use-tag-inheritance' would select it for inheritance.
2432 If this option is t, a match early-on in a tree can lead to a large
2433 number of matches in the subtree when constructing the agenda or creating
2434 a sparse tree. If you only want to see the first match in a tree during
2435 a search, check out the variable `org-tags-match-list-sublevels'."
2436 :group 'org-tags
2437 :type '(choice
2438 (const :tag "Not" nil)
2439 (const :tag "Always" t)
2440 (repeat :tag "Specific tags" (string :tag "Tag"))
2441 (regexp :tag "Tags matched by regexp")))
2443 (defcustom org-tags-exclude-from-inheritance nil
2444 "List of tags that should never be inherited.
2445 This is a way to exclude a few tags from inheritance. For way to do
2446 the opposite, to actively allow inheritance for selected tags,
2447 see the variable `org-use-tag-inheritance'."
2448 :group 'org-tags
2449 :type '(repeat (string :tag "Tag")))
2451 (defun org-tag-inherit-p (tag)
2452 "Check if TAG is one that should be inherited."
2453 (cond
2454 ((member tag org-tags-exclude-from-inheritance) nil)
2455 ((eq org-use-tag-inheritance t) t)
2456 ((not org-use-tag-inheritance) nil)
2457 ((stringp org-use-tag-inheritance)
2458 (string-match org-use-tag-inheritance tag))
2459 ((listp org-use-tag-inheritance)
2460 (member tag org-use-tag-inheritance))
2461 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2463 (defcustom org-tags-match-list-sublevels t
2464 "Non-nil means list also sublevels of headlines matching a search.
2465 This variable applies to tags/property searches, and also to stuck
2466 projects because this search is based on a tags match as well.
2468 When set to the symbol `indented', sublevels are indented with
2469 leading dots.
2471 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2472 the sublevels of a headline matching a tag search often also match
2473 the same search. Listing all of them can create very long lists.
2474 Setting this variable to nil causes subtrees of a match to be skipped.
2476 This variable is semi-obsolete and probably should always be true. It
2477 is better to limit inheritance to certain tags using the variables
2478 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2479 :group 'org-tags
2480 :type '(choice
2481 (const :tag "No, don't list them" nil)
2482 (const :tag "Yes, do list them" t)
2483 (const :tag "List them, indented with leading dots" indented)))
2485 (defcustom org-tags-sort-function nil
2486 "When set, tags are sorted using this function as a comparator"
2487 :group 'org-tags
2488 :type '(choice
2489 (const :tag "No sorting" nil)
2490 (const :tag "Alphabetical" string<)
2491 (const :tag "Reverse alphabetical" string>)
2492 (function :tag "Custom function" nil)))
2494 (defvar org-tags-history nil
2495 "History of minibuffer reads for tags.")
2496 (defvar org-last-tags-completion-table nil
2497 "The last used completion table for tags.")
2498 (defvar org-after-tags-change-hook nil
2499 "Hook that is run after the tags in a line have changed.")
2501 (defgroup org-properties nil
2502 "Options concerning properties in Org-mode."
2503 :tag "Org Properties"
2504 :group 'org)
2506 (defcustom org-property-format "%-10s %s"
2507 "How property key/value pairs should be formatted by `indent-line'.
2508 When `indent-line' hits a property definition, it will format the line
2509 according to this format, mainly to make sure that the values are
2510 lined-up with respect to each other."
2511 :group 'org-properties
2512 :type 'string)
2514 (defcustom org-use-property-inheritance nil
2515 "Non-nil means, properties apply also for sublevels.
2517 This setting is chiefly used during property searches. Turning it on can
2518 cause significant overhead when doing a search, which is why it is not
2519 on by default.
2521 When nil, only the properties directly given in the current entry count.
2522 When t, every property is inherited. The value may also be a list of
2523 properties that should have inheritance, or a regular expression matching
2524 properties that should be inherited.
2526 However, note that some special properties use inheritance under special
2527 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2528 and the properties ending in \"_ALL\" when they are used as descriptor
2529 for valid values of a property.
2531 Note for programmers:
2532 When querying an entry with `org-entry-get', you can control if inheritance
2533 should be used. By default, `org-entry-get' looks only at the local
2534 properties. You can request inheritance by setting the inherit argument
2535 to t (to force inheritance) or to `selective' (to respect the setting
2536 in this variable)."
2537 :group 'org-properties
2538 :type '(choice
2539 (const :tag "Not" nil)
2540 (const :tag "Always" t)
2541 (repeat :tag "Specific properties" (string :tag "Property"))
2542 (regexp :tag "Properties matched by regexp")))
2544 (defun org-property-inherit-p (property)
2545 "Check if PROPERTY is one that should be inherited."
2546 (cond
2547 ((eq org-use-property-inheritance t) t)
2548 ((not org-use-property-inheritance) nil)
2549 ((stringp org-use-property-inheritance)
2550 (string-match org-use-property-inheritance property))
2551 ((listp org-use-property-inheritance)
2552 (member property org-use-property-inheritance))
2553 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2555 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2556 "The default column format, if no other format has been defined.
2557 This variable can be set on the per-file basis by inserting a line
2559 #+COLUMNS: %25ITEM ....."
2560 :group 'org-properties
2561 :type 'string)
2563 (defcustom org-columns-ellipses ".."
2564 "The ellipses to be used when a field in column view is truncated.
2565 When this is the empty string, as many characters as possible are shown,
2566 but then there will be no visual indication that the field has been truncated.
2567 When this is a string of length N, the last N characters of a truncated
2568 field are replaced by this string. If the column is narrower than the
2569 ellipses string, only part of the ellipses string will be shown."
2570 :group 'org-properties
2571 :type 'string)
2573 (defcustom org-columns-modify-value-for-display-function nil
2574 "Function that modifies values for display in column view.
2575 For example, it can be used to cut out a certain part from a time stamp.
2576 The function must take 2 arguments:
2578 column-title The title of the column (*not* the property name)
2579 value The value that should be modified.
2581 The function should return the value that should be displayed,
2582 or nil if the normal value should be used."
2583 :group 'org-properties
2584 :type 'function)
2586 (defcustom org-effort-property "Effort"
2587 "The property that is being used to keep track of effort estimates.
2588 Effort estimates given in this property need to have the format H:MM."
2589 :group 'org-properties
2590 :group 'org-progress
2591 :type '(string :tag "Property"))
2593 (defconst org-global-properties-fixed
2594 '(("VISIBILITY_ALL" . "folded children content all")
2595 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2596 "List of property/value pairs that can be inherited by any entry.
2598 These are fixed values, for the preset properties. The user variable
2599 that can be used to add to this list is `org-global-properties'.
2601 The entries in this list are cons cells where the car is a property
2602 name and cdr is a string with the value. If the value represents
2603 multiple items like an \"_ALL\" property, separate the items by
2604 spaces.")
2606 (defcustom org-global-properties nil
2607 "List of property/value pairs that can be inherited by any entry.
2609 This list will be combined with the constant `org-global-properties-fixed'.
2611 The entries in this list are cons cells where the car is a property
2612 name and cdr is a string with the value.
2614 You can set buffer-local values for the same purpose in the variable
2615 `org-file-properties' this by adding lines like
2617 #+PROPERTY: NAME VALUE"
2618 :group 'org-properties
2619 :type '(repeat
2620 (cons (string :tag "Property")
2621 (string :tag "Value"))))
2623 (defvar org-file-properties nil
2624 "List of property/value pairs that can be inherited by any entry.
2625 Valid for the current buffer.
2626 This variable is populated from #+PROPERTY lines.")
2627 (make-variable-buffer-local 'org-file-properties)
2629 (defgroup org-agenda nil
2630 "Options concerning agenda views in Org-mode."
2631 :tag "Org Agenda"
2632 :group 'org)
2634 (defvar org-category nil
2635 "Variable used by org files to set a category for agenda display.
2636 Such files should use a file variable to set it, for example
2638 # -*- mode: org; org-category: \"ELisp\"
2640 or contain a special line
2642 #+CATEGORY: ELisp
2644 If the file does not specify a category, then file's base name
2645 is used instead.")
2646 (make-variable-buffer-local 'org-category)
2647 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2649 (defcustom org-agenda-files nil
2650 "The files to be used for agenda display.
2651 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2652 \\[org-remove-file]. You can also use customize to edit the list.
2654 If an entry is a directory, all files in that directory that are matched by
2655 `org-agenda-file-regexp' will be part of the file list.
2657 If the value of the variable is not a list but a single file name, then
2658 the list of agenda files is actually stored and maintained in that file, one
2659 agenda file per line."
2660 :group 'org-agenda
2661 :type '(choice
2662 (repeat :tag "List of files and directories" file)
2663 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2665 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2666 "Regular expression to match files for `org-agenda-files'.
2667 If any element in the list in that variable contains a directory instead
2668 of a normal file, all files in that directory that are matched by this
2669 regular expression will be included."
2670 :group 'org-agenda
2671 :type 'regexp)
2673 (defcustom org-agenda-text-search-extra-files nil
2674 "List of extra files to be searched by text search commands.
2675 These files will be search in addition to the agenda files by the
2676 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2677 Note that these files will only be searched for text search commands,
2678 not for the other agenda views like todo lists, tag searches or the weekly
2679 agenda. This variable is intended to list notes and possibly archive files
2680 that should also be searched by these two commands.
2681 In fact, if the first element in the list is the symbol `agenda-archives',
2682 than all archive files of all agenda files will be added to the search
2683 scope."
2684 :group 'org-agenda
2685 :type '(set :greedy t
2686 (const :tag "Agenda Archives" agenda-archives)
2687 (repeat :inline t (file))))
2689 (if (fboundp 'defvaralias)
2690 (defvaralias 'org-agenda-multi-occur-extra-files
2691 'org-agenda-text-search-extra-files))
2693 (defcustom org-agenda-skip-unavailable-files nil
2694 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2695 A nil value means to remove them, after a query, from the list."
2696 :group 'org-agenda
2697 :type 'boolean)
2699 (defcustom org-calendar-to-agenda-key [?c]
2700 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2701 The command `org-calendar-goto-agenda' will be bound to this key. The
2702 default is the character `c' because then `c' can be used to switch back and
2703 forth between agenda and calendar."
2704 :group 'org-agenda
2705 :type 'sexp)
2707 (defcustom org-calendar-agenda-action-key [?k]
2708 "The key to be installed in `calendar-mode-map' for agenda-action.
2709 The command `org-agenda-action' will be bound to this key. The
2710 default is the character `k' because we use the same key in the agenda."
2711 :group 'org-agenda
2712 :type 'sexp)
2714 (eval-after-load "calendar"
2715 '(progn
2716 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2717 'org-calendar-goto-agenda)
2718 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2719 'org-agenda-action)))
2721 (defgroup org-latex nil
2722 "Options for embedding LaTeX code into Org-mode."
2723 :tag "Org LaTeX"
2724 :group 'org)
2726 (defcustom org-format-latex-options
2727 '(:foreground default :background default :scale 1.0
2728 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2729 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2730 "Options for creating images from LaTeX fragments.
2731 This is a property list with the following properties:
2732 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2733 `default' means use the foreground of the default face.
2734 :background the background color, or \"Transparent\".
2735 `default' means use the background of the default face.
2736 :scale a scaling factor for the size of the images.
2737 :html-foreground, :html-background, :html-scale
2738 the same numbers for HTML export.
2739 :matchers a list indicating which matchers should be used to
2740 find LaTeX fragments. Valid members of this list are:
2741 \"begin\" find environments
2742 \"$1\" find single characters surrounded by $.$
2743 \"$\" find math expressions surrounded by $...$
2744 \"$$\" find math expressions surrounded by $$....$$
2745 \"\\(\" find math expressions surrounded by \\(...\\)
2746 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2747 :group 'org-latex
2748 :type 'plist)
2750 (defcustom org-format-latex-header "\\documentclass{article}
2751 \\usepackage{amssymb}
2752 \\usepackage[usenames]{color}
2753 \\usepackage{amsmath}
2754 \\usepackage{latexsym}
2755 \\usepackage[mathscr]{eucal}
2756 \\pagestyle{empty} % do not remove
2757 % The settings below are copied from fullpage.sty
2758 \\setlength{\\textwidth}{\\paperwidth}
2759 \\addtolength{\\textwidth}{-3cm}
2760 \\setlength{\\oddsidemargin}{1.5cm}
2761 \\addtolength{\\oddsidemargin}{-2.54cm}
2762 \\setlength{\\evensidemargin}{\\oddsidemargin}
2763 \\setlength{\\textheight}{\\paperheight}
2764 \\addtolength{\\textheight}{-\\headheight}
2765 \\addtolength{\\textheight}{-\\headsep}
2766 \\addtolength{\\textheight}{-\\footskip}
2767 \\addtolength{\\textheight}{-3cm}
2768 \\setlength{\\topmargin}{1.5cm}
2769 \\addtolength{\\topmargin}{-2.54cm}"
2770 "The document header used for processing LaTeX fragments.
2771 It is imperative that this header make sure that no page number
2772 appears on the page."
2773 :group 'org-latex
2774 :type 'string)
2777 (defgroup org-font-lock nil
2778 "Font-lock settings for highlighting in Org-mode."
2779 :tag "Org Font Lock"
2780 :group 'org)
2782 (defcustom org-level-color-stars-only nil
2783 "Non-nil means fontify only the stars in each headline.
2784 When nil, the entire headline is fontified.
2785 Changing it requires restart of `font-lock-mode' to become effective
2786 also in regions already fontified."
2787 :group 'org-font-lock
2788 :type 'boolean)
2790 (defcustom org-hide-leading-stars nil
2791 "Non-nil means, hide the first N-1 stars in a headline.
2792 This works by using the face `org-hide' for these stars. This
2793 face is white for a light background, and black for a dark
2794 background. You may have to customize the face `org-hide' to
2795 make this work.
2796 Changing it requires restart of `font-lock-mode' to become effective
2797 also in regions already fontified.
2798 You may also set this on a per-file basis by adding one of the following
2799 lines to the buffer:
2801 #+STARTUP: hidestars
2802 #+STARTUP: showstars"
2803 :group 'org-font-lock
2804 :type 'boolean)
2806 (defcustom org-fontify-done-headline nil
2807 "Non-nil means, change the face of a headline if it is marked DONE.
2808 Normally, only the TODO/DONE keyword indicates the state of a headline.
2809 When this is non-nil, the headline after the keyword is set to the
2810 `org-headline-done' as an additional indication."
2811 :group 'org-font-lock
2812 :type 'boolean)
2814 (defcustom org-fontify-emphasized-text t
2815 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2816 Changing this variable requires a restart of Emacs to take effect."
2817 :group 'org-font-lock
2818 :type 'boolean)
2820 (defcustom org-fontify-whole-heading-line nil
2821 "Non-nil means fontify the whole line for headings.
2822 This is useful when setting a background color for the
2823 org-leve-* faces."
2824 :group 'org-font-lock
2825 :type 'boolean)
2827 (defcustom org-highlight-latex-fragments-and-specials nil
2828 "Non-nil means, fontify what is treated specially by the exporters."
2829 :group 'org-font-lock
2830 :type 'boolean)
2832 (defcustom org-hide-emphasis-markers nil
2833 "Non-nil mean font-lock should hide the emphasis marker characters."
2834 :group 'org-font-lock
2835 :type 'boolean)
2837 (defvar org-emph-re nil
2838 "Regular expression for matching emphasis.")
2839 (defvar org-verbatim-re nil
2840 "Regular expression for matching verbatim text.")
2841 (defvar org-emphasis-regexp-components) ; defined just below
2842 (defvar org-emphasis-alist) ; defined just below
2843 (defun org-set-emph-re (var val)
2844 "Set variable and compute the emphasis regular expression."
2845 (set var val)
2846 (when (and (boundp 'org-emphasis-alist)
2847 (boundp 'org-emphasis-regexp-components)
2848 org-emphasis-alist org-emphasis-regexp-components)
2849 (let* ((e org-emphasis-regexp-components)
2850 (pre (car e))
2851 (post (nth 1 e))
2852 (border (nth 2 e))
2853 (body (nth 3 e))
2854 (nl (nth 4 e))
2855 (body1 (concat body "*?"))
2856 (markers (mapconcat 'car org-emphasis-alist ""))
2857 (vmarkers (mapconcat
2858 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2859 org-emphasis-alist "")))
2860 ;; make sure special characters appear at the right position in the class
2861 (if (string-match "\\^" markers)
2862 (setq markers (concat (replace-match "" t t markers) "^")))
2863 (if (string-match "-" markers)
2864 (setq markers (concat (replace-match "" t t markers) "-")))
2865 (if (string-match "\\^" vmarkers)
2866 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2867 (if (string-match "-" vmarkers)
2868 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2869 (if (> nl 0)
2870 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2871 (int-to-string nl) "\\}")))
2872 ;; Make the regexp
2873 (setq org-emph-re
2874 (concat "\\([" pre "]\\|^\\)"
2875 "\\("
2876 "\\([" markers "]\\)"
2877 "\\("
2878 "[^" border "]\\|"
2879 "[^" border "]"
2880 body1
2881 "[^" border "]"
2882 "\\)"
2883 "\\3\\)"
2884 "\\([" post "]\\|$\\)"))
2885 (setq org-verbatim-re
2886 (concat "\\([" pre "]\\|^\\)"
2887 "\\("
2888 "\\([" vmarkers "]\\)"
2889 "\\("
2890 "[^" border "]\\|"
2891 "[^" border "]"
2892 body1
2893 "[^" border "]"
2894 "\\)"
2895 "\\3\\)"
2896 "\\([" post "]\\|$\\)")))))
2898 (defcustom org-emphasis-regexp-components
2899 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2900 "Components used to build the regular expression for emphasis.
2901 This is a list with 6 entries. Terminology: In an emphasis string
2902 like \" *strong word* \", we call the initial space PREMATCH, the final
2903 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2904 and \"trong wor\" is the body. The different components in this variable
2905 specify what is allowed/forbidden in each part:
2907 pre Chars allowed as prematch. Beginning of line will be allowed too.
2908 post Chars allowed as postmatch. End of line will be allowed too.
2909 border The chars *forbidden* as border characters.
2910 body-regexp A regexp like \".\" to match a body character. Don't use
2911 non-shy groups here, and don't allow newline here.
2912 newline The maximum number of newlines allowed in an emphasis exp.
2914 Use customize to modify this, or restart Emacs after changing it."
2915 :group 'org-font-lock
2916 :set 'org-set-emph-re
2917 :type '(list
2918 (sexp :tag "Allowed chars in pre ")
2919 (sexp :tag "Allowed chars in post ")
2920 (sexp :tag "Forbidden chars in border ")
2921 (sexp :tag "Regexp for body ")
2922 (integer :tag "number of newlines allowed")
2923 (option (boolean :tag "Please ignore this button"))))
2925 (defcustom org-emphasis-alist
2926 `(("*" bold "<b>" "</b>")
2927 ("/" italic "<i>" "</i>")
2928 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2929 ("=" org-code "<code>" "</code>" verbatim)
2930 ("~" org-verbatim "<code>" "</code>" verbatim)
2931 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2932 "<del>" "</del>")
2934 "Special syntax for emphasized text.
2935 Text starting and ending with a special character will be emphasized, for
2936 example *bold*, _underlined_ and /italic/. This variable sets the marker
2937 characters, the face to be used by font-lock for highlighting in Org-mode
2938 Emacs buffers, and the HTML tags to be used for this.
2939 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2940 Use customize to modify this, or restart Emacs after changing it."
2941 :group 'org-font-lock
2942 :set 'org-set-emph-re
2943 :type '(repeat
2944 (list
2945 (string :tag "Marker character")
2946 (choice
2947 (face :tag "Font-lock-face")
2948 (plist :tag "Face property list"))
2949 (string :tag "HTML start tag")
2950 (string :tag "HTML end tag")
2951 (option (const verbatim)))))
2953 (defvar org-protecting-blocks
2954 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2955 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2956 This is needed for font-lock setup.")
2958 ;;; Miscellaneous options
2960 (defgroup org-completion nil
2961 "Completion in Org-mode."
2962 :tag "Org Completion"
2963 :group 'org)
2965 (defcustom org-completion-use-ido nil
2966 "Non-nil means, use ido completion wherever possible.
2967 Note that `ido-mode' must be active for this variable to be relevant.
2968 If you decide to turn this variable on, you might well want to turn off
2969 `org-outline-path-complete-in-steps'.
2970 See also `org-completion-use-iswitchb'."
2971 :group 'org-completion
2972 :type 'boolean)
2974 (defcustom org-completion-use-iswitchb nil
2975 "Non-nil means, use iswitchb completion wherever possible.
2976 Note that `iswitchb-mode' must be active for this variable to be relevant.
2977 If you decide to turn this variable on, you might well want to turn off
2978 `org-outline-path-complete-in-steps'.
2979 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
2980 :group 'org-completion
2981 :type 'boolean)
2983 (defcustom org-completion-fallback-command 'hippie-expand
2984 "The expansion command called by \\[org-complete] in normal context.
2985 Normal means, no org-mode-specific context."
2986 :group 'org-completion
2987 :type 'function)
2989 ;;; Functions and variables from ther packages
2990 ;; Declared here to avoid compiler warnings
2992 ;; XEmacs only
2993 (defvar outline-mode-menu-heading)
2994 (defvar outline-mode-menu-show)
2995 (defvar outline-mode-menu-hide)
2996 (defvar zmacs-regions) ; XEmacs regions
2998 ;; Emacs only
2999 (defvar mark-active)
3001 ;; Various packages
3002 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3003 (declare-function calendar-forward-day "cal-move" (arg))
3004 (declare-function calendar-goto-date "cal-move" (date))
3005 (declare-function calendar-goto-today "cal-move" ())
3006 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3007 (defvar calc-embedded-close-formula)
3008 (defvar calc-embedded-open-formula)
3009 (declare-function cdlatex-tab "ext:cdlatex" ())
3010 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3011 (defvar font-lock-unfontify-region-function)
3012 (declare-function iswitchb-read-buffer "iswitchb"
3013 (prompt &optional default require-match start matches-set))
3014 (defvar iswitchb-temp-buflist)
3015 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3016 (defvar org-agenda-tags-todo-honor-ignore-options)
3017 (declare-function org-agenda-skip "org-agenda" ())
3018 (declare-function org-format-agenda-item "org-agenda"
3019 (extra txt &optional category tags dotime noprefix remove-re))
3020 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3021 (declare-function org-agenda-change-all-lines "org-agenda"
3022 (newhead hdmarker &optional fixface just-this))
3023 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3024 (declare-function org-agenda-maybe-redo "org-agenda" ())
3025 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3026 (beg end))
3027 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3028 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3029 "org-agenda" (&optional end))
3030 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3031 (declare-function org-indent-mode "org-indent" (&optional arg))
3032 (declare-function parse-time-string "parse-time" (string))
3033 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3034 (defvar remember-data-file)
3035 (defvar texmathp-why)
3036 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3037 (declare-function table--at-cell-p "table" (position &optional object at-column))
3039 (defvar w3m-current-url)
3040 (defvar w3m-current-title)
3042 (defvar org-latex-regexps)
3044 ;;; Autoload and prepare some org modules
3046 ;; Some table stuff that needs to be defined here, because it is used
3047 ;; by the functions setting up org-mode or checking for table context.
3049 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3050 "Detects an org-type or table-type table.")
3051 (defconst org-table-line-regexp "^[ \t]*|"
3052 "Detects an org-type table line.")
3053 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3054 "Detects an org-type table line.")
3055 (defconst org-table-hline-regexp "^[ \t]*|-"
3056 "Detects an org-type table hline.")
3057 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3058 "Detects a table-type table hline.")
3059 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3060 "Searching from within a table (any type) this finds the first line
3061 outside the table.")
3063 ;; Autoload the functions in org-table.el that are needed by functions here.
3065 (eval-and-compile
3066 (org-autoload "org-table"
3067 '(org-table-align org-table-begin org-table-blank-field
3068 org-table-convert org-table-convert-region org-table-copy-down
3069 org-table-copy-region org-table-create
3070 org-table-create-or-convert-from-region
3071 org-table-create-with-table.el org-table-current-dline
3072 org-table-cut-region org-table-delete-column org-table-edit-field
3073 org-table-edit-formulas org-table-end org-table-eval-formula
3074 org-table-export org-table-field-info
3075 org-table-get-stored-formulas org-table-goto-column
3076 org-table-hline-and-move org-table-import org-table-insert-column
3077 org-table-insert-hline org-table-insert-row org-table-iterate
3078 org-table-justify-field-maybe org-table-kill-row
3079 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3080 org-table-move-column org-table-move-column-left
3081 org-table-move-column-right org-table-move-row
3082 org-table-move-row-down org-table-move-row-up
3083 org-table-next-field org-table-next-row org-table-paste-rectangle
3084 org-table-previous-field org-table-recalculate
3085 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3086 org-table-toggle-coordinate-overlays
3087 org-table-toggle-formula-debugger org-table-wrap-region
3088 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3090 (defun org-at-table-p (&optional table-type)
3091 "Return t if the cursor is inside an org-type table.
3092 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3093 (if org-enable-table-editor
3094 (save-excursion
3095 (beginning-of-line 1)
3096 (looking-at (if table-type org-table-any-line-regexp
3097 org-table-line-regexp)))
3098 nil))
3099 (defsubst org-table-p () (org-at-table-p))
3101 (defun org-at-table.el-p ()
3102 "Return t if and only if we are at a table.el table."
3103 (and (org-at-table-p 'any)
3104 (save-excursion
3105 (goto-char (org-table-begin 'any))
3106 (looking-at org-table1-hline-regexp))))
3107 (defun org-table-recognize-table.el ()
3108 "If there is a table.el table nearby, recognize it and move into it."
3109 (if org-table-tab-recognizes-table.el
3110 (if (org-at-table.el-p)
3111 (progn
3112 (beginning-of-line 1)
3113 (if (looking-at org-table-dataline-regexp)
3115 (if (looking-at org-table1-hline-regexp)
3116 (progn
3117 (beginning-of-line 2)
3118 (if (looking-at org-table-any-border-regexp)
3119 (beginning-of-line -1)))))
3120 (if (re-search-forward "|" (org-table-end t) t)
3121 (progn
3122 (require 'table)
3123 (if (table--at-cell-p (point))
3125 (message "recognizing table.el table...")
3126 (table-recognize-table)
3127 (message "recognizing table.el table...done")))
3128 (error "This should not happen..."))
3130 nil)
3131 nil))
3133 (defun org-at-table-hline-p ()
3134 "Return t if the cursor is inside a hline in a table."
3135 (if org-enable-table-editor
3136 (save-excursion
3137 (beginning-of-line 1)
3138 (looking-at org-table-hline-regexp))
3139 nil))
3141 (defvar org-table-clean-did-remove-column nil)
3143 (defun org-table-map-tables (function)
3144 "Apply FUNCTION to the start of all tables in the buffer."
3145 (save-excursion
3146 (save-restriction
3147 (widen)
3148 (goto-char (point-min))
3149 (while (re-search-forward org-table-any-line-regexp nil t)
3150 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3151 (beginning-of-line 1)
3152 (when (looking-at org-table-line-regexp)
3153 (save-excursion (funcall function))
3154 (or (looking-at org-table-line-regexp)
3155 (forward-char 1)))
3156 (re-search-forward org-table-any-border-regexp nil 1))))
3157 (message "Mapping tables: done"))
3159 ;; Declare and autoload functions from org-exp.el & Co
3161 (declare-function org-default-export-plist "org-exp")
3162 (declare-function org-infile-export-plist "org-exp")
3163 (declare-function org-get-current-options "org-exp")
3164 (eval-and-compile
3165 (org-autoload "org-exp"
3166 '(org-export org-export-visible
3167 org-insert-export-options-template
3168 org-table-clean-before-export))
3169 (org-autoload "org-ascii"
3170 '(org-export-as-ascii org-export-ascii-preprocess
3171 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3172 org-export-region-as-ascii))
3173 (org-autoload "org-html"
3174 '(org-export-as-html-and-open
3175 org-export-as-html-batch org-export-as-html-to-buffer
3176 org-replace-region-by-html org-export-region-as-html
3177 org-export-as-html))
3178 (org-autoload "org-icalendar"
3179 '(org-export-icalendar-this-file
3180 org-export-icalendar-all-agenda-files
3181 org-export-icalendar-combine-agenda-files))
3182 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3184 ;; Declare and autoload functions from org-agenda.el
3186 (eval-and-compile
3187 (org-autoload "org-agenda"
3188 '(org-agenda org-agenda-list org-search-view
3189 org-todo-list org-tags-view org-agenda-list-stuck-projects
3190 org-diary org-agenda-to-appt
3191 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3193 ;; Autoload org-remember
3195 (eval-and-compile
3196 (org-autoload "org-remember"
3197 '(org-remember-insinuate org-remember-annotation
3198 org-remember-apply-template org-remember org-remember-handler)))
3200 ;; Autoload org-clock.el
3203 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3204 (beg end))
3205 (declare-function org-clock-update-mode-line "org-clock" ())
3206 (declare-function org-resolve-clocks "org-clock"
3207 (&optional also-non-dangling-p prompt last-valid))
3208 (defvar org-clock-start-time)
3209 (defvar org-clock-marker (make-marker)
3210 "Marker recording the last clock-in.")
3211 (defvar org-clock-hd-marker (make-marker)
3212 "Marker recording the last clock-in, but the headline position.")
3213 (defvar org-clock-heading ""
3214 "The heading of the current clock entry.")
3215 (defun org-clock-is-active ()
3216 "Return non-nil if clock is currently running.
3217 The return value is actually the clock marker."
3218 (marker-buffer org-clock-marker))
3220 (eval-and-compile
3221 (org-autoload
3222 "org-clock"
3223 '(org-clock-in org-clock-out org-clock-cancel
3224 org-clock-goto org-clock-sum org-clock-display
3225 org-clock-remove-overlays org-clock-report
3226 org-clocktable-shift org-dblock-write:clocktable
3227 org-get-clocktable org-resolve-clocks)))
3229 (defun org-clock-update-time-maybe ()
3230 "If this is a CLOCK line, update it and return t.
3231 Otherwise, return nil."
3232 (interactive)
3233 (save-excursion
3234 (beginning-of-line 1)
3235 (skip-chars-forward " \t")
3236 (when (looking-at org-clock-string)
3237 (let ((re (concat "[ \t]*" org-clock-string
3238 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3239 "\\([ \t]*=>.*\\)?\\)?"))
3240 ts te h m s neg)
3241 (cond
3242 ((not (looking-at re))
3243 nil)
3244 ((not (match-end 2))
3245 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3246 (> org-clock-marker (point))
3247 (<= org-clock-marker (point-at-eol)))
3248 ;; The clock is running here
3249 (setq org-clock-start-time
3250 (apply 'encode-time
3251 (org-parse-time-string (match-string 1))))
3252 (org-clock-update-mode-line)))
3254 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3255 (end-of-line 1)
3256 (setq ts (match-string 1)
3257 te (match-string 3))
3258 (setq s (- (org-float-time
3259 (apply 'encode-time (org-parse-time-string te)))
3260 (org-float-time
3261 (apply 'encode-time (org-parse-time-string ts))))
3262 neg (< s 0)
3263 s (abs s)
3264 h (floor (/ s 3600))
3265 s (- s (* 3600 h))
3266 m (floor (/ s 60))
3267 s (- s (* 60 s)))
3268 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3269 t))))))
3271 (defun org-check-running-clock ()
3272 "Check if the current buffer contains the running clock.
3273 If yes, offer to stop it and to save the buffer with the changes."
3274 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3275 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3276 (buffer-name))))
3277 (org-clock-out)
3278 (when (y-or-n-p "Save changed buffer?")
3279 (save-buffer))))
3281 (defun org-clocktable-try-shift (dir n)
3282 "Check if this line starts a clock table, if yes, shift the time block."
3283 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3284 (org-clocktable-shift dir n)))
3286 ;; Autoload org-timer.el
3288 (eval-and-compile
3289 (org-autoload
3290 "org-timer"
3291 '(org-timer-start org-timer org-timer-item
3292 org-timer-change-times-in-region
3293 org-timer-set-timer
3294 org-timer-reset-timers
3295 org-timer-show-remaining-time)))
3297 ;; Autoload org-feed.el
3299 (eval-and-compile
3300 (org-autoload
3301 "org-feed"
3302 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3305 ;; Autoload org-indent.el
3307 (eval-and-compile
3308 (org-autoload
3309 "org-indent"
3310 '(org-indent-mode)))
3312 ;; Autoload org-mobile.el
3314 (eval-and-compile
3315 (org-autoload
3316 "org-mobile"
3317 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3319 ;; Autoload archiving code
3320 ;; The stuff that is needed for cycling and tags has to be defined here.
3322 (defgroup org-archive nil
3323 "Options concerning archiving in Org-mode."
3324 :tag "Org Archive"
3325 :group 'org-structure)
3327 (defcustom org-archive-location "%s_archive::"
3328 "The location where subtrees should be archived.
3330 The value of this variable is a string, consisting of two parts,
3331 separated by a double-colon. The first part is a filename and
3332 the second part is a headline.
3334 When the filename is omitted, archiving happens in the same file.
3335 %s in the filename will be replaced by the current file
3336 name (without the directory part). Archiving to a different file
3337 is useful to keep archived entries from contributing to the
3338 Org-mode Agenda.
3340 The archived entries will be filed as subtrees of the specified
3341 headline. When the headline is omitted, the subtrees are simply
3342 filed away at the end of the file, as top-level entries. Also in
3343 the heading you can use %s to represent the file name, this can be
3344 useful when using the same archive for a number of different files.
3346 Here are a few examples:
3347 \"%s_archive::\"
3348 If the current file is Projects.org, archive in file
3349 Projects.org_archive, as top-level trees. This is the default.
3351 \"::* Archived Tasks\"
3352 Archive in the current file, under the top-level headline
3353 \"* Archived Tasks\".
3355 \"~/org/archive.org::\"
3356 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3358 \"~/org/archive.org::From %s\"
3359 Archive in file ~/org/archive.org (absolute path), und headlines
3360 \"From FILENAME\" where file name is the current file name.
3362 \"basement::** Finished Tasks\"
3363 Archive in file ./basement (relative path), as level 3 trees
3364 below the level 2 heading \"** Finished Tasks\".
3366 You may set this option on a per-file basis by adding to the buffer a
3367 line like
3369 #+ARCHIVE: basement::** Finished Tasks
3371 You may also define it locally for a subtree by setting an ARCHIVE property
3372 in the entry. If such a property is found in an entry, or anywhere up
3373 the hierarchy, it will be used."
3374 :group 'org-archive
3375 :type 'string)
3377 (defcustom org-archive-tag "ARCHIVE"
3378 "The tag that marks a subtree as archived.
3379 An archived subtree does not open during visibility cycling, and does
3380 not contribute to the agenda listings.
3381 After changing this, font-lock must be restarted in the relevant buffers to
3382 get the proper fontification."
3383 :group 'org-archive
3384 :group 'org-keywords
3385 :type 'string)
3387 (defcustom org-agenda-skip-archived-trees t
3388 "Non-nil means, the agenda will skip any items located in archived trees.
3389 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3390 variable is no longer recommended, you should leave it at the value t.
3391 Instead, use the key `v' to cycle the archives-mode in the agenda."
3392 :group 'org-archive
3393 :group 'org-agenda-skip
3394 :type 'boolean)
3396 (defcustom org-columns-skip-arrchived-trees t
3397 "Non-nil means, irgnore archived trees when creating column view."
3398 :group 'org-archive
3399 :group 'org-properties
3400 :type 'boolean)
3402 (defcustom org-cycle-open-archived-trees nil
3403 "Non-nil means, `org-cycle' will open archived trees.
3404 An archived tree is a tree marked with the tag ARCHIVE.
3405 When nil, archived trees will stay folded. You can still open them with
3406 normal outline commands like `show-all', but not with the cycling commands."
3407 :group 'org-archive
3408 :group 'org-cycle
3409 :type 'boolean)
3411 (defcustom org-sparse-tree-open-archived-trees nil
3412 "Non-nil means sparse tree construction shows matches in archived trees.
3413 When nil, matches in these trees are highlighted, but the trees are kept in
3414 collapsed state."
3415 :group 'org-archive
3416 :group 'org-sparse-trees
3417 :type 'boolean)
3419 (defun org-cycle-hide-archived-subtrees (state)
3420 "Re-hide all archived subtrees after a visibility state change."
3421 (when (and (not org-cycle-open-archived-trees)
3422 (not (memq state '(overview folded))))
3423 (save-excursion
3424 (let* ((globalp (memq state '(contents all)))
3425 (beg (if globalp (point-min) (point)))
3426 (end (if globalp (point-max) (org-end-of-subtree t))))
3427 (org-hide-archived-subtrees beg end)
3428 (goto-char beg)
3429 (if (looking-at (concat ".*:" org-archive-tag ":"))
3430 (message "%s" (substitute-command-keys
3431 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3433 (defun org-force-cycle-archived ()
3434 "Cycle subtree even if it is archived."
3435 (interactive)
3436 (setq this-command 'org-cycle)
3437 (let ((org-cycle-open-archived-trees t))
3438 (call-interactively 'org-cycle)))
3440 (defun org-hide-archived-subtrees (beg end)
3441 "Re-hide all archived subtrees after a visibility state change."
3442 (save-excursion
3443 (let* ((re (concat ":" org-archive-tag ":")))
3444 (goto-char beg)
3445 (while (re-search-forward re end t)
3446 (and (org-on-heading-p) (hide-subtree))
3447 (org-end-of-subtree t)))))
3449 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3451 (eval-and-compile
3452 (org-autoload "org-archive"
3453 '(org-add-archive-files org-archive-subtree
3454 org-archive-to-archive-sibling org-toggle-archive-tag)))
3456 ;; Autoload Column View Code
3458 (declare-function org-columns-number-to-string "org-colview")
3459 (declare-function org-columns-get-format-and-top-level "org-colview")
3460 (declare-function org-columns-compute "org-colview")
3462 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3463 '(org-columns-number-to-string org-columns-get-format-and-top-level
3464 org-columns-compute org-agenda-columns org-columns-remove-overlays
3465 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3467 ;; Autoload ID code
3469 (declare-function org-id-store-link "org-id")
3470 (declare-function org-id-locations-load "org-id")
3471 (declare-function org-id-locations-save "org-id")
3472 (defvar org-id-track-globally)
3473 (org-autoload "org-id"
3474 '(org-id-get-create org-id-new org-id-copy org-id-get
3475 org-id-get-with-outline-path-completion
3476 org-id-get-with-outline-drilling
3477 org-id-goto org-id-find org-id-store-link))
3479 ;; Autoload Plotting Code
3481 (org-autoload "org-plot"
3482 '(org-plot/gnuplot))
3484 ;;; Variables for pre-computed regular expressions, all buffer local
3486 (defvar org-drawer-regexp nil
3487 "Matches first line of a hidden block.")
3488 (make-variable-buffer-local 'org-drawer-regexp)
3489 (defvar org-todo-regexp nil
3490 "Matches any of the TODO state keywords.")
3491 (make-variable-buffer-local 'org-todo-regexp)
3492 (defvar org-not-done-regexp nil
3493 "Matches any of the TODO state keywords except the last one.")
3494 (make-variable-buffer-local 'org-not-done-regexp)
3495 (defvar org-not-done-heading-regexp nil
3496 "Matches a TODO headline that is not done.")
3497 (make-variable-buffer-local 'org-not-done-regexp)
3498 (defvar org-todo-line-regexp nil
3499 "Matches a headline and puts TODO state into group 2 if present.")
3500 (make-variable-buffer-local 'org-todo-line-regexp)
3501 (defvar org-complex-heading-regexp nil
3502 "Matches a headline and puts everything into groups:
3503 group 1: the stars
3504 group 2: The todo keyword, maybe
3505 group 3: Priority cookie
3506 group 4: True headline
3507 group 5: Tags")
3508 (make-variable-buffer-local 'org-complex-heading-regexp)
3509 (defvar org-complex-heading-regexp-format nil)
3510 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3511 (defvar org-todo-line-tags-regexp nil
3512 "Matches a headline and puts TODO state into group 2 if present.
3513 Also put tags into group 4 if tags are present.")
3514 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3515 (defvar org-nl-done-regexp nil
3516 "Matches newline followed by a headline with the DONE keyword.")
3517 (make-variable-buffer-local 'org-nl-done-regexp)
3518 (defvar org-looking-at-done-regexp nil
3519 "Matches the DONE keyword a point.")
3520 (make-variable-buffer-local 'org-looking-at-done-regexp)
3521 (defvar org-ds-keyword-length 12
3522 "Maximum length of the Deadline and SCHEDULED keywords.")
3523 (make-variable-buffer-local 'org-ds-keyword-length)
3524 (defvar org-deadline-regexp nil
3525 "Matches the DEADLINE keyword.")
3526 (make-variable-buffer-local 'org-deadline-regexp)
3527 (defvar org-deadline-time-regexp nil
3528 "Matches the DEADLINE keyword together with a time stamp.")
3529 (make-variable-buffer-local 'org-deadline-time-regexp)
3530 (defvar org-deadline-line-regexp nil
3531 "Matches the DEADLINE keyword and the rest of the line.")
3532 (make-variable-buffer-local 'org-deadline-line-regexp)
3533 (defvar org-scheduled-regexp nil
3534 "Matches the SCHEDULED keyword.")
3535 (make-variable-buffer-local 'org-scheduled-regexp)
3536 (defvar org-scheduled-time-regexp nil
3537 "Matches the SCHEDULED keyword together with a time stamp.")
3538 (make-variable-buffer-local 'org-scheduled-time-regexp)
3539 (defvar org-closed-time-regexp nil
3540 "Matches the CLOSED keyword together with a time stamp.")
3541 (make-variable-buffer-local 'org-closed-time-regexp)
3543 (defvar org-keyword-time-regexp nil
3544 "Matches any of the 4 keywords, together with the time stamp.")
3545 (make-variable-buffer-local 'org-keyword-time-regexp)
3546 (defvar org-keyword-time-not-clock-regexp nil
3547 "Matches any of the 3 keywords, together with the time stamp.")
3548 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3549 (defvar org-maybe-keyword-time-regexp nil
3550 "Matches a timestamp, possibly preceeded by a keyword.")
3551 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3552 (defvar org-planning-or-clock-line-re nil
3553 "Matches a line with planning or clock info.")
3554 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3556 (defconst org-plain-time-of-day-regexp
3557 (concat
3558 "\\(\\<[012]?[0-9]"
3559 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3560 "\\(--?"
3561 "\\(\\<[012]?[0-9]"
3562 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3563 "\\)?")
3564 "Regular expression to match a plain time or time range.
3565 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3566 groups carry important information:
3567 0 the full match
3568 1 the first time, range or not
3569 8 the second time, if it is a range.")
3571 (defconst org-plain-time-extension-regexp
3572 (concat
3573 "\\(\\<[012]?[0-9]"
3574 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3575 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3576 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3577 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3578 groups carry important information:
3579 0 the full match
3580 7 hours of duration
3581 9 minutes of duration")
3583 (defconst org-stamp-time-of-day-regexp
3584 (concat
3585 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3586 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3587 "\\(--?"
3588 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3589 "Regular expression to match a timestamp time or time range.
3590 After a match, the following groups carry important information:
3591 0 the full match
3592 1 date plus weekday, for backreferencing to make sure both times on same day
3593 2 the first time, range or not
3594 4 the second time, if it is a range.")
3596 (defconst org-startup-options
3597 '(("fold" org-startup-folded t)
3598 ("overview" org-startup-folded t)
3599 ("nofold" org-startup-folded nil)
3600 ("showall" org-startup-folded nil)
3601 ("showeverything" org-startup-folded showeverything)
3602 ("content" org-startup-folded content)
3603 ("indent" org-startup-indented t)
3604 ("noindent" org-startup-indented nil)
3605 ("hidestars" org-hide-leading-stars t)
3606 ("showstars" org-hide-leading-stars nil)
3607 ("odd" org-odd-levels-only t)
3608 ("oddeven" org-odd-levels-only nil)
3609 ("align" org-startup-align-all-tables t)
3610 ("noalign" org-startup-align-all-tables nil)
3611 ("customtime" org-display-custom-times t)
3612 ("logdone" org-log-done time)
3613 ("lognotedone" org-log-done note)
3614 ("nologdone" org-log-done nil)
3615 ("lognoteclock-out" org-log-note-clock-out t)
3616 ("nolognoteclock-out" org-log-note-clock-out nil)
3617 ("logrepeat" org-log-repeat state)
3618 ("lognoterepeat" org-log-repeat note)
3619 ("nologrepeat" org-log-repeat nil)
3620 ("fninline" org-footnote-define-inline t)
3621 ("nofninline" org-footnote-define-inline nil)
3622 ("fnlocal" org-footnote-section nil)
3623 ("fnauto" org-footnote-auto-label t)
3624 ("fnprompt" org-footnote-auto-label nil)
3625 ("fnconfirm" org-footnote-auto-label confirm)
3626 ("fnplain" org-footnote-auto-label plain)
3627 ("fnadjust" org-footnote-auto-adjust t)
3628 ("nofnadjust" org-footnote-auto-adjust nil)
3629 ("constcgs" constants-unit-system cgs)
3630 ("constSI" constants-unit-system SI)
3631 ("noptag" org-tag-persistent-alist nil)
3632 ("hideblocks" org-hide-block-startup t)
3633 ("nohideblocks" org-hide-block-startup nil))
3634 "Variable associated with STARTUP options for org-mode.
3635 Each element is a list of three items: The startup options as written
3636 in the #+STARTUP line, the corresponding variable, and the value to
3637 set this variable to if the option is found. An optional forth element PUSH
3638 means to push this value onto the list in the variable.")
3640 (defun org-set-regexps-and-options ()
3641 "Precompute regular expressions for current buffer."
3642 (when (org-mode-p)
3643 (org-set-local 'org-todo-kwd-alist nil)
3644 (org-set-local 'org-todo-key-alist nil)
3645 (org-set-local 'org-todo-key-trigger nil)
3646 (org-set-local 'org-todo-keywords-1 nil)
3647 (org-set-local 'org-done-keywords nil)
3648 (org-set-local 'org-todo-heads nil)
3649 (org-set-local 'org-todo-sets nil)
3650 (org-set-local 'org-todo-log-states nil)
3651 (org-set-local 'org-file-properties nil)
3652 (org-set-local 'org-file-tags nil)
3653 (let ((re (org-make-options-regexp
3654 '("CATEGORY" "TODO" "COLUMNS"
3655 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3656 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3657 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3658 (splitre "[ \t]+")
3659 kwds kws0 kwsa key log value cat arch tags const links hw dws
3660 tail sep kws1 prio props ftags drawers
3661 ext-setup-or-nil setup-contents (start 0))
3662 (save-excursion
3663 (save-restriction
3664 (widen)
3665 (goto-char (point-min))
3666 (while (or (and ext-setup-or-nil
3667 (string-match re ext-setup-or-nil start)
3668 (setq start (match-end 0)))
3669 (and (setq ext-setup-or-nil nil start 0)
3670 (re-search-forward re nil t)))
3671 (setq key (upcase (match-string 1 ext-setup-or-nil))
3672 value (org-match-string-no-properties 2 ext-setup-or-nil))
3673 (cond
3674 ((equal key "CATEGORY")
3675 (if (string-match "[ \t]+$" value)
3676 (setq value (replace-match "" t t value)))
3677 (setq cat value))
3678 ((member key '("SEQ_TODO" "TODO"))
3679 (push (cons 'sequence (org-split-string value splitre)) kwds))
3680 ((equal key "TYP_TODO")
3681 (push (cons 'type (org-split-string value splitre)) kwds))
3682 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3683 ;; general TODO-like setup
3684 (push (cons (intern (downcase (match-string 1 key)))
3685 (org-split-string value splitre)) kwds))
3686 ((equal key "TAGS")
3687 (setq tags (append tags (if tags '("\\n") nil)
3688 (org-split-string value splitre))))
3689 ((equal key "COLUMNS")
3690 (org-set-local 'org-columns-default-format value))
3691 ((equal key "LINK")
3692 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3693 (push (cons (match-string 1 value)
3694 (org-trim (match-string 2 value)))
3695 links)))
3696 ((equal key "PRIORITIES")
3697 (setq prio (org-split-string value " +")))
3698 ((equal key "PROPERTY")
3699 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3700 (push (cons (match-string 1 value) (match-string 2 value))
3701 props)))
3702 ((equal key "FILETAGS")
3703 (when (string-match "\\S-" value)
3704 (setq ftags
3705 (append
3706 ftags
3707 (apply 'append
3708 (mapcar (lambda (x) (org-split-string x ":"))
3709 (org-split-string value)))))))
3710 ((equal key "DRAWERS")
3711 (setq drawers (org-split-string value splitre)))
3712 ((equal key "CONSTANTS")
3713 (setq const (append const (org-split-string value splitre))))
3714 ((equal key "STARTUP")
3715 (let ((opts (org-split-string value splitre))
3716 l var val)
3717 (while (setq l (pop opts))
3718 (when (setq l (assoc l org-startup-options))
3719 (setq var (nth 1 l) val (nth 2 l))
3720 (if (not (nth 3 l))
3721 (set (make-local-variable var) val)
3722 (if (not (listp (symbol-value var)))
3723 (set (make-local-variable var) nil))
3724 (set (make-local-variable var) (symbol-value var))
3725 (add-to-list var val))))))
3726 ((equal key "ARCHIVE")
3727 (string-match " *$" value)
3728 (setq arch (replace-match "" t t value))
3729 (remove-text-properties 0 (length arch)
3730 '(face t fontified t) arch))
3731 ((equal key "SETUPFILE")
3732 (setq setup-contents (org-file-contents
3733 (expand-file-name
3734 (org-remove-double-quotes value))
3735 'noerror))
3736 (if (not ext-setup-or-nil)
3737 (setq ext-setup-or-nil setup-contents start 0)
3738 (setq ext-setup-or-nil
3739 (concat (substring ext-setup-or-nil 0 start)
3740 "\n" setup-contents "\n"
3741 (substring ext-setup-or-nil start)))))
3742 ))))
3743 (when cat
3744 (org-set-local 'org-category (intern cat))
3745 (push (cons "CATEGORY" cat) props))
3746 (when prio
3747 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3748 (setq prio (mapcar 'string-to-char prio))
3749 (org-set-local 'org-highest-priority (nth 0 prio))
3750 (org-set-local 'org-lowest-priority (nth 1 prio))
3751 (org-set-local 'org-default-priority (nth 2 prio)))
3752 (and props (org-set-local 'org-file-properties (nreverse props)))
3753 (and ftags (org-set-local 'org-file-tags
3754 (mapcar 'org-add-prop-inherited ftags)))
3755 (and drawers (org-set-local 'org-drawers drawers))
3756 (and arch (org-set-local 'org-archive-location arch))
3757 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3758 ;; Process the TODO keywords
3759 (unless kwds
3760 ;; Use the global values as if they had been given locally.
3761 (setq kwds (default-value 'org-todo-keywords))
3762 (if (stringp (car kwds))
3763 (setq kwds (list (cons org-todo-interpretation
3764 (default-value 'org-todo-keywords)))))
3765 (setq kwds (reverse kwds)))
3766 (setq kwds (nreverse kwds))
3767 (let (inter kws kw)
3768 (while (setq kws (pop kwds))
3769 (let ((kws (or
3770 (run-hook-with-args-until-success
3771 'org-todo-setup-filter-hook kws)
3772 kws)))
3773 (setq inter (pop kws) sep (member "|" kws)
3774 kws0 (delete "|" (copy-sequence kws))
3775 kwsa nil
3776 kws1 (mapcar
3777 (lambda (x)
3778 ;; 1 2
3779 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3780 (progn
3781 (setq kw (match-string 1 x)
3782 key (and (match-end 2) (match-string 2 x))
3783 log (org-extract-log-state-settings x))
3784 (push (cons kw (and key (string-to-char key))) kwsa)
3785 (and log (push log org-todo-log-states))
3787 (error "Invalid TODO keyword %s" x)))
3788 kws0)
3789 kwsa (if kwsa (append '((:startgroup))
3790 (nreverse kwsa)
3791 '((:endgroup))))
3792 hw (car kws1)
3793 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3794 tail (list inter hw (car dws) (org-last dws))))
3795 (add-to-list 'org-todo-heads hw 'append)
3796 (push kws1 org-todo-sets)
3797 (setq org-done-keywords (append org-done-keywords dws nil))
3798 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3799 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3800 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3801 (setq org-todo-sets (nreverse org-todo-sets)
3802 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3803 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3804 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3805 ;; Process the constants
3806 (when const
3807 (let (e cst)
3808 (while (setq e (pop const))
3809 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3810 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3811 (setq org-table-formula-constants-local cst)))
3813 ;; Process the tags.
3814 (when tags
3815 (let (e tgs)
3816 (while (setq e (pop tags))
3817 (cond
3818 ((equal e "{") (push '(:startgroup) tgs))
3819 ((equal e "}") (push '(:endgroup) tgs))
3820 ((equal e "\\n") (push '(:newline) tgs))
3821 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3822 (push (cons (match-string 1 e)
3823 (string-to-char (match-string 2 e)))
3824 tgs))
3825 (t (push (list e) tgs))))
3826 (org-set-local 'org-tag-alist nil)
3827 (while (setq e (pop tgs))
3828 (or (and (stringp (car e))
3829 (assoc (car e) org-tag-alist))
3830 (push e org-tag-alist)))))
3832 ;; Compute the regular expressions and other local variables
3833 (if (not org-done-keywords)
3834 (setq org-done-keywords (and org-todo-keywords-1
3835 (list (org-last org-todo-keywords-1)))))
3836 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3837 (length org-scheduled-string)
3838 (length org-clock-string)
3839 (length org-closed-string)))
3840 org-drawer-regexp
3841 (concat "^[ \t]*:\\("
3842 (mapconcat 'regexp-quote org-drawers "\\|")
3843 "\\):[ \t]*$")
3844 org-not-done-keywords
3845 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3846 org-todo-regexp
3847 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3848 "\\|") "\\)\\>")
3849 org-not-done-regexp
3850 (concat "\\<\\("
3851 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3852 "\\)\\>")
3853 org-not-done-heading-regexp
3854 (concat "^\\(\\*+\\)[ \t]+\\("
3855 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3856 "\\)\\>")
3857 org-todo-line-regexp
3858 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3859 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3860 "\\)\\>\\)?[ \t]*\\(.*\\)")
3861 org-complex-heading-regexp
3862 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3863 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3864 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3865 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3866 org-complex-heading-regexp-format
3867 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3868 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3869 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3870 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3871 org-nl-done-regexp
3872 (concat "\n\\*+[ \t]+"
3873 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3874 "\\)" "\\>")
3875 org-todo-line-tags-regexp
3876 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3877 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3878 (org-re
3879 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3880 org-looking-at-done-regexp
3881 (concat "^" "\\(?:"
3882 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3883 "\\>")
3884 org-deadline-regexp (concat "\\<" org-deadline-string)
3885 org-deadline-time-regexp
3886 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3887 org-deadline-line-regexp
3888 (concat "\\<\\(" org-deadline-string "\\).*")
3889 org-scheduled-regexp
3890 (concat "\\<" org-scheduled-string)
3891 org-scheduled-time-regexp
3892 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3893 org-closed-time-regexp
3894 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3895 org-keyword-time-regexp
3896 (concat "\\<\\(" org-scheduled-string
3897 "\\|" org-deadline-string
3898 "\\|" org-closed-string
3899 "\\|" org-clock-string "\\)"
3900 " *[[<]\\([^]>]+\\)[]>]")
3901 org-keyword-time-not-clock-regexp
3902 (concat "\\<\\(" org-scheduled-string
3903 "\\|" org-deadline-string
3904 "\\|" org-closed-string
3905 "\\)"
3906 " *[[<]\\([^]>]+\\)[]>]")
3907 org-maybe-keyword-time-regexp
3908 (concat "\\(\\<\\(" org-scheduled-string
3909 "\\|" org-deadline-string
3910 "\\|" org-closed-string
3911 "\\|" org-clock-string "\\)\\)?"
3912 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3913 org-planning-or-clock-line-re
3914 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3915 "\\|" org-deadline-string
3916 "\\|" org-closed-string "\\|" org-clock-string
3917 "\\)\\>\\)")
3919 (org-compute-latex-and-specials-regexp)
3920 (org-set-font-lock-defaults))))
3922 (defun org-file-contents (file &optional noerror)
3923 "Return the contents of FILE, as a string."
3924 (if (or (not file)
3925 (not (file-readable-p file)))
3926 (if noerror
3927 (progn
3928 (message "Cannot read file %s" file)
3929 (ding) (sit-for 2)
3931 (error "Cannot read file %s" file))
3932 (with-temp-buffer
3933 (insert-file-contents file)
3934 (buffer-string))))
3936 (defun org-extract-log-state-settings (x)
3937 "Extract the log state setting from a TODO keyword string.
3938 This will extract info from a string like \"WAIT(w@/!)\"."
3939 (let (kw key log1 log2)
3940 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3941 (setq kw (match-string 1 x)
3942 key (and (match-end 2) (match-string 2 x))
3943 log1 (and (match-end 3) (match-string 3 x))
3944 log2 (and (match-end 4) (match-string 4 x)))
3945 (and (or log1 log2)
3946 (list kw
3947 (and log1 (if (equal log1 "!") 'time 'note))
3948 (and log2 (if (equal log2 "!") 'time 'note)))))))
3950 (defun org-remove-keyword-keys (list)
3951 "Remove a pair of parenthesis at the end of each string in LIST."
3952 (mapcar (lambda (x)
3953 (if (string-match "(.*)$" x)
3954 (substring x 0 (match-beginning 0))
3956 list))
3958 ;; FIXME: this could be done much better, using second characters etc.
3959 (defun org-assign-fast-keys (alist)
3960 "Assign fast keys to a keyword-key alist.
3961 Respect keys that are already there."
3962 (let (new e k c c1 c2 (char ?a))
3963 (while (setq e (pop alist))
3964 (cond
3965 ((equal e '(:startgroup)) (push e new))
3966 ((equal e '(:endgroup)) (push e new))
3967 ((equal e '(:newline)) (push e new))
3969 (setq k (car e) c2 nil)
3970 (if (cdr e)
3971 (setq c (cdr e))
3972 ;; automatically assign a character.
3973 (setq c1 (string-to-char
3974 (downcase (substring
3975 k (if (= (string-to-char k) ?@) 1 0)))))
3976 (if (or (rassoc c1 new) (rassoc c1 alist))
3977 (while (or (rassoc char new) (rassoc char alist))
3978 (setq char (1+ char)))
3979 (setq c2 c1))
3980 (setq c (or c2 char)))
3981 (push (cons k c) new))))
3982 (nreverse new)))
3984 ;;; Some variables used in various places
3986 (defvar org-window-configuration nil
3987 "Used in various places to store a window configuration.")
3988 (defvar org-selected-window nil
3989 "Used in various places to store a window configuration.")
3990 (defvar org-finish-function nil
3991 "Function to be called when `C-c C-c' is used.
3992 This is for getting out of special buffers like remember.")
3995 ;; FIXME: Occasionally check by commenting these, to make sure
3996 ;; no other functions uses these, forgetting to let-bind them.
3997 (defvar entry)
3998 (defvar last-state)
3999 (defvar date)
4001 ;; Defined somewhere in this file, but used before definition.
4002 (defvar org-html-entities)
4003 (defvar org-struct-menu)
4004 (defvar org-org-menu)
4005 (defvar org-tbl-menu)
4006 (defvar org-agenda-keymap)
4008 ;;;; Define the Org-mode
4010 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4011 (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."))
4014 ;; We use a before-change function to check if a table might need
4015 ;; an update.
4016 (defvar org-table-may-need-update t
4017 "Indicates that a table might need an update.
4018 This variable is set by `org-before-change-function'.
4019 `org-table-align' sets it back to nil.")
4020 (defun org-before-change-function (beg end)
4021 "Every change indicates that a table might need an update."
4022 (setq org-table-may-need-update t))
4023 (defvar org-mode-map)
4024 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4025 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4026 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4027 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4028 (defvar org-table-buffer-is-an nil)
4029 (defconst org-outline-regexp "\\*+ ")
4031 ;;;###autoload
4032 (define-derived-mode org-mode outline-mode "Org"
4033 "Outline-based notes management and organizer, alias
4034 \"Carsten's outline-mode for keeping track of everything.\"
4036 Org-mode develops organizational tasks around a NOTES file which
4037 contains information about projects as plain text. Org-mode is
4038 implemented on top of outline-mode, which is ideal to keep the content
4039 of large files well structured. It supports ToDo items, deadlines and
4040 time stamps, which magically appear in the diary listing of the Emacs
4041 calendar. Tables are easily created with a built-in table editor.
4042 Plain text URL-like links connect to websites, emails (VM), Usenet
4043 messages (Gnus), BBDB entries, and any files related to the project.
4044 For printing and sharing of notes, an Org-mode file (or a part of it)
4045 can be exported as a structured ASCII or HTML file.
4047 The following commands are available:
4049 \\{org-mode-map}"
4051 ;; Get rid of Outline menus, they are not needed
4052 ;; Need to do this here because define-derived-mode sets up
4053 ;; the keymap so late. Still, it is a waste to call this each time
4054 ;; we switch another buffer into org-mode.
4055 (if (featurep 'xemacs)
4056 (when (boundp 'outline-mode-menu-heading)
4057 ;; Assume this is Greg's port, it used easymenu
4058 (easy-menu-remove outline-mode-menu-heading)
4059 (easy-menu-remove outline-mode-menu-show)
4060 (easy-menu-remove outline-mode-menu-hide))
4061 (define-key org-mode-map [menu-bar headings] 'undefined)
4062 (define-key org-mode-map [menu-bar hide] 'undefined)
4063 (define-key org-mode-map [menu-bar show] 'undefined))
4065 (org-load-modules-maybe)
4066 (easy-menu-add org-org-menu)
4067 (easy-menu-add org-tbl-menu)
4068 (org-install-agenda-files-menu)
4069 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4070 (org-add-to-invisibility-spec '(org-cwidth))
4071 (org-add-to-invisibility-spec '(org-hide-block . t))
4072 (when (featurep 'xemacs)
4073 (org-set-local 'line-move-ignore-invisible t))
4074 (org-set-local 'outline-regexp org-outline-regexp)
4075 (org-set-local 'outline-level 'org-outline-level)
4076 (when (and org-ellipsis
4077 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4078 (fboundp 'make-glyph-code))
4079 (unless org-display-table
4080 (setq org-display-table (make-display-table)))
4081 (set-display-table-slot
4082 org-display-table 4
4083 (vconcat (mapcar
4084 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4085 org-ellipsis)))
4086 (if (stringp org-ellipsis) org-ellipsis "..."))))
4087 (setq buffer-display-table org-display-table))
4088 (org-set-regexps-and-options)
4089 (when (and org-tag-faces (not org-tags-special-faces-re))
4090 ;; tag faces set outside customize.... force initialization.
4091 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4092 ;; Calc embedded
4093 (org-set-local 'calc-embedded-open-mode "# ")
4094 (modify-syntax-entry ?# "<")
4095 (modify-syntax-entry ?@ "w")
4096 (if org-startup-truncated (setq truncate-lines t))
4097 (org-set-local 'font-lock-unfontify-region-function
4098 'org-unfontify-region)
4099 ;; Activate before-change-function
4100 (org-set-local 'org-table-may-need-update t)
4101 (org-add-hook 'before-change-functions 'org-before-change-function nil
4102 'local)
4103 ;; Check for running clock before killing a buffer
4104 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4105 ;; Paragraphs and auto-filling
4106 (org-set-autofill-regexps)
4107 (setq indent-line-function 'org-indent-line-function)
4108 (org-update-radio-target-regexp)
4109 ;; Make sure dependence stuff works reliably, even for users who set it
4110 ;; too late :-(
4111 (if org-enforce-todo-dependencies
4112 (add-hook 'org-blocker-hook
4113 'org-block-todo-from-children-or-siblings-or-parent)
4114 (remove-hook 'org-blocker-hook
4115 'org-block-todo-from-children-or-siblings-or-parent))
4116 (if org-enforce-todo-checkbox-dependencies
4117 (add-hook 'org-blocker-hook
4118 'org-block-todo-from-checkboxes)
4119 (remove-hook 'org-blocker-hook
4120 'org-block-todo-from-checkboxes))
4122 ;; Comment characters
4123 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4124 (org-set-local 'comment-padding " ")
4126 ;; Align options lines
4127 (org-set-local
4128 'align-mode-rules-list
4129 '((org-in-buffer-settings
4130 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4131 (modes . '(org-mode)))))
4133 ;; Imenu
4134 (org-set-local 'imenu-create-index-function
4135 'org-imenu-get-tree)
4137 ;; Make isearch reveal context
4138 (if (or (featurep 'xemacs)
4139 (not (boundp 'outline-isearch-open-invisible-function)))
4140 ;; Emacs 21 and XEmacs make use of the hook
4141 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4142 ;; Emacs 22 deals with this through a special variable
4143 (org-set-local 'outline-isearch-open-invisible-function
4144 (lambda (&rest ignore) (org-show-context 'isearch))))
4146 ;; If empty file that did not turn on org-mode automatically, make it to.
4147 (if (and org-insert-mode-line-in-empty-file
4148 (interactive-p)
4149 (= (point-min) (point-max)))
4150 (insert "# -*- mode: org -*-\n\n"))
4152 (unless org-inhibit-startup
4153 (when org-startup-align-all-tables
4154 (let ((bmp (buffer-modified-p)))
4155 (org-table-map-tables 'org-table-align)
4156 (set-buffer-modified-p bmp)))
4157 (when org-startup-indented
4158 (require 'org-indent)
4159 (org-indent-mode 1))
4160 (org-set-startup-visibility)))
4162 (when (fboundp 'abbrev-table-put)
4163 (abbrev-table-put org-mode-abbrev-table
4164 :parents (list text-mode-abbrev-table)))
4166 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4168 (defun org-current-time ()
4169 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4170 (if (> (car org-time-stamp-rounding-minutes) 1)
4171 (let ((r (car org-time-stamp-rounding-minutes))
4172 (time (decode-time)))
4173 (apply 'encode-time
4174 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4175 (nthcdr 2 time))))
4176 (current-time)))
4178 ;;;; Font-Lock stuff, including the activators
4180 (defvar org-mouse-map (make-sparse-keymap))
4181 (org-defkey org-mouse-map
4182 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4183 (org-defkey org-mouse-map
4184 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4185 (when org-mouse-1-follows-link
4186 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4187 (when org-tab-follows-link
4188 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4189 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4191 (require 'font-lock)
4193 (defconst org-non-link-chars "]\t\n\r<>")
4194 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4195 "shell" "elisp"))
4196 (defvar org-link-types-re nil
4197 "Matches a link that has a url-like prefix like \"http:\"")
4198 (defvar org-link-re-with-space nil
4199 "Matches a link with spaces, optional angular brackets around it.")
4200 (defvar org-link-re-with-space2 nil
4201 "Matches a link with spaces, optional angular brackets around it.")
4202 (defvar org-link-re-with-space3 nil
4203 "Matches a link with spaces, only for internal part in bracket links.")
4204 (defvar org-angle-link-re nil
4205 "Matches link with angular brackets, spaces are allowed.")
4206 (defvar org-plain-link-re nil
4207 "Matches plain link, without spaces.")
4208 (defvar org-bracket-link-regexp nil
4209 "Matches a link in double brackets.")
4210 (defvar org-bracket-link-analytic-regexp nil
4211 "Regular expression used to analyze links.
4212 Here is what the match groups contain after a match:
4213 1: http:
4214 2: http
4215 3: path
4216 4: [desc]
4217 5: desc")
4218 (defvar org-bracket-link-analytic-regexp++ nil
4219 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4220 (defvar org-any-link-re nil
4221 "Regular expression matching any link.")
4223 (defun org-make-link-regexps ()
4224 "Update the link regular expressions.
4225 This should be called after the variable `org-link-types' has changed."
4226 (setq org-link-types-re
4227 (concat
4228 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4229 org-link-re-with-space
4230 (concat
4231 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4232 "\\([^" org-non-link-chars " ]"
4233 "[^" org-non-link-chars "]*"
4234 "[^" org-non-link-chars " ]\\)>?")
4235 org-link-re-with-space2
4236 (concat
4237 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4238 "\\([^" org-non-link-chars " ]"
4239 "[^\t\n\r]*"
4240 "[^" org-non-link-chars " ]\\)>?")
4241 org-link-re-with-space3
4242 (concat
4243 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4244 "\\([^" org-non-link-chars " ]"
4245 "[^\t\n\r]*\\)")
4246 org-angle-link-re
4247 (concat
4248 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4249 "\\([^" org-non-link-chars " ]"
4250 "[^" org-non-link-chars "]*"
4251 "\\)>")
4252 org-plain-link-re
4253 (concat
4254 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4255 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4256 org-bracket-link-regexp
4257 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4258 org-bracket-link-analytic-regexp
4259 (concat
4260 "\\[\\["
4261 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4262 "\\([^]]+\\)"
4263 "\\]"
4264 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4265 "\\]")
4266 org-bracket-link-analytic-regexp++
4267 (concat
4268 "\\[\\["
4269 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4270 "\\([^]]+\\)"
4271 "\\]"
4272 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4273 "\\]")
4274 org-any-link-re
4275 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4276 org-angle-link-re "\\)\\|\\("
4277 org-plain-link-re "\\)")))
4279 (org-make-link-regexps)
4281 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4282 "Regular expression for fast time stamp matching.")
4283 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4284 "Regular expression for fast time stamp matching.")
4285 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4286 "Regular expression matching time strings for analysis.
4287 This one does not require the space after the date, so it can be used
4288 on a string that terminates immediately after the date.")
4289 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4290 "Regular expression matching time strings for analysis.")
4291 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4292 "Regular expression matching time stamps, with groups.")
4293 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4294 "Regular expression matching time stamps (also [..]), with groups.")
4295 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4296 "Regular expression matching a time stamp range.")
4297 (defconst org-tr-regexp-both
4298 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4299 "Regular expression matching a time stamp range.")
4300 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4301 org-ts-regexp "\\)?")
4302 "Regular expression matching a time stamp or time stamp range.")
4303 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4304 org-ts-regexp-both "\\)?")
4305 "Regular expression matching a time stamp or time stamp range.
4306 The time stamps may be either active or inactive.")
4308 (defvar org-emph-face nil)
4310 (defun org-do-emphasis-faces (limit)
4311 "Run through the buffer and add overlays to links."
4312 (let (rtn a)
4313 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4314 (if (not (= (char-after (match-beginning 3))
4315 (char-after (match-beginning 4))))
4316 (progn
4317 (setq rtn t)
4318 (setq a (assoc (match-string 3) org-emphasis-alist))
4319 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4320 'face
4321 (nth 1 a))
4322 (and (nth 4 a)
4323 (org-remove-flyspell-overlays-in
4324 (match-beginning 0) (match-end 0)))
4325 (add-text-properties (match-beginning 2) (match-end 2)
4326 '(font-lock-multiline t))
4327 (when org-hide-emphasis-markers
4328 (add-text-properties (match-end 4) (match-beginning 5)
4329 '(invisible org-link))
4330 (add-text-properties (match-beginning 3) (match-end 3)
4331 '(invisible org-link)))))
4332 (backward-char 1))
4333 rtn))
4335 (defun org-emphasize (&optional char)
4336 "Insert or change an emphasis, i.e. a font like bold or italic.
4337 If there is an active region, change that region to a new emphasis.
4338 If there is no region, just insert the marker characters and position
4339 the cursor between them.
4340 CHAR should be either the marker character, or the first character of the
4341 HTML tag associated with that emphasis. If CHAR is a space, the means
4342 to remove the emphasis of the selected region.
4343 If char is not given (for example in an interactive call) it
4344 will be prompted for."
4345 (interactive)
4346 (let ((eal org-emphasis-alist) e det
4347 (erc org-emphasis-regexp-components)
4348 (prompt "")
4349 (string "") beg end move tag c s)
4350 (if (org-region-active-p)
4351 (setq beg (region-beginning) end (region-end)
4352 string (buffer-substring beg end))
4353 (setq move t))
4355 (while (setq e (pop eal))
4356 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4357 c (aref tag 0))
4358 (push (cons c (string-to-char (car e))) det)
4359 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4360 (substring tag 1)))))
4361 (setq det (nreverse det))
4362 (unless char
4363 (message "%s" (concat "Emphasis marker or tag:" prompt))
4364 (setq char (read-char-exclusive)))
4365 (setq char (or (cdr (assoc char det)) char))
4366 (if (equal char ?\ )
4367 (setq s "" move nil)
4368 (unless (assoc (char-to-string char) org-emphasis-alist)
4369 (error "No such emphasis marker: \"%c\"" char))
4370 (setq s (char-to-string char)))
4371 (while (and (> (length string) 1)
4372 (equal (substring string 0 1) (substring string -1))
4373 (assoc (substring string 0 1) org-emphasis-alist))
4374 (setq string (substring string 1 -1)))
4375 (setq string (concat s string s))
4376 (if beg (delete-region beg end))
4377 (unless (or (bolp)
4378 (string-match (concat "[" (nth 0 erc) "\n]")
4379 (char-to-string (char-before (point)))))
4380 (insert " "))
4381 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4382 (char-to-string (char-after (point))))
4383 (insert " ") (backward-char 1))
4384 (insert string)
4385 (and move (backward-char 1))))
4387 (defconst org-nonsticky-props
4388 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4390 (defsubst org-rear-nonsticky-at (pos)
4391 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4393 (defun org-activate-plain-links (limit)
4394 "Run through the buffer and add overlays to links."
4395 (catch 'exit
4396 (let (f)
4397 (if (re-search-forward org-plain-link-re limit t)
4398 (progn
4399 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4400 (setq f (get-text-property (match-beginning 0) 'face))
4401 (if (or (eq f 'org-tag)
4402 (and (listp f) (memq 'org-tag f)))
4404 (add-text-properties (match-beginning 0) (match-end 0)
4405 (list 'mouse-face 'highlight
4406 'keymap org-mouse-map))
4407 (org-rear-nonsticky-at (match-end 0)))
4408 t)))))
4410 (defun org-activate-code (limit)
4411 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4412 (progn
4413 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4414 (remove-text-properties (match-beginning 0) (match-end 0)
4415 '(display t invisible t intangible t))
4416 t)))
4418 (defun org-fontify-meta-lines-and-blocks (limit)
4419 "Fontify #+ lines and blocks, in the correct ways."
4420 (let ((case-fold-search t))
4421 (if (re-search-forward
4422 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4423 limit t)
4424 (let ((beg (match-beginning 0))
4425 (beg1 (line-beginning-position 2))
4426 (dc1 (downcase (match-string 2)))
4427 (dc3 (downcase (match-string 3)))
4428 end end1 quoting)
4429 (cond
4430 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4431 ;; a single line of backend-specific content
4432 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4433 (remove-text-properties (match-beginning 0) (match-end 0)
4434 '(display t invisible t intangible t))
4435 (add-text-properties (match-beginning 1) (match-end 3)
4436 '(font-lock-fontified t face org-meta-line))
4437 (add-text-properties (match-beginning 6) (match-end 6)
4438 '(font-lock-fontified t face org-block))
4440 ((and (match-end 4) (equal dc3 "begin"))
4441 ;; Truely a block
4442 (setq quoting (member (downcase (match-string 5))
4443 org-protecting-blocks))
4444 (when (re-search-forward
4445 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4446 nil t) ;; on purpose, we look further than LIMIT
4447 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4448 (when quoting
4449 (remove-text-properties beg end
4450 '(display t invisible t intangible t)))
4451 (add-text-properties
4452 beg end
4453 '(font-lock-fontified t font-lock-multiline t))
4454 (add-text-properties beg beg1 '(face org-meta-line))
4455 (add-text-properties end1 end '(face org-meta-line))
4456 (when quoting
4457 (add-text-properties beg1 end1 '(face org-block)))
4459 ((not (member (char-after beg) '(?\ ?\t)))
4460 ;; just any other in-buffer setting, but not indented
4461 (add-text-properties
4462 beg (match-end 0)
4463 '(font-lock-fontified t face org-meta-line))
4465 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4466 "orgtbl:" "tblfm:" "tblname:"))
4467 (and (match-end 4) (equal dc3 "attr")))
4468 (add-text-properties
4469 beg (match-end 0)
4470 '(font-lock-fontified t face org-meta-line))
4472 ((member dc3 '(" " ""))
4473 (add-text-properties
4474 beg (match-end 0)
4475 '(font-lock-fontified t face font-lock-comment-face)))
4476 (t nil))))))
4478 (defun org-activate-angle-links (limit)
4479 "Run through the buffer and add overlays to links."
4480 (if (re-search-forward org-angle-link-re limit t)
4481 (progn
4482 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4483 (add-text-properties (match-beginning 0) (match-end 0)
4484 (list 'mouse-face 'highlight
4485 'keymap org-mouse-map))
4486 (org-rear-nonsticky-at (match-end 0))
4487 t)))
4489 (defun org-activate-footnote-links (limit)
4490 "Run through the buffer and add overlays to links."
4491 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4492 limit t)
4493 (progn
4494 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4495 (add-text-properties (match-beginning 2) (match-end 2)
4496 (list 'mouse-face 'highlight
4497 'keymap org-mouse-map
4498 'help-echo
4499 (if (= (point-at-bol) (match-beginning 2))
4500 "Footnote definition"
4501 "Footnote reference")
4503 (org-rear-nonsticky-at (match-end 2))
4504 t)))
4506 (defun org-activate-bracket-links (limit)
4507 "Run through the buffer and add overlays to bracketed links."
4508 (if (re-search-forward org-bracket-link-regexp limit t)
4509 (let* ((help (concat "LINK: "
4510 (org-match-string-no-properties 1)))
4511 ;; FIXME: above we should remove the escapes.
4512 ;; but that requires another match, protecting match data,
4513 ;; a lot of overhead for font-lock.
4514 (ip (org-maybe-intangible
4515 (list 'invisible 'org-link
4516 'keymap org-mouse-map 'mouse-face 'highlight
4517 'font-lock-multiline t 'help-echo help)))
4518 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4519 'font-lock-multiline t 'help-echo help)))
4520 ;; We need to remove the invisible property here. Table narrowing
4521 ;; may have made some of this invisible.
4522 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4523 (remove-text-properties (match-beginning 0) (match-end 0)
4524 '(invisible nil))
4525 (if (match-end 3)
4526 (progn
4527 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4528 (org-rear-nonsticky-at (match-beginning 3))
4529 (add-text-properties (match-beginning 3) (match-end 3) vp)
4530 (org-rear-nonsticky-at (match-end 3))
4531 (add-text-properties (match-end 3) (match-end 0) ip)
4532 (org-rear-nonsticky-at (match-end 0)))
4533 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4534 (org-rear-nonsticky-at (match-beginning 1))
4535 (add-text-properties (match-beginning 1) (match-end 1) vp)
4536 (org-rear-nonsticky-at (match-end 1))
4537 (add-text-properties (match-end 1) (match-end 0) ip)
4538 (org-rear-nonsticky-at (match-end 0)))
4539 t)))
4541 (defun org-activate-dates (limit)
4542 "Run through the buffer and add overlays to dates."
4543 (if (re-search-forward org-tsr-regexp-both limit t)
4544 (progn
4545 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4546 (add-text-properties (match-beginning 0) (match-end 0)
4547 (list 'mouse-face 'highlight
4548 'keymap org-mouse-map))
4549 (org-rear-nonsticky-at (match-end 0))
4550 (when org-display-custom-times
4551 (if (match-end 3)
4552 (org-display-custom-time (match-beginning 3) (match-end 3)))
4553 (org-display-custom-time (match-beginning 1) (match-end 1)))
4554 t)))
4556 (defvar org-target-link-regexp nil
4557 "Regular expression matching radio targets in plain text.")
4558 (make-variable-buffer-local 'org-target-link-regexp)
4559 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4560 "Regular expression matching a link target.")
4561 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4562 "Regular expression matching a radio target.")
4563 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4564 "Regular expression matching any target.")
4566 (defun org-activate-target-links (limit)
4567 "Run through the buffer and add overlays to target matches."
4568 (when org-target-link-regexp
4569 (let ((case-fold-search t))
4570 (if (re-search-forward org-target-link-regexp limit t)
4571 (progn
4572 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4573 (add-text-properties (match-beginning 0) (match-end 0)
4574 (list 'mouse-face 'highlight
4575 'keymap org-mouse-map
4576 'help-echo "Radio target link"
4577 'org-linked-text t))
4578 (org-rear-nonsticky-at (match-end 0))
4579 t)))))
4581 (defun org-update-radio-target-regexp ()
4582 "Find all radio targets in this file and update the regular expression."
4583 (interactive)
4584 (when (memq 'radio org-activate-links)
4585 (setq org-target-link-regexp
4586 (org-make-target-link-regexp (org-all-targets 'radio)))
4587 (org-restart-font-lock)))
4589 (defun org-hide-wide-columns (limit)
4590 (let (s e)
4591 (setq s (text-property-any (point) (or limit (point-max))
4592 'org-cwidth t))
4593 (when s
4594 (setq e (next-single-property-change s 'org-cwidth))
4595 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4596 (goto-char e)
4597 t)))
4599 (defvar org-latex-and-specials-regexp nil
4600 "Regular expression for highlighting export special stuff.")
4601 (defvar org-match-substring-regexp)
4602 (defvar org-match-substring-with-braces-regexp)
4604 ;; This should be with the exporter code, but we also use if for font-locking
4605 (defconst org-export-html-special-string-regexps
4606 '(("\\\\-" . "&shy;")
4607 ("---\\([^-]\\)" . "&mdash;\\1")
4608 ("--\\([^-]\\)" . "&ndash;\\1")
4609 ("\\.\\.\\." . "&hellip;"))
4610 "Regular expressions for special string conversion.")
4613 (defun org-compute-latex-and-specials-regexp ()
4614 "Compute regular expression for stuff treated specially by exporters."
4615 (if (not org-highlight-latex-fragments-and-specials)
4616 (org-set-local 'org-latex-and-specials-regexp nil)
4617 (require 'org-exp)
4618 (let*
4619 ((matchers (plist-get org-format-latex-options :matchers))
4620 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4621 org-latex-regexps)))
4622 (options (org-combine-plists (org-default-export-plist)
4623 (org-infile-export-plist)))
4624 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4625 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4626 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4627 (org-export-html-expand (plist-get options :expand-quoted-html))
4628 (org-export-with-special-strings (plist-get options :special-strings))
4629 (re-sub
4630 (cond
4631 ((equal org-export-with-sub-superscripts '{})
4632 (list org-match-substring-with-braces-regexp))
4633 (org-export-with-sub-superscripts
4634 (list org-match-substring-regexp))
4635 (t nil)))
4636 (re-latex
4637 (if org-export-with-LaTeX-fragments
4638 (mapcar (lambda (x) (nth 1 x)) latexs)))
4639 (re-macros
4640 (if org-export-with-TeX-macros
4641 (list (concat "\\\\"
4642 (regexp-opt
4643 (append (mapcar 'car org-html-entities)
4644 (if (boundp 'org-latex-entities)
4645 (mapcar (lambda (x)
4646 (or (car-safe x) x))
4647 org-latex-entities)
4648 nil))
4649 'words))) ; FIXME
4651 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4652 (re-special (if org-export-with-special-strings
4653 (mapcar (lambda (x) (car x))
4654 org-export-html-special-string-regexps)))
4655 (re-rest
4656 (delq nil
4657 (list
4658 (if org-export-html-expand "@<[^>\n]+>")
4659 ))))
4660 (org-set-local
4661 'org-latex-and-specials-regexp
4662 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4663 re-rest) "\\|")))))
4665 (defun org-do-latex-and-special-faces (limit)
4666 "Run through the buffer and add overlays to links."
4667 (when org-latex-and-specials-regexp
4668 (let (rtn d)
4669 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4670 limit t))
4671 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4672 'face))
4673 '(org-code org-verbatim underline)))
4674 (progn
4675 (setq rtn t
4676 d (cond ((member (char-after (1+ (match-beginning 0)))
4677 '(?_ ?^)) 1)
4678 (t 0)))
4679 (font-lock-prepend-text-property
4680 (+ d (match-beginning 0)) (match-end 0)
4681 'face 'org-latex-and-export-specials)
4682 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4683 '(font-lock-multiline t)))))
4684 rtn)))
4686 (defun org-restart-font-lock ()
4687 "Restart font-lock-mode, to force refontification."
4688 (when (and (boundp 'font-lock-mode) font-lock-mode)
4689 (font-lock-mode -1)
4690 (font-lock-mode 1)))
4692 (defun org-all-targets (&optional radio)
4693 "Return a list of all targets in this file.
4694 With optional argument RADIO, only find radio targets."
4695 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4696 rtn)
4697 (save-excursion
4698 (goto-char (point-min))
4699 (while (re-search-forward re nil t)
4700 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4701 rtn)))
4703 (defun org-make-target-link-regexp (targets)
4704 "Make regular expression matching all strings in TARGETS.
4705 The regular expression finds the targets also if there is a line break
4706 between words."
4707 (and targets
4708 (concat
4709 "\\<\\("
4710 (mapconcat
4711 (lambda (x)
4712 (while (string-match " +" x)
4713 (setq x (replace-match "\\s-+" t t x)))
4715 targets
4716 "\\|")
4717 "\\)\\>")))
4719 (defun org-activate-tags (limit)
4720 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4721 (progn
4722 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4723 (add-text-properties (match-beginning 1) (match-end 1)
4724 (list 'mouse-face 'highlight
4725 'keymap org-mouse-map))
4726 (org-rear-nonsticky-at (match-end 1))
4727 t)))
4729 (defun org-outline-level ()
4730 "Compute the outline level of the heading at point.
4731 This function assumes that the cursor is at the beginning of a line matched
4732 by outline-regexp. Otherwise it returns garbage.
4733 If this is called at a normal headline, the level is the number of stars.
4734 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4735 For plain list items, if they are matched by `outline-regexp', this returns
4736 1000 plus the line indentation."
4737 (save-excursion
4738 (looking-at outline-regexp)
4739 (if (match-beginning 1)
4740 (+ (org-get-string-indentation (match-string 1)) 1000)
4741 (1- (- (match-end 0) (match-beginning 0))))))
4743 (defvar org-font-lock-keywords nil)
4745 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4746 "Regular expression matching a property line.")
4748 (defvar org-font-lock-hook nil
4749 "Functions to be called for special font lock stuff.")
4751 (defun org-font-lock-hook (limit)
4752 (run-hook-with-args 'org-font-lock-hook limit))
4754 (defun org-set-font-lock-defaults ()
4755 (let* ((em org-fontify-emphasized-text)
4756 (lk org-activate-links)
4757 (org-font-lock-extra-keywords
4758 (list
4759 ;; Call the hook
4760 '(org-font-lock-hook)
4761 ;; Headlines
4762 `(,(if org-fontify-whole-heading-line
4763 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4764 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4765 (1 (org-get-level-face 1))
4766 (2 (org-get-level-face 2))
4767 (3 (org-get-level-face 3)))
4768 ;; Table lines
4769 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4770 (1 'org-table t))
4771 ;; Table internals
4772 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4773 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4774 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4775 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4776 ;; Drawers
4777 (list org-drawer-regexp '(0 'org-special-keyword t))
4778 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4779 ;; Properties
4780 (list org-property-re
4781 '(1 'org-special-keyword t)
4782 '(3 'org-property-value t))
4783 ;; Links
4784 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4785 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4786 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4787 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4788 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4789 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4790 (if (memq 'footnote lk) '(org-activate-footnote-links
4791 (2 'org-footnote t)))
4792 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4793 '(org-hide-wide-columns (0 nil append))
4794 ;; TODO lines
4795 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4796 '(1 (org-get-todo-face 1) t))
4797 ;; DONE
4798 (if org-fontify-done-headline
4799 (list (concat "^[*]+ +\\<\\("
4800 (mapconcat 'regexp-quote org-done-keywords "\\|")
4801 "\\)\\(.*\\)")
4802 '(2 'org-headline-done t))
4803 nil)
4804 ;; Priorities
4805 '(org-font-lock-add-priority-faces)
4806 ;; Tags
4807 '(org-font-lock-add-tag-faces)
4808 ;; Special keywords
4809 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4810 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4811 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4812 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4813 ;; Emphasis
4814 (if em
4815 (if (featurep 'xemacs)
4816 '(org-do-emphasis-faces (0 nil append))
4817 '(org-do-emphasis-faces)))
4818 ;; Checkboxes
4819 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4820 2 'org-checkbox prepend)
4821 (if org-provide-checkbox-statistics
4822 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4823 (0 (org-get-checkbox-statistics-face) t)))
4824 ;; Description list items
4825 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4826 2 'bold prepend)
4827 ;; ARCHIVEd headings
4828 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4829 '(1 'org-archived prepend))
4830 ;; Specials
4831 '(org-do-latex-and-special-faces)
4832 ;; Code
4833 '(org-activate-code (1 'org-code t))
4834 ;; COMMENT
4835 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4836 "\\|" org-quote-string "\\)\\>")
4837 '(1 'org-special-keyword t))
4838 '("^#.*" (0 'font-lock-comment-face t))
4839 ;; Blocks and meta lines
4840 '(org-fontify-meta-lines-and-blocks)
4842 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4843 ;; Now set the full font-lock-keywords
4844 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4845 (org-set-local 'font-lock-defaults
4846 '(org-font-lock-keywords t nil nil backward-paragraph))
4847 (kill-local-variable 'font-lock-keywords) nil))
4849 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4850 "Fontify string S like in Org-mode"
4851 (with-temp-buffer
4852 (insert s)
4853 (let ((org-odd-levels-only odd-levels))
4854 (org-mode)
4855 (font-lock-fontify-buffer)
4856 (buffer-string))))
4858 (defvar org-m nil)
4859 (defvar org-l nil)
4860 (defvar org-f nil)
4861 (defun org-get-level-face (n)
4862 "Get the right face for match N in font-lock matching of headlines."
4863 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4864 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4865 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4866 (cond
4867 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4868 ((eq n 2) org-f)
4869 (t (if org-level-color-stars-only nil org-f))))
4871 (defun org-get-todo-face (kwd)
4872 "Get the right face for a TODO keyword KWD.
4873 If KWD is a number, get the corresponding match group."
4874 (if (numberp kwd) (setq kwd (match-string kwd)))
4875 (or (cdr (assoc kwd org-todo-keyword-faces))
4876 (and (member kwd org-done-keywords) 'org-done)
4877 'org-todo))
4879 (defun org-font-lock-add-tag-faces (limit)
4880 "Add the special tag faces."
4881 (when (and org-tag-faces org-tags-special-faces-re)
4882 (while (re-search-forward org-tags-special-faces-re limit t)
4883 (add-text-properties (match-beginning 1) (match-end 1)
4884 (list 'face (org-get-tag-face 1)
4885 'font-lock-fontified t))
4886 (backward-char 1))))
4888 (defun org-font-lock-add-priority-faces (limit)
4889 "Add the special priority faces."
4890 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4891 (add-text-properties
4892 (match-beginning 0) (match-end 0)
4893 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4894 org-priority-faces))
4895 'org-special-keyword)
4896 'font-lock-fontified t))))
4898 (defun org-get-tag-face (kwd)
4899 "Get the right face for a TODO keyword KWD.
4900 If KWD is a number, get the corresponding match group."
4901 (if (numberp kwd) (setq kwd (match-string kwd)))
4902 (or (cdr (assoc kwd org-tag-faces))
4903 'org-tag))
4905 (defun org-unfontify-region (beg end &optional maybe_loudly)
4906 "Remove fontification and activation overlays from links."
4907 (font-lock-default-unfontify-region beg end)
4908 (let* ((buffer-undo-list t)
4909 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4910 (inhibit-modification-hooks t)
4911 deactivate-mark buffer-file-name buffer-file-truename)
4912 (remove-text-properties beg end
4913 '(mouse-face t keymap t org-linked-text t
4914 invisible t intangible t
4915 line-prefix t wrap-prefix t
4916 org-no-flyspell t))))
4918 ;;;; Visibility cycling, including org-goto and indirect buffer
4920 ;;; Cycling
4922 (defvar org-cycle-global-status nil)
4923 (make-variable-buffer-local 'org-cycle-global-status)
4924 (defvar org-cycle-subtree-status nil)
4925 (make-variable-buffer-local 'org-cycle-subtree-status)
4927 ;;;###autoload
4929 (defvar org-inlinetask-min-level)
4931 (defun org-cycle (&optional arg)
4932 "TAB-action and visibility cycling for Org-mode.
4934 This is the command invoked in Org-mode by the TAB key. Its main purpose
4935 is outine visibility cycling, but it also invokes other actions
4936 in special contexts.
4938 - When this function is called with a prefix argument, rotate the entire
4939 buffer through 3 states (global cycling)
4940 1. OVERVIEW: Show only top-level headlines.
4941 2. CONTENTS: Show all headlines of all levels, but no body text.
4942 3. SHOW ALL: Show everything.
4943 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4944 determined by the variable `org-startup-folded', and by any VISIBILITY
4945 properties in the buffer.
4946 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4947 including any drawers.
4949 - When inside a table, re-align the table and move to the next field.
4951 - When point is at the beginning of a headline, rotate the subtree started
4952 by this line through 3 different states (local cycling)
4953 1. FOLDED: Only the main headline is shown.
4954 2. CHILDREN: The main headline and the direct children are shown.
4955 From this state, you can move to one of the children
4956 and zoom in further.
4957 3. SUBTREE: Show the entire subtree, including body text.
4958 If there is no subtree, switch directly from CHILDREN to FOLDED.
4960 - When there is a numeric prefix, go up to a heading with level ARG, do
4961 a `show-subtree' and return to the previous cursor position. If ARG
4962 is negative, go up that many levels.
4964 - When point is not at the beginning of a headline, execute the global
4965 binding for TAB, which is re-indenting the line. See the option
4966 `org-cycle-emulate-tab' for details.
4968 - Special case: if point is at the beginning of the buffer and there is
4969 no headline in line 1, this function will act as if called with prefix arg.
4970 But only if also the variable `org-cycle-global-at-bob' is t."
4971 (interactive "P")
4972 (org-load-modules-maybe)
4973 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
4974 (and org-cycle-level-after-item/entry-creation
4975 (or (org-cycle-level)
4976 (org-cycle-item-indentation))))
4977 (let* ((limit-level
4978 (or org-cycle-max-level
4979 (and (boundp 'org-inlinetask-min-level)
4980 org-inlinetask-min-level
4981 (1- org-inlinetask-min-level))))
4982 (nstars (and limit-level
4983 (if org-odd-levels-only
4984 (and limit-level (1- (* limit-level 2)))
4985 limit-level)))
4986 (outline-regexp
4987 (cond
4988 ((not (org-mode-p)) outline-regexp)
4989 ((or (eq org-cycle-include-plain-lists 'integrate)
4990 (and org-cycle-include-plain-lists (org-at-item-p)))
4991 (concat "\\(?:\\*"
4992 (if nstars (format "\\{1,%d\\}" nstars) "+")
4993 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4994 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4995 (bob-special (and org-cycle-global-at-bob (bobp)
4996 (not (looking-at outline-regexp))))
4997 (org-cycle-hook
4998 (if bob-special
4999 (delq 'org-optimize-window-after-visibility-change
5000 (copy-sequence org-cycle-hook))
5001 org-cycle-hook))
5002 (pos (point)))
5004 (if (or bob-special (equal arg '(4)))
5005 ;; special case: use global cycling
5006 (setq arg t))
5008 (cond
5010 ((equal arg '(16))
5011 (org-set-startup-visibility)
5012 (message "Startup visibility, plus VISIBILITY properties"))
5014 ((equal arg '(64))
5015 (show-all)
5016 (message "Entire buffer visible, including drawers"))
5018 ((org-at-table-p 'any)
5019 ;; Enter the table or move to the next field in the table
5020 (or (org-table-recognize-table.el)
5021 (progn
5022 (if arg (org-table-edit-field t)
5023 (org-table-justify-field-maybe)
5024 (call-interactively 'org-table-next-field)))))
5026 ((run-hook-with-args-until-success
5027 'org-tab-after-check-for-table-hook))
5029 ((eq arg t) ;; Global cycling
5030 (org-cycle-internal-global))
5032 ((and org-drawers org-drawer-regexp
5033 (save-excursion
5034 (beginning-of-line 1)
5035 (looking-at org-drawer-regexp)))
5036 ;; Toggle block visibility
5037 (org-flag-drawer
5038 (not (get-char-property (match-end 0) 'invisible))))
5040 ((integerp arg)
5041 ;; Show-subtree, ARG levels up from here.
5042 (save-excursion
5043 (org-back-to-heading)
5044 (outline-up-heading (if (< arg 0) (- arg)
5045 (- (funcall outline-level) arg)))
5046 (org-show-subtree)))
5048 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5049 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5051 (org-cycle-internal-local))
5053 ;; TAB emulation and template completion
5054 (buffer-read-only (org-back-to-heading))
5056 ((run-hook-with-args-until-success
5057 'org-tab-after-check-for-cycling-hook))
5059 ((org-try-structure-completion))
5061 ((org-try-cdlatex-tab))
5063 ((run-hook-with-args-until-success
5064 'org-tab-before-tab-emulation-hook))
5066 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5067 (or (not (bolp))
5068 (not (looking-at outline-regexp))))
5069 (call-interactively (global-key-binding "\t")))
5071 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5072 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5073 (or (and (eq org-cycle-emulate-tab 'white)
5074 (= (match-end 0) (point-at-eol)))
5075 (and (eq org-cycle-emulate-tab 'whitestart)
5076 (>= (match-end 0) pos))))
5078 (eq org-cycle-emulate-tab t))
5079 (call-interactively (global-key-binding "\t")))
5081 (t (save-excursion
5082 (org-back-to-heading)
5083 (org-cycle)))))))
5085 (defun org-cycle-internal-global ()
5086 "Do the global cycling action."
5087 (cond
5088 ((and (eq last-command this-command)
5089 (eq org-cycle-global-status 'overview))
5090 ;; We just created the overview - now do table of contents
5091 ;; This can be slow in very large buffers, so indicate action
5092 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5093 (message "CONTENTS...")
5094 (org-content)
5095 (message "CONTENTS...done")
5096 (setq org-cycle-global-status 'contents)
5097 (run-hook-with-args 'org-cycle-hook 'contents))
5099 ((and (eq last-command this-command)
5100 (eq org-cycle-global-status 'contents))
5101 ;; We just showed the table of contents - now show everything
5102 (run-hook-with-args 'org-pre-cycle-hook 'all)
5103 (show-all)
5104 (message "SHOW ALL")
5105 (setq org-cycle-global-status 'all)
5106 (run-hook-with-args 'org-cycle-hook 'all))
5109 ;; Default action: go to overview
5110 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5111 (org-overview)
5112 (message "OVERVIEW")
5113 (setq org-cycle-global-status 'overview)
5114 (run-hook-with-args 'org-cycle-hook 'overview))))
5116 (defun org-cycle-internal-local ()
5117 "Do the local cycling action."
5118 (org-back-to-heading)
5119 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5120 ;; First, some boundaries
5121 (save-excursion
5122 (org-back-to-heading)
5123 (setq level (funcall outline-level))
5124 (save-excursion
5125 (beginning-of-line 2)
5126 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5127 ; XEmacs does not have `next-single-char-property-change'
5128 ; I'm not sure about Emacs 21.
5129 (while (and (not (eobp)) ;; this is like `next-line'
5130 (get-char-property (1- (point)) 'invisible))
5131 (beginning-of-line 2))
5132 (while (and (not (eobp)) ;; this is like `next-line'
5133 (get-char-property (1- (point)) 'invisible))
5134 (goto-char (next-single-char-property-change (point) 'invisible))
5135 ;;;??? (or (bolp) (beginning-of-line 2))))
5136 (and (eolp) (beginning-of-line 2))))
5137 (setq eol (point)))
5138 (outline-end-of-heading) (setq eoh (point))
5139 (save-excursion
5140 (outline-next-heading)
5141 (setq has-children (and (org-at-heading-p t)
5142 (> (funcall outline-level) level))))
5143 (org-end-of-subtree t)
5144 (unless (eobp)
5145 (skip-chars-forward " \t\n")
5146 (beginning-of-line 1) ; in case this is an item
5148 (setq eos (if (eobp) (point) (1- (point)))))
5149 ;; Find out what to do next and set `this-command'
5150 (cond
5151 ((= eos eoh)
5152 ;; Nothing is hidden behind this heading
5153 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5154 (message "EMPTY ENTRY")
5155 (setq org-cycle-subtree-status nil)
5156 (save-excursion
5157 (goto-char eos)
5158 (outline-next-heading)
5159 (if (org-invisible-p) (org-flag-heading nil))))
5160 ((and (or (>= eol eos)
5161 (not (string-match "\\S-" (buffer-substring eol eos))))
5162 (or has-children
5163 (not (setq children-skipped
5164 org-cycle-skip-children-state-if-no-children))))
5165 ;; Entire subtree is hidden in one line: children view
5166 (run-hook-with-args 'org-pre-cycle-hook 'children)
5167 (org-show-entry)
5168 (show-children)
5169 (message "CHILDREN")
5170 (save-excursion
5171 (goto-char eos)
5172 (outline-next-heading)
5173 (if (org-invisible-p) (org-flag-heading nil)))
5174 (setq org-cycle-subtree-status 'children)
5175 (run-hook-with-args 'org-cycle-hook 'children))
5176 ((or children-skipped
5177 (and (eq last-command this-command)
5178 (eq org-cycle-subtree-status 'children)))
5179 ;; We just showed the children, or no children are there,
5180 ;; now show everything.
5181 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5182 (org-show-subtree)
5183 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5184 (setq org-cycle-subtree-status 'subtree)
5185 (run-hook-with-args 'org-cycle-hook 'subtree))
5187 ;; Default action: hide the subtree.
5188 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5189 (hide-subtree)
5190 (message "FOLDED")
5191 (setq org-cycle-subtree-status 'folded)
5192 (run-hook-with-args 'org-cycle-hook 'folded)))))
5194 ;;;###autoload
5195 (defun org-global-cycle (&optional arg)
5196 "Cycle the global visibility. For details see `org-cycle'.
5197 With C-u prefix arg, switch to startup visibility.
5198 With a numeric prefix, show all headlines up to that level."
5199 (interactive "P")
5200 (let ((org-cycle-include-plain-lists
5201 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5202 (cond
5203 ((integerp arg)
5204 (show-all)
5205 (hide-sublevels arg)
5206 (setq org-cycle-global-status 'contents))
5207 ((equal arg '(4))
5208 (org-set-startup-visibility)
5209 (message "Startup visibility, plus VISIBILITY properties."))
5211 (org-cycle '(4))))))
5213 (defun org-set-startup-visibility ()
5214 "Set the visibility required by startup options and properties."
5215 (cond
5216 ((eq org-startup-folded t)
5217 (org-cycle '(4)))
5218 ((eq org-startup-folded 'content)
5219 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5220 (org-cycle '(4)) (org-cycle '(4)))))
5221 (unless (eq org-startup-folded 'showeverything)
5222 (if org-hide-block-startup (org-hide-block-all))
5223 (org-set-visibility-according-to-property 'no-cleanup)
5224 (org-cycle-hide-archived-subtrees 'all)
5225 (org-cycle-hide-drawers 'all)
5226 (org-cycle-show-empty-lines 'all)))
5228 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5229 "Switch subtree visibilities according to :VISIBILITY: property."
5230 (interactive)
5231 (let (org-show-entry-below state)
5232 (save-excursion
5233 (goto-char (point-min))
5234 (while (re-search-forward
5235 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5236 nil t)
5237 (setq state (match-string 1))
5238 (save-excursion
5239 (org-back-to-heading t)
5240 (hide-subtree)
5241 (org-reveal)
5242 (cond
5243 ((equal state '("fold" "folded"))
5244 (hide-subtree))
5245 ((equal state "children")
5246 (org-show-hidden-entry)
5247 (show-children))
5248 ((equal state "content")
5249 (save-excursion
5250 (save-restriction
5251 (org-narrow-to-subtree)
5252 (org-content))))
5253 ((member state '("all" "showall"))
5254 (show-subtree)))))
5255 (unless no-cleanup
5256 (org-cycle-hide-archived-subtrees 'all)
5257 (org-cycle-hide-drawers 'all)
5258 (org-cycle-show-empty-lines 'all)))))
5260 (defun org-overview ()
5261 "Switch to overview mode, showing only top-level headlines.
5262 Really, this shows all headlines with level equal or greater than the level
5263 of the first headline in the buffer. This is important, because if the
5264 first headline is not level one, then (hide-sublevels 1) gives confusing
5265 results."
5266 (interactive)
5267 (let ((level (save-excursion
5268 (goto-char (point-min))
5269 (if (re-search-forward (concat "^" outline-regexp) nil t)
5270 (progn
5271 (goto-char (match-beginning 0))
5272 (funcall outline-level))))))
5273 (and level (hide-sublevels level))))
5275 (defun org-content (&optional arg)
5276 "Show all headlines in the buffer, like a table of contents.
5277 With numerical argument N, show content up to level N."
5278 (interactive "P")
5279 (save-excursion
5280 ;; Visit all headings and show their offspring
5281 (and (integerp arg) (org-overview))
5282 (goto-char (point-max))
5283 (catch 'exit
5284 (while (and (progn (condition-case nil
5285 (outline-previous-visible-heading 1)
5286 (error (goto-char (point-min))))
5288 (looking-at outline-regexp))
5289 (if (integerp arg)
5290 (show-children (1- arg))
5291 (show-branches))
5292 (if (bobp) (throw 'exit nil))))))
5295 (defun org-optimize-window-after-visibility-change (state)
5296 "Adjust the window after a change in outline visibility.
5297 This function is the default value of the hook `org-cycle-hook'."
5298 (when (get-buffer-window (current-buffer))
5299 (cond
5300 ((eq state 'content) nil)
5301 ((eq state 'all) nil)
5302 ((eq state 'folded) nil)
5303 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5304 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5306 ;; FIXME: no longer in use
5307 (defun org-compact-display-after-subtree-move ()
5308 "Show a compacter version of the tree of the entry's parent."
5309 (save-excursion
5310 (if (org-up-heading-safe)
5311 (progn
5312 (hide-subtree)
5313 (show-entry)
5314 (show-children)
5315 (org-cycle-show-empty-lines 'children)
5316 (org-cycle-hide-drawers 'children))
5317 (org-overview))))
5319 (defun org-remove-empty-overlays-at (pos)
5320 "Remove outline overlays that do not contain non-white stuff."
5321 (mapc
5322 (lambda (o)
5323 (and (eq 'outline (org-overlay-get o 'invisible))
5324 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5325 (org-overlay-end o))))
5326 (org-delete-overlay o)))
5327 (org-overlays-at pos)))
5329 (defun org-clean-visibility-after-subtree-move ()
5330 "Fix visibility issues after moving a subtree."
5331 ;; First, find a reasonable region to look at:
5332 ;; Start two siblings above, end three below
5333 (let* ((beg (save-excursion
5334 (and (org-get-last-sibling)
5335 (org-get-last-sibling))
5336 (point)))
5337 (end (save-excursion
5338 (and (org-get-next-sibling)
5339 (org-get-next-sibling)
5340 (org-get-next-sibling))
5341 (if (org-at-heading-p)
5342 (point-at-eol)
5343 (point))))
5344 (level (looking-at "\\*+"))
5345 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5346 (save-excursion
5347 (save-restriction
5348 (narrow-to-region beg end)
5349 (when re
5350 ;; Properly fold already folded siblings
5351 (goto-char (point-min))
5352 (while (re-search-forward re nil t)
5353 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5354 (hide-entry))))
5355 (org-cycle-show-empty-lines 'overview)
5356 (org-cycle-hide-drawers 'overview)))))
5358 (defun org-cycle-show-empty-lines (state)
5359 "Show empty lines above all visible headlines.
5360 The region to be covered depends on STATE when called through
5361 `org-cycle-hook'. Lisp program can use t for STATE to get the
5362 entire buffer covered. Note that an empty line is only shown if there
5363 are at least `org-cycle-separator-lines' empty lines before the headline."
5364 (when (not (= org-cycle-separator-lines 0))
5365 (save-excursion
5366 (let* ((n (abs org-cycle-separator-lines))
5367 (re (cond
5368 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5369 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5370 (t (let ((ns (number-to-string (- n 2))))
5371 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5372 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5373 beg end b e)
5374 (cond
5375 ((memq state '(overview contents t))
5376 (setq beg (point-min) end (point-max)))
5377 ((memq state '(children folded))
5378 (setq beg (point) end (progn (org-end-of-subtree t t)
5379 (beginning-of-line 2)
5380 (point)))))
5381 (when beg
5382 (goto-char beg)
5383 (while (re-search-forward re end t)
5384 (unless (get-char-property (match-end 1) 'invisible)
5385 (setq e (match-end 1))
5386 (if (< org-cycle-separator-lines 0)
5387 (setq b (save-excursion
5388 (goto-char (match-beginning 0))
5389 (org-back-over-empty-lines)
5390 (if (save-excursion
5391 (goto-char (max (point-min) (1- (point))))
5392 (org-on-heading-p))
5393 (1- (point))
5394 (point))))
5395 (setq b (match-beginning 1)))
5396 (outline-flag-region b e nil)))))))
5397 ;; Never hide empty lines at the end of the file.
5398 (save-excursion
5399 (goto-char (point-max))
5400 (outline-previous-heading)
5401 (outline-end-of-heading)
5402 (if (and (looking-at "[ \t\n]+")
5403 (= (match-end 0) (point-max)))
5404 (outline-flag-region (point) (match-end 0) nil))))
5406 (defun org-show-empty-lines-in-parent ()
5407 "Move to the parent and re-show empty lines before visible headlines."
5408 (save-excursion
5409 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5410 (org-cycle-show-empty-lines context))))
5412 (defun org-files-list ()
5413 "Return `org-agenda-files' list, plus all open org-mode files.
5414 This is useful for operations that need to scan all of a user's
5415 open and agenda-wise Org files."
5416 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5417 (dolist (buf (buffer-list))
5418 (with-current-buffer buf
5419 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5420 (let ((file (expand-file-name (buffer-file-name))))
5421 (unless (member file files)
5422 (push file files))))))
5423 files))
5425 (defsubst org-entry-beginning-position ()
5426 "Return the beginning position of the current entry."
5427 (save-excursion (outline-back-to-heading t) (point)))
5429 (defsubst org-entry-end-position ()
5430 "Return the end position of the current entry."
5431 (save-excursion (outline-next-heading) (point)))
5433 (defun org-cycle-hide-drawers (state)
5434 "Re-hide all drawers after a visibility state change."
5435 (when (and (org-mode-p)
5436 (not (memq state '(overview folded contents))))
5437 (save-excursion
5438 (let* ((globalp (memq state '(contents all)))
5439 (beg (if globalp (point-min) (point)))
5440 (end (if globalp (point-max)
5441 (if (eq state 'children)
5442 (save-excursion (outline-next-heading) (point))
5443 (org-end-of-subtree t)))))
5444 (goto-char beg)
5445 (while (re-search-forward org-drawer-regexp end t)
5446 (org-flag-drawer t))))))
5448 (defun org-flag-drawer (flag)
5449 (save-excursion
5450 (beginning-of-line 1)
5451 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5452 (let ((b (match-end 0))
5453 (outline-regexp org-outline-regexp))
5454 (if (re-search-forward
5455 "^[ \t]*:END:"
5456 (save-excursion (outline-next-heading) (point)) t)
5457 (outline-flag-region b (point-at-eol) flag)
5458 (error ":END: line missing at position %s" b))))))
5460 (defun org-subtree-end-visible-p ()
5461 "Is the end of the current subtree visible?"
5462 (pos-visible-in-window-p
5463 (save-excursion (org-end-of-subtree t) (point))))
5465 (defun org-first-headline-recenter (&optional N)
5466 "Move cursor to the first headline and recenter the headline.
5467 Optional argument N means, put the headline into the Nth line of the window."
5468 (goto-char (point-min))
5469 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5470 (beginning-of-line)
5471 (recenter (prefix-numeric-value N))))
5473 ;;; Folding of blocks
5475 (defconst org-block-regexp
5477 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5478 "Regular expression for hiding blocks.")
5480 (defvar org-hide-block-overlays nil
5481 "Overays hiding blocks.")
5482 (make-variable-buffer-local 'org-hide-block-overlays)
5484 (defun org-block-map (function &optional start end)
5485 "Call func at the head of all source blocks in the current
5486 buffer. Optional arguments START and END can be used to limit
5487 the range."
5488 (let ((start (or start (point-min)))
5489 (end (or end (point-max))))
5490 (save-excursion
5491 (goto-char start)
5492 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5493 (save-excursion
5494 (save-match-data
5495 (goto-char (match-beginning 0))
5496 (funcall function)))))))
5498 (defun org-hide-block-toggle-all ()
5499 "Toggle the visibility of all blocks in the current buffer."
5500 (org-block-map #'org-hide-block-toggle))
5502 (defun org-hide-block-all ()
5503 "Fold all blocks in the current buffer."
5504 (interactive)
5505 (org-show-block-all)
5506 (org-block-map #'org-hide-block-toggle-maybe))
5508 (defun org-show-block-all ()
5509 "Unfold all blocks in the current buffer."
5510 (mapc 'org-delete-overlay org-hide-block-overlays)
5511 (setq org-hide-block-overlays nil))
5513 (defun org-hide-block-toggle-maybe ()
5514 "Toggle visibility of block at point."
5515 (interactive)
5516 (let ((case-fold-search t))
5517 (if (save-excursion
5518 (beginning-of-line 1)
5519 (looking-at org-block-regexp))
5520 (progn (org-hide-block-toggle)
5521 t) ;; to signal that we took action
5522 nil))) ;; to signal that we did not
5524 (defun org-hide-block-toggle (&optional force)
5525 "Toggle the visibility of the current block."
5526 (interactive)
5527 (save-excursion
5528 (beginning-of-line)
5529 (if (re-search-forward org-block-regexp nil t)
5530 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5531 (end (match-end 0)) ;; end of entire body
5533 (if (memq t (mapcar (lambda (overlay)
5534 (eq (org-overlay-get overlay 'invisible)
5535 'org-hide-block))
5536 (org-overlays-at start)))
5537 (if (or (not force) (eq force 'off))
5538 (mapc (lambda (ov)
5539 (when (member ov org-hide-block-overlays)
5540 (setq org-hide-block-overlays
5541 (delq ov org-hide-block-overlays)))
5542 (when (eq (org-overlay-get ov 'invisible)
5543 'org-hide-block)
5544 (org-delete-overlay ov)))
5545 (org-overlays-at start)))
5546 (setq ov (org-make-overlay start end))
5547 (org-overlay-put ov 'invisible 'org-hide-block)
5548 ;; make the block accessible to isearch
5549 (org-overlay-put
5550 ov 'isearch-open-invisible
5551 (lambda (ov)
5552 (when (member ov org-hide-block-overlays)
5553 (setq org-hide-block-overlays
5554 (delq ov org-hide-block-overlays)))
5555 (when (eq (org-overlay-get ov 'invisible)
5556 'org-hide-block)
5557 (org-delete-overlay ov))))
5558 (push ov org-hide-block-overlays)))
5559 (error "Not looking at a source block"))))
5561 ;; org-tab-after-check-for-cycling-hook
5562 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5563 ;; Remove overlays when changing major mode
5564 (add-hook 'org-mode-hook
5565 (lambda () (org-add-hook 'change-major-mode-hook
5566 'org-show-block-all 'append 'local)))
5568 ;;; Org-goto
5570 (defvar org-goto-window-configuration nil)
5571 (defvar org-goto-marker nil)
5572 (defvar org-goto-map
5573 (let ((map (make-sparse-keymap)))
5574 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5575 (while (setq cmd (pop cmds))
5576 (substitute-key-definition cmd cmd map global-map)))
5577 (suppress-keymap map)
5578 (org-defkey map "\C-m" 'org-goto-ret)
5579 (org-defkey map [(return)] 'org-goto-ret)
5580 (org-defkey map [(left)] 'org-goto-left)
5581 (org-defkey map [(right)] 'org-goto-right)
5582 (org-defkey map [(control ?g)] 'org-goto-quit)
5583 (org-defkey map "\C-i" 'org-cycle)
5584 (org-defkey map [(tab)] 'org-cycle)
5585 (org-defkey map [(down)] 'outline-next-visible-heading)
5586 (org-defkey map [(up)] 'outline-previous-visible-heading)
5587 (if org-goto-auto-isearch
5588 (if (fboundp 'define-key-after)
5589 (define-key-after map [t] 'org-goto-local-auto-isearch)
5590 nil)
5591 (org-defkey map "q" 'org-goto-quit)
5592 (org-defkey map "n" 'outline-next-visible-heading)
5593 (org-defkey map "p" 'outline-previous-visible-heading)
5594 (org-defkey map "f" 'outline-forward-same-level)
5595 (org-defkey map "b" 'outline-backward-same-level)
5596 (org-defkey map "u" 'outline-up-heading))
5597 (org-defkey map "/" 'org-occur)
5598 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5599 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5600 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5601 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5602 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5603 map))
5605 (defconst org-goto-help
5606 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5607 RET=jump to location [Q]uit and return to previous location
5608 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5610 (defvar org-goto-start-pos) ; dynamically scoped parameter
5612 ;; FIXME: Docstring doe not mention both interfaces
5613 (defun org-goto (&optional alternative-interface)
5614 "Look up a different location in the current file, keeping current visibility.
5616 When you want look-up or go to a different location in a document, the
5617 fastest way is often to fold the entire buffer and then dive into the tree.
5618 This method has the disadvantage, that the previous location will be folded,
5619 which may not be what you want.
5621 This command works around this by showing a copy of the current buffer
5622 in an indirect buffer, in overview mode. You can dive into the tree in
5623 that copy, use org-occur and incremental search to find a location.
5624 When pressing RET or `Q', the command returns to the original buffer in
5625 which the visibility is still unchanged. After RET is will also jump to
5626 the location selected in the indirect buffer and expose the
5627 the headline hierarchy above."
5628 (interactive "P")
5629 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5630 (org-refile-use-outline-path t)
5631 (org-refile-target-verify-function nil)
5632 (interface
5633 (if (not alternative-interface)
5634 org-goto-interface
5635 (if (eq org-goto-interface 'outline)
5636 'outline-path-completion
5637 'outline)))
5638 (org-goto-start-pos (point))
5639 (selected-point
5640 (if (eq interface 'outline)
5641 (car (org-get-location (current-buffer) org-goto-help))
5642 (nth 3 (org-refile-get-location "Goto: ")))))
5643 (if selected-point
5644 (progn
5645 (org-mark-ring-push org-goto-start-pos)
5646 (goto-char selected-point)
5647 (if (or (org-invisible-p) (org-invisible-p2))
5648 (org-show-context 'org-goto)))
5649 (message "Quit"))))
5651 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5652 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5653 (defvar org-goto-local-auto-isearch-map) ; defined below
5655 (defun org-get-location (buf help)
5656 "Let the user select a location in the Org-mode buffer BUF.
5657 This function uses a recursive edit. It returns the selected position
5658 or nil."
5659 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5660 (isearch-hide-immediately nil)
5661 (isearch-search-fun-function
5662 (lambda () 'org-goto-local-search-headings))
5663 (org-goto-selected-point org-goto-exit-command))
5664 (save-excursion
5665 (save-window-excursion
5666 (delete-other-windows)
5667 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5668 (switch-to-buffer
5669 (condition-case nil
5670 (make-indirect-buffer (current-buffer) "*org-goto*")
5671 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5672 (with-output-to-temp-buffer "*Help*"
5673 (princ help))
5674 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5675 (setq buffer-read-only nil)
5676 (let ((org-startup-truncated t)
5677 (org-startup-folded nil)
5678 (org-startup-align-all-tables nil))
5679 (org-mode)
5680 (org-overview))
5681 (setq buffer-read-only t)
5682 (if (and (boundp 'org-goto-start-pos)
5683 (integer-or-marker-p org-goto-start-pos))
5684 (let ((org-show-hierarchy-above t)
5685 (org-show-siblings t)
5686 (org-show-following-heading t))
5687 (goto-char org-goto-start-pos)
5688 (and (org-invisible-p) (org-show-context)))
5689 (goto-char (point-min)))
5690 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5691 (message "Select location and press RET")
5692 (use-local-map org-goto-map)
5693 (recursive-edit)
5695 (kill-buffer "*org-goto*")
5696 (cons org-goto-selected-point org-goto-exit-command)))
5698 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5699 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5700 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5701 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5703 (defun org-goto-local-search-headings (string bound noerror)
5704 "Search and make sure that any matches are in headlines."
5705 (catch 'return
5706 (while (if isearch-forward
5707 (search-forward string bound noerror)
5708 (search-backward string bound noerror))
5709 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5710 (and (member :headline context)
5711 (not (member :tags context))))
5712 (throw 'return (point))))))
5714 (defun org-goto-local-auto-isearch ()
5715 "Start isearch."
5716 (interactive)
5717 (goto-char (point-min))
5718 (let ((keys (this-command-keys)))
5719 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5720 (isearch-mode t)
5721 (isearch-process-search-char (string-to-char keys)))))
5723 (defun org-goto-ret (&optional arg)
5724 "Finish `org-goto' by going to the new location."
5725 (interactive "P")
5726 (setq org-goto-selected-point (point)
5727 org-goto-exit-command 'return)
5728 (throw 'exit nil))
5730 (defun org-goto-left ()
5731 "Finish `org-goto' by going to the new location."
5732 (interactive)
5733 (if (org-on-heading-p)
5734 (progn
5735 (beginning-of-line 1)
5736 (setq org-goto-selected-point (point)
5737 org-goto-exit-command 'left)
5738 (throw 'exit nil))
5739 (error "Not on a heading")))
5741 (defun org-goto-right ()
5742 "Finish `org-goto' by going to the new location."
5743 (interactive)
5744 (if (org-on-heading-p)
5745 (progn
5746 (setq org-goto-selected-point (point)
5747 org-goto-exit-command 'right)
5748 (throw 'exit nil))
5749 (error "Not on a heading")))
5751 (defun org-goto-quit ()
5752 "Finish `org-goto' without cursor motion."
5753 (interactive)
5754 (setq org-goto-selected-point nil)
5755 (setq org-goto-exit-command 'quit)
5756 (throw 'exit nil))
5758 ;;; Indirect buffer display of subtrees
5760 (defvar org-indirect-dedicated-frame nil
5761 "This is the frame being used for indirect tree display.")
5762 (defvar org-last-indirect-buffer nil)
5764 (defun org-tree-to-indirect-buffer (&optional arg)
5765 "Create indirect buffer and narrow it to current subtree.
5766 With numerical prefix ARG, go up to this level and then take that tree.
5767 If ARG is negative, go up that many levels.
5768 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5769 indirect buffer previously made with this command, to avoid proliferation of
5770 indirect buffers. However, when you call the command with a `C-u' prefix, or
5771 when `org-indirect-buffer-display' is `new-frame', the last buffer
5772 is kept so that you can work with several indirect buffers at the same time.
5773 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5774 requests that a new frame be made for the new buffer, so that the dedicated
5775 frame is not changed."
5776 (interactive "P")
5777 (let ((cbuf (current-buffer))
5778 (cwin (selected-window))
5779 (pos (point))
5780 beg end level heading ibuf)
5781 (save-excursion
5782 (org-back-to-heading t)
5783 (when (numberp arg)
5784 (setq level (org-outline-level))
5785 (if (< arg 0) (setq arg (+ level arg)))
5786 (while (> (setq level (org-outline-level)) arg)
5787 (outline-up-heading 1 t)))
5788 (setq beg (point)
5789 heading (org-get-heading))
5790 (org-end-of-subtree t t) (setq end (point)))
5791 (if (and (buffer-live-p org-last-indirect-buffer)
5792 (not (eq org-indirect-buffer-display 'new-frame))
5793 (not arg))
5794 (kill-buffer org-last-indirect-buffer))
5795 (setq ibuf (org-get-indirect-buffer cbuf)
5796 org-last-indirect-buffer ibuf)
5797 (cond
5798 ((or (eq org-indirect-buffer-display 'new-frame)
5799 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5800 (select-frame (make-frame))
5801 (delete-other-windows)
5802 (switch-to-buffer ibuf)
5803 (org-set-frame-title heading))
5804 ((eq org-indirect-buffer-display 'dedicated-frame)
5805 (raise-frame
5806 (select-frame (or (and org-indirect-dedicated-frame
5807 (frame-live-p org-indirect-dedicated-frame)
5808 org-indirect-dedicated-frame)
5809 (setq org-indirect-dedicated-frame (make-frame)))))
5810 (delete-other-windows)
5811 (switch-to-buffer ibuf)
5812 (org-set-frame-title (concat "Indirect: " heading)))
5813 ((eq org-indirect-buffer-display 'current-window)
5814 (switch-to-buffer ibuf))
5815 ((eq org-indirect-buffer-display 'other-window)
5816 (pop-to-buffer ibuf))
5817 (t (error "Invalid value")))
5818 (if (featurep 'xemacs)
5819 (save-excursion (org-mode) (turn-on-font-lock)))
5820 (narrow-to-region beg end)
5821 (show-all)
5822 (goto-char pos)
5823 (and (window-live-p cwin) (select-window cwin))))
5825 (defun org-get-indirect-buffer (&optional buffer)
5826 (setq buffer (or buffer (current-buffer)))
5827 (let ((n 1) (base (buffer-name buffer)) bname)
5828 (while (buffer-live-p
5829 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5830 (setq n (1+ n)))
5831 (condition-case nil
5832 (make-indirect-buffer buffer bname 'clone)
5833 (error (make-indirect-buffer buffer bname)))))
5835 (defun org-set-frame-title (title)
5836 "Set the title of the current frame to the string TITLE."
5837 ;; FIXME: how to name a single frame in XEmacs???
5838 (unless (featurep 'xemacs)
5839 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5841 ;;;; Structure editing
5843 ;;; Inserting headlines
5845 (defun org-previous-line-empty-p ()
5846 (save-excursion
5847 (and (not (bobp))
5848 (or (beginning-of-line 0) t)
5849 (save-match-data
5850 (looking-at "[ \t]*$")))))
5852 (defun org-insert-heading (&optional force-heading)
5853 "Insert a new heading or item with same depth at point.
5854 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5855 If point is at the beginning of a headline, insert a sibling before the
5856 current headline. If point is not at the beginning, do not split the line,
5857 but create the new headline after the current line."
5858 (interactive "P")
5859 (if (= (buffer-size) 0)
5860 (insert "\n* ")
5861 (when (or force-heading (not (org-insert-item)))
5862 (let* ((empty-line-p nil)
5863 (head (save-excursion
5864 (condition-case nil
5865 (progn
5866 (org-back-to-heading)
5867 (setq empty-line-p (org-previous-line-empty-p))
5868 (match-string 0))
5869 (error "*"))))
5870 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5871 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5872 pos hide-previous previous-pos)
5873 (cond
5874 ((and (org-on-heading-p) (bolp)
5875 (or (bobp)
5876 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5877 ;; insert before the current line
5878 (open-line (if blank 2 1)))
5879 ((and (bolp)
5880 (not org-insert-heading-respect-content)
5881 (or (bobp)
5882 (save-excursion
5883 (backward-char 1) (not (org-invisible-p)))))
5884 ;; insert right here
5885 nil)
5887 ;; somewhere in the line
5888 (save-excursion
5889 (setq previous-pos (point-at-bol))
5890 (end-of-line)
5891 (setq hide-previous (org-invisible-p)))
5892 (and org-insert-heading-respect-content (org-show-subtree))
5893 (let ((split
5894 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5895 (save-excursion
5896 (let ((p (point)))
5897 (goto-char (point-at-bol))
5898 (and (looking-at org-complex-heading-regexp)
5899 (> p (match-beginning 4)))))))
5900 tags pos)
5901 (cond
5902 (org-insert-heading-respect-content
5903 (org-end-of-subtree nil t)
5904 (or (bolp) (newline))
5905 (or (org-previous-line-empty-p)
5906 (and blank (newline)))
5907 (open-line 1))
5908 ((org-on-heading-p)
5909 (when hide-previous
5910 (show-children)
5911 (org-show-entry))
5912 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5913 (setq tags (and (match-end 2) (match-string 2)))
5914 (and (match-end 1)
5915 (delete-region (match-beginning 1) (match-end 1)))
5916 (setq pos (point-at-bol))
5917 (or split (end-of-line 1))
5918 (delete-horizontal-space)
5919 (newline (if blank 2 1))
5920 (when tags
5921 (save-excursion
5922 (goto-char pos)
5923 (end-of-line 1)
5924 (insert " " tags)
5925 (org-set-tags nil 'align))))
5927 (or split (end-of-line 1))
5928 (newline (if blank 2 1)))))))
5929 (insert head) (just-one-space)
5930 (setq pos (point))
5931 (end-of-line 1)
5932 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5933 (when (and org-insert-heading-respect-content hide-previous)
5934 (save-excursion
5935 (goto-char previous-pos)
5936 (hide-subtree)))
5937 (run-hooks 'org-insert-heading-hook)))))
5939 (defun org-get-heading (&optional no-tags)
5940 "Return the heading of the current entry, without the stars."
5941 (save-excursion
5942 (org-back-to-heading t)
5943 (if (looking-at
5944 (if no-tags
5945 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5946 "\\*+[ \t]+\\([^\r\n]*\\)"))
5947 (match-string 1) "")))
5949 (defun org-heading-components ()
5950 "Return the components of the current heading.
5951 This is a list with the following elements:
5952 - the level as an integer
5953 - the reduced level, different if `org-odd-levels-only' is set.
5954 - the TODO keyword, or nil
5955 - the priority character, like ?A, or nil if no priority is given
5956 - the headline text itself, or the tags string if no headline text
5957 - the tags string, or nil."
5958 (save-excursion
5959 (org-back-to-heading t)
5960 (if (looking-at org-complex-heading-regexp)
5961 (list (length (match-string 1))
5962 (org-reduced-level (length (match-string 1)))
5963 (org-match-string-no-properties 2)
5964 (and (match-end 3) (aref (match-string 3) 2))
5965 (org-match-string-no-properties 4)
5966 (org-match-string-no-properties 5)))))
5968 (defun org-get-entry ()
5969 "Get the entry text, after heading, entire subtree."
5970 (save-excursion
5971 (org-back-to-heading t)
5972 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5974 (defun org-insert-heading-after-current ()
5975 "Insert a new heading with same level as current, after current subtree."
5976 (interactive)
5977 (org-back-to-heading)
5978 (org-insert-heading)
5979 (org-move-subtree-down)
5980 (end-of-line 1))
5982 (defun org-insert-heading-respect-content ()
5983 (interactive)
5984 (let ((org-insert-heading-respect-content t))
5985 (org-insert-heading t)))
5987 (defun org-insert-todo-heading-respect-content (&optional force-state)
5988 (interactive "P")
5989 (let ((org-insert-heading-respect-content t))
5990 (org-insert-todo-heading force-state t)))
5992 (defun org-insert-todo-heading (arg &optional force-heading)
5993 "Insert a new heading with the same level and TODO state as current heading.
5994 If the heading has no TODO state, or if the state is DONE, use the first
5995 state (TODO by default). Also with prefix arg, force first state."
5996 (interactive "P")
5997 (when (or force-heading (not (org-insert-item 'checkbox)))
5998 (org-insert-heading force-heading)
5999 (save-excursion
6000 (org-back-to-heading)
6001 (outline-previous-heading)
6002 (looking-at org-todo-line-regexp))
6003 (let*
6004 ((new-mark-x
6005 (if (or arg
6006 (not (match-beginning 2))
6007 (member (match-string 2) org-done-keywords))
6008 (car org-todo-keywords-1)
6009 (match-string 2)))
6010 (new-mark
6012 (run-hook-with-args-until-success
6013 'org-todo-get-default-hook new-mark-x nil)
6014 new-mark-x)))
6015 (beginning-of-line 1)
6016 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6017 (if org-treat-insert-todo-heading-as-state-change
6018 (org-todo new-mark)
6019 (insert new-mark " "))))
6020 (when org-provide-todo-statistics
6021 (org-update-parent-todo-statistics))))
6023 (defun org-insert-subheading (arg)
6024 "Insert a new subheading and demote it.
6025 Works for outline headings and for plain lists alike."
6026 (interactive "P")
6027 (org-insert-heading arg)
6028 (cond
6029 ((org-on-heading-p) (org-do-demote))
6030 ((org-at-item-p) (org-indent-item 1))))
6032 (defun org-insert-todo-subheading (arg)
6033 "Insert a new subheading with TODO keyword or checkbox and demote it.
6034 Works for outline headings and for plain lists alike."
6035 (interactive "P")
6036 (org-insert-todo-heading arg)
6037 (cond
6038 ((org-on-heading-p) (org-do-demote))
6039 ((org-at-item-p) (org-indent-item 1))))
6041 ;;; Promotion and Demotion
6043 (defvar org-after-demote-entry-hook nil
6044 "Hook run after an entry has been demoted.
6045 The cursor will be at the beginning of the entry.
6046 When a subtree is being demoted, the hook will be called for each node.")
6048 (defvar org-after-promote-entry-hook nil
6049 "Hook run after an entry has been promoted.
6050 The cursor will be at the beginning of the entry.
6051 When a subtree is being promoted, the hook will be called for each node.")
6053 (defun org-promote-subtree ()
6054 "Promote the entire subtree.
6055 See also `org-promote'."
6056 (interactive)
6057 (save-excursion
6058 (org-map-tree 'org-promote))
6059 (org-fix-position-after-promote))
6061 (defun org-demote-subtree ()
6062 "Demote the entire subtree. See `org-demote'.
6063 See also `org-promote'."
6064 (interactive)
6065 (save-excursion
6066 (org-map-tree 'org-demote))
6067 (org-fix-position-after-promote))
6070 (defun org-do-promote ()
6071 "Promote the current heading higher up the tree.
6072 If the region is active in `transient-mark-mode', promote all headings
6073 in the region."
6074 (interactive)
6075 (save-excursion
6076 (if (org-region-active-p)
6077 (org-map-region 'org-promote (region-beginning) (region-end))
6078 (org-promote)))
6079 (org-fix-position-after-promote))
6081 (defun org-do-demote ()
6082 "Demote the current heading lower down the tree.
6083 If the region is active in `transient-mark-mode', demote all headings
6084 in the region."
6085 (interactive)
6086 (save-excursion
6087 (if (org-region-active-p)
6088 (org-map-region 'org-demote (region-beginning) (region-end))
6089 (org-demote)))
6090 (org-fix-position-after-promote))
6092 (defun org-fix-position-after-promote ()
6093 "Make sure that after pro/demotion cursor position is right."
6094 (let ((pos (point)))
6095 (when (save-excursion
6096 (beginning-of-line 1)
6097 (looking-at org-todo-line-regexp)
6098 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6099 (cond ((eobp) (insert " "))
6100 ((eolp) (insert " "))
6101 ((equal (char-after) ?\ ) (forward-char 1))))))
6103 (defun org-current-level ()
6104 "Return the level of the current entry, or nil if before the first headline.
6105 The level is the number of stars at the beginning of the headline."
6106 (save-excursion
6107 (condition-case nil
6108 (progn
6109 (org-back-to-heading t)
6110 (funcall outline-level))
6111 (error nil))))
6113 (defun org-reduced-level (l)
6114 "Compute the effective level of a heading.
6115 This takes into account the setting of `org-odd-levels-only'."
6116 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6118 (defun org-get-valid-level (level &optional change)
6119 "Rectify a level change under the influence of `org-odd-levels-only'
6120 LEVEL is a current level, CHANGE is by how much the level should be
6121 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6122 even level numbers will become the next higher odd number."
6123 (if org-odd-levels-only
6124 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6125 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6126 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6127 (max 1 (+ level (or change 0)))))
6129 (if (boundp 'define-obsolete-function-alias)
6130 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6131 (define-obsolete-function-alias 'org-get-legal-level
6132 'org-get-valid-level)
6133 (define-obsolete-function-alias 'org-get-legal-level
6134 'org-get-valid-level "23.1")))
6136 (defun org-promote ()
6137 "Promote the current heading higher up the tree.
6138 If the region is active in `transient-mark-mode', promote all headings
6139 in the region."
6140 (org-back-to-heading t)
6141 (let* ((level (save-match-data (funcall outline-level)))
6142 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6143 (diff (abs (- level (length up-head) -1))))
6144 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6145 (replace-match up-head nil t)
6146 ;; Fixup tag positioning
6147 (and org-auto-align-tags (org-set-tags nil t))
6148 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6149 (run-hooks 'org-after-promote-entry-hook)))
6151 (defun org-demote ()
6152 "Demote the current heading lower down the tree.
6153 If the region is active in `transient-mark-mode', demote all headings
6154 in the region."
6155 (org-back-to-heading t)
6156 (let* ((level (save-match-data (funcall outline-level)))
6157 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6158 (diff (abs (- level (length down-head) -1))))
6159 (replace-match down-head nil t)
6160 ;; Fixup tag positioning
6161 (and org-auto-align-tags (org-set-tags nil t))
6162 (if org-adapt-indentation (org-fixup-indentation diff))
6163 (run-hooks 'org-after-demote-entry-hook)))
6165 (defvar org-tab-ind-state nil)
6167 (defun org-cycle-level ()
6168 (let ((org-adapt-indentation nil))
6169 (when (and (looking-at "[ \t]*$")
6170 (looking-back
6171 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6172 (setq this-command 'org-cycle-level)
6173 (if (eq last-command 'org-cycle-level)
6174 (condition-case nil
6175 (progn (org-do-promote)
6176 (if (equal org-tab-ind-state (org-current-level))
6177 (org-do-promote)))
6178 (error
6179 (progn
6180 (save-excursion
6181 (beginning-of-line 1)
6182 (and (looking-at "\\*+")
6183 (replace-match
6184 (make-string org-tab-ind-state ?*))))
6185 (setq this-command 'org-cycle))))
6186 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6187 (org-do-demote))
6188 t)))
6190 (defun org-map-tree (fun)
6191 "Call FUN for every heading underneath the current one."
6192 (org-back-to-heading)
6193 (let ((level (funcall outline-level)))
6194 (save-excursion
6195 (funcall fun)
6196 (while (and (progn
6197 (outline-next-heading)
6198 (> (funcall outline-level) level))
6199 (not (eobp)))
6200 (funcall fun)))))
6202 (defun org-map-region (fun beg end)
6203 "Call FUN for every heading between BEG and END."
6204 (let ((org-ignore-region t))
6205 (save-excursion
6206 (setq end (copy-marker end))
6207 (goto-char beg)
6208 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6209 (< (point) end))
6210 (funcall fun))
6211 (while (and (progn
6212 (outline-next-heading)
6213 (< (point) end))
6214 (not (eobp)))
6215 (funcall fun)))))
6217 (defun org-fixup-indentation (diff)
6218 "Change the indentation in the current entry by DIFF
6219 However, if any line in the current entry has no indentation, or if it
6220 would end up with no indentation after the change, nothing at all is done."
6221 (save-excursion
6222 (let ((end (save-excursion (outline-next-heading)
6223 (point-marker)))
6224 (prohibit (if (> diff 0)
6225 "^\\S-"
6226 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6227 col)
6228 (unless (save-excursion (end-of-line 1)
6229 (re-search-forward prohibit end t))
6230 (while (and (< (point) end)
6231 (re-search-forward "^[ \t]+" end t))
6232 (goto-char (match-end 0))
6233 (setq col (current-column))
6234 (if (< diff 0) (replace-match ""))
6235 (org-indent-to-column (+ diff col))))
6236 (move-marker end nil))))
6238 (defun org-convert-to-odd-levels ()
6239 "Convert an org-mode file with all levels allowed to one with odd levels.
6240 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6241 level 5 etc."
6242 (interactive)
6243 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6244 (let ((outline-regexp org-outline-regexp)
6245 (outline-level 'org-outline-level)
6246 (org-odd-levels-only nil) n)
6247 (save-excursion
6248 (goto-char (point-min))
6249 (while (re-search-forward "^\\*\\*+ " nil t)
6250 (setq n (- (length (match-string 0)) 2))
6251 (while (>= (setq n (1- n)) 0)
6252 (org-demote))
6253 (end-of-line 1))))))
6255 (defun org-convert-to-oddeven-levels ()
6256 "Convert an org-mode file with only odd levels to one with odd and even levels.
6257 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6258 section with an even level, conversion would destroy the structure of the file. An error
6259 is signaled in this case."
6260 (interactive)
6261 (goto-char (point-min))
6262 ;; First check if there are no even levels
6263 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6264 (org-show-context t)
6265 (error "Not all levels are odd in this file. Conversion not possible"))
6266 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6267 (let ((outline-regexp org-outline-regexp)
6268 (outline-level 'org-outline-level)
6269 (org-odd-levels-only nil) n)
6270 (save-excursion
6271 (goto-char (point-min))
6272 (while (re-search-forward "^\\*\\*+ " nil t)
6273 (setq n (/ (1- (length (match-string 0))) 2))
6274 (while (>= (setq n (1- n)) 0)
6275 (org-promote))
6276 (end-of-line 1))))))
6278 (defun org-tr-level (n)
6279 "Make N odd if required."
6280 (if org-odd-levels-only (1+ (/ n 2)) n))
6282 ;;; Vertical tree motion, cutting and pasting of subtrees
6284 (defun org-move-subtree-up (&optional arg)
6285 "Move the current subtree up past ARG headlines of the same level."
6286 (interactive "p")
6287 (org-move-subtree-down (- (prefix-numeric-value arg))))
6289 (defun org-move-subtree-down (&optional arg)
6290 "Move the current subtree down past ARG headlines of the same level."
6291 (interactive "p")
6292 (setq arg (prefix-numeric-value arg))
6293 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6294 'org-get-last-sibling))
6295 (ins-point (make-marker))
6296 (cnt (abs arg))
6297 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6298 ;; Select the tree
6299 (org-back-to-heading)
6300 (setq beg0 (point))
6301 (save-excursion
6302 (setq ne-beg (org-back-over-empty-lines))
6303 (setq beg (point)))
6304 (save-match-data
6305 (save-excursion (outline-end-of-heading)
6306 (setq folded (org-invisible-p)))
6307 (outline-end-of-subtree))
6308 (outline-next-heading)
6309 (setq ne-end (org-back-over-empty-lines))
6310 (setq end (point))
6311 (goto-char beg0)
6312 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6313 ;; include less whitespace
6314 (save-excursion
6315 (goto-char beg)
6316 (forward-line (- ne-beg ne-end))
6317 (setq beg (point))))
6318 ;; Find insertion point, with error handling
6319 (while (> cnt 0)
6320 (or (and (funcall movfunc) (looking-at outline-regexp))
6321 (progn (goto-char beg0)
6322 (error "Cannot move past superior level or buffer limit")))
6323 (setq cnt (1- cnt)))
6324 (if (> arg 0)
6325 ;; Moving forward - still need to move over subtree
6326 (progn (org-end-of-subtree t t)
6327 (save-excursion
6328 (org-back-over-empty-lines)
6329 (or (bolp) (newline)))))
6330 (setq ne-ins (org-back-over-empty-lines))
6331 (move-marker ins-point (point))
6332 (setq txt (buffer-substring beg end))
6333 (org-save-markers-in-region beg end)
6334 (delete-region beg end)
6335 (org-remove-empty-overlays-at beg)
6336 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6337 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6338 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6339 (let ((bbb (point)))
6340 (insert-before-markers txt)
6341 (org-reinstall-markers-in-region bbb)
6342 (move-marker ins-point bbb))
6343 (or (bolp) (insert "\n"))
6344 (setq ins-end (point))
6345 (goto-char ins-point)
6346 (org-skip-whitespace)
6347 (when (and (< arg 0)
6348 (org-first-sibling-p)
6349 (> ne-ins ne-beg))
6350 ;; Move whitespace back to beginning
6351 (save-excursion
6352 (goto-char ins-end)
6353 (let ((kill-whole-line t))
6354 (kill-line (- ne-ins ne-beg)) (point)))
6355 (insert (make-string (- ne-ins ne-beg) ?\n)))
6356 (move-marker ins-point nil)
6357 (if folded
6358 (hide-subtree)
6359 (org-show-entry)
6360 (show-children)
6361 (org-cycle-hide-drawers 'children))
6362 (org-clean-visibility-after-subtree-move)))
6364 (defvar org-subtree-clip ""
6365 "Clipboard for cut and paste of subtrees.
6366 This is actually only a copy of the kill, because we use the normal kill
6367 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6369 (defvar org-subtree-clip-folded nil
6370 "Was the last copied subtree folded?
6371 This is used to fold the tree back after pasting.")
6373 (defun org-cut-subtree (&optional n)
6374 "Cut the current subtree into the clipboard.
6375 With prefix arg N, cut this many sequential subtrees.
6376 This is a short-hand for marking the subtree and then cutting it."
6377 (interactive "p")
6378 (org-copy-subtree n 'cut))
6380 (defun org-copy-subtree (&optional n cut force-store-markers)
6381 "Cut the current subtree into the clipboard.
6382 With prefix arg N, cut this many sequential subtrees.
6383 This is a short-hand for marking the subtree and then copying it.
6384 If CUT is non-nil, actually cut the subtree.
6385 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6386 of some markers in the region, even if CUT is non-nil. This is
6387 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6388 (interactive "p")
6389 (let (beg end folded (beg0 (point)))
6390 (if (interactive-p)
6391 (org-back-to-heading nil) ; take what looks like a subtree
6392 (org-back-to-heading t)) ; take what is really there
6393 (org-back-over-empty-lines)
6394 (setq beg (point))
6395 (skip-chars-forward " \t\r\n")
6396 (save-match-data
6397 (save-excursion (outline-end-of-heading)
6398 (setq folded (org-invisible-p)))
6399 (condition-case nil
6400 (org-forward-same-level (1- n) t)
6401 (error nil))
6402 (org-end-of-subtree t t))
6403 (org-back-over-empty-lines)
6404 (setq end (point))
6405 (goto-char beg0)
6406 (when (> end beg)
6407 (setq org-subtree-clip-folded folded)
6408 (when (or cut force-store-markers)
6409 (org-save-markers-in-region beg end))
6410 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6411 (setq org-subtree-clip (current-kill 0))
6412 (message "%s: Subtree(s) with %d characters"
6413 (if cut "Cut" "Copied")
6414 (length org-subtree-clip)))))
6416 (defun org-paste-subtree (&optional level tree for-yank)
6417 "Paste the clipboard as a subtree, with modification of headline level.
6418 The entire subtree is promoted or demoted in order to match a new headline
6419 level.
6421 If the cursor is at the beginning of a headline, the same level as
6422 that headline is used to paste the tree
6424 If not, the new level is derived from the *visible* headings
6425 before and after the insertion point, and taken to be the inferior headline
6426 level of the two. So if the previous visible heading is level 3 and the
6427 next is level 4 (or vice versa), level 4 will be used for insertion.
6428 This makes sure that the subtree remains an independent subtree and does
6429 not swallow low level entries.
6431 You can also force a different level, either by using a numeric prefix
6432 argument, or by inserting the heading marker by hand. For example, if the
6433 cursor is after \"*****\", then the tree will be shifted to level 5.
6435 If optional TREE is given, use this text instead of the kill ring.
6437 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6438 move back over whitespace before inserting, and move point to the end of
6439 the inserted text when done."
6440 (interactive "P")
6441 (setq tree (or tree (and kill-ring (current-kill 0))))
6442 (unless (org-kill-is-subtree-p tree)
6443 (error "%s"
6444 (substitute-command-keys
6445 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6446 (let* ((visp (not (org-invisible-p)))
6447 (txt tree)
6448 (^re (concat "^\\(" outline-regexp "\\)"))
6449 (re (concat "\\(" outline-regexp "\\)"))
6450 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6452 (old-level (if (string-match ^re txt)
6453 (- (match-end 0) (match-beginning 0) 1)
6454 -1))
6455 (force-level (cond (level (prefix-numeric-value level))
6456 ((and (looking-at "[ \t]*$")
6457 (string-match
6458 ^re_ (buffer-substring
6459 (point-at-bol) (point))))
6460 (- (match-end 1) (match-beginning 1)))
6461 ((and (bolp)
6462 (looking-at org-outline-regexp))
6463 (- (match-end 0) (point) 1))
6464 (t nil)))
6465 (previous-level (save-excursion
6466 (condition-case nil
6467 (progn
6468 (outline-previous-visible-heading 1)
6469 (if (looking-at re)
6470 (- (match-end 0) (match-beginning 0) 1)
6472 (error 1))))
6473 (next-level (save-excursion
6474 (condition-case nil
6475 (progn
6476 (or (looking-at outline-regexp)
6477 (outline-next-visible-heading 1))
6478 (if (looking-at re)
6479 (- (match-end 0) (match-beginning 0) 1)
6481 (error 1))))
6482 (new-level (or force-level (max previous-level next-level)))
6483 (shift (if (or (= old-level -1)
6484 (= new-level -1)
6485 (= old-level new-level))
6487 (- new-level old-level)))
6488 (delta (if (> shift 0) -1 1))
6489 (func (if (> shift 0) 'org-demote 'org-promote))
6490 (org-odd-levels-only nil)
6491 beg end newend)
6492 ;; Remove the forced level indicator
6493 (if force-level
6494 (delete-region (point-at-bol) (point)))
6495 ;; Paste
6496 (beginning-of-line 1)
6497 (unless for-yank (org-back-over-empty-lines))
6498 (setq beg (point))
6499 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6500 (insert-before-markers txt)
6501 (unless (string-match "\n\\'" txt) (insert "\n"))
6502 (setq newend (point))
6503 (org-reinstall-markers-in-region beg)
6504 (setq end (point))
6505 (goto-char beg)
6506 (skip-chars-forward " \t\n\r")
6507 (setq beg (point))
6508 (if (and (org-invisible-p) visp)
6509 (save-excursion (outline-show-heading)))
6510 ;; Shift if necessary
6511 (unless (= shift 0)
6512 (save-restriction
6513 (narrow-to-region beg end)
6514 (while (not (= shift 0))
6515 (org-map-region func (point-min) (point-max))
6516 (setq shift (+ delta shift)))
6517 (goto-char (point-min))
6518 (setq newend (point-max))))
6519 (when (or (interactive-p) for-yank)
6520 (message "Clipboard pasted as level %d subtree" new-level))
6521 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6522 kill-ring
6523 (eq org-subtree-clip (current-kill 0))
6524 org-subtree-clip-folded)
6525 ;; The tree was folded before it was killed/copied
6526 (hide-subtree))
6527 (and for-yank (goto-char newend))))
6529 (defun org-kill-is-subtree-p (&optional txt)
6530 "Check if the current kill is an outline subtree, or a set of trees.
6531 Returns nil if kill does not start with a headline, or if the first
6532 headline level is not the largest headline level in the tree.
6533 So this will actually accept several entries of equal levels as well,
6534 which is OK for `org-paste-subtree'.
6535 If optional TXT is given, check this string instead of the current kill."
6536 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6537 (start-level (and kill
6538 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6539 org-outline-regexp "\\)")
6540 kill)
6541 (- (match-end 2) (match-beginning 2) 1)))
6542 (re (concat "^" org-outline-regexp))
6543 (start (1+ (or (match-beginning 2) -1))))
6544 (if (not start-level)
6545 (progn
6546 nil) ;; does not even start with a heading
6547 (catch 'exit
6548 (while (setq start (string-match re kill (1+ start)))
6549 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6550 (throw 'exit nil)))
6551 t))))
6553 (defvar org-markers-to-move nil
6554 "Markers that should be moved with a cut-and-paste operation.
6555 Those markers are stored together with their positions relative to
6556 the start of the region.")
6558 (defun org-save-markers-in-region (beg end)
6559 "Check markers in region.
6560 If these markers are between BEG and END, record their position relative
6561 to BEG, so that after moving the block of text, we can put the markers back
6562 into place.
6563 This function gets called just before an entry or tree gets cut from the
6564 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6565 called immediately, to move the markers with the entries."
6566 (setq org-markers-to-move nil)
6567 (when (featurep 'org-clock)
6568 (org-clock-save-markers-for-cut-and-paste beg end))
6569 (when (featurep 'org-agenda)
6570 (org-agenda-save-markers-for-cut-and-paste beg end)))
6572 (defun org-check-and-save-marker (marker beg end)
6573 "Check if MARKER is between BEG and END.
6574 If yes, remember the marker and the distance to BEG."
6575 (when (and (marker-buffer marker)
6576 (equal (marker-buffer marker) (current-buffer)))
6577 (if (and (>= marker beg) (< marker end))
6578 (push (cons marker (- marker beg)) org-markers-to-move))))
6580 (defun org-reinstall-markers-in-region (beg)
6581 "Move all remembered markers to their position relative to BEG."
6582 (mapc (lambda (x)
6583 (move-marker (car x) (+ beg (cdr x))))
6584 org-markers-to-move)
6585 (setq org-markers-to-move nil))
6587 (defun org-narrow-to-subtree ()
6588 "Narrow buffer to the current subtree."
6589 (interactive)
6590 (save-excursion
6591 (save-match-data
6592 (narrow-to-region
6593 (progn (org-back-to-heading t) (point))
6594 (progn (org-end-of-subtree t t) (point))))))
6596 (defun org-clone-subtree-with-time-shift (n &optional shift)
6597 "Clone the task (subtree) at point N times.
6598 The clones will be inserted as siblings.
6600 In interactive use, the user will be prompted for the number of clones
6601 to be produced, and for a time SHIFT, which may be a repeater as used
6602 in time stamps, for example `+3d'.
6604 When a valid repeater is given and the entry contains any time stamps,
6605 the clones will become a sequence in time, with time stamps in the
6606 subtree shifted for each clone produced. If SHIFT is nil or the
6607 empty string, time stamps will be left alone.
6609 If the original subtree did contain time stamps with a repeater,
6610 the following will happen:
6611 - the repeater will be removed in each clone
6612 - an additional clone will be produced, with the current, unshifted
6613 date(s) in the entry.
6614 - the original entry will be placed *after* all the clones, with
6615 repeater intact.
6616 - the start days in the repeater in the original entry will be shifted
6617 to past the last clone.
6618 I this way you can spell out a number of instances of a repeating task,
6619 and still retain the repeater to cover future instances of the task."
6620 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6621 (let (beg end template task
6622 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6623 (if (not (and (integerp n) (> n 0)))
6624 (error "Invalid number of replications %s" n))
6625 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6626 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6627 shift)))
6628 (error "Invalid shift specification %s" shift))
6629 (when doshift
6630 (setq shift-n (string-to-number (match-string 1 shift))
6631 shift-what (cdr (assoc (match-string 2 shift)
6632 '(("d" . day) ("w" . week)
6633 ("m" . month) ("y" . year))))))
6634 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6635 (setq nmin 1 nmax n)
6636 (org-back-to-heading t)
6637 (setq beg (point))
6638 (org-end-of-subtree t t)
6639 (setq end (point))
6640 (setq template (buffer-substring beg end))
6641 (when (and doshift
6642 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6643 (delete-region beg end)
6644 (setq end beg)
6645 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6646 (goto-char end)
6647 (loop for n from nmin to nmax do
6648 (if (not doshift)
6649 (setq task template)
6650 (with-temp-buffer
6651 (insert template)
6652 (org-mode)
6653 (goto-char (point-min))
6654 (while (re-search-forward org-ts-regexp-both nil t)
6655 (org-timestamp-change (* n shift-n) shift-what))
6656 (unless (= n n-no-remove)
6657 (goto-char (point-min))
6658 (while (re-search-forward org-ts-regexp nil t)
6659 (save-excursion
6660 (goto-char (match-beginning 0))
6661 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6662 (delete-region (match-beginning 1) (match-end 1))))))
6663 (setq task (buffer-string))))
6664 (insert task))
6665 (goto-char beg)))
6667 ;;; Outline Sorting
6669 (defun org-sort (with-case)
6670 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6671 Optional argument WITH-CASE means sort case-sensitively.
6672 With a double prefix argument, also remove duplicate entries."
6673 (interactive "P")
6674 (if (org-at-table-p)
6675 (org-call-with-arg 'org-table-sort-lines with-case)
6676 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6678 (defun org-sort-remove-invisible (s)
6679 (remove-text-properties 0 (length s) org-rm-props s)
6680 (while (string-match org-bracket-link-regexp s)
6681 (setq s (replace-match (if (match-end 2)
6682 (match-string 3 s)
6683 (match-string 1 s)) t t s)))
6686 (defvar org-priority-regexp) ; defined later in the file
6688 (defvar org-after-sorting-entries-or-items-hook nil
6689 "Hook that is run after a bunch of entries or items have been sorted.
6690 When children are sorted, the cursor is in the parent line when this
6691 hook gets called. When a region or a plain list is sorted, the cursor
6692 will be in the first entry of the sorted region/list.")
6694 (defun org-sort-entries-or-items
6695 (&optional with-case sorting-type getkey-func compare-func property)
6696 "Sort entries on a certain level of an outline tree, or plain list items.
6697 If there is an active region, the entries in the region are sorted.
6698 Else, if the cursor is before the first entry, sort the top-level items.
6699 Else, the children of the entry at point are sorted.
6700 If the cursor is at the first item in a plain list, the list items will be
6701 sorted.
6703 Sorting can be alphabetically, numerically, by date/time as given by
6704 a time stamp, by a property or by priority.
6706 The command prompts for the sorting type unless it has been given to the
6707 function through the SORTING-TYPE argument, which needs to a character,
6708 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6709 precise meaning of each character:
6711 n Numerically, by converting the beginning of the entry/item to a number.
6712 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6713 t By date/time, either the first active time stamp in the entry, or, if
6714 none exist, by the first inactive one.
6715 In items, only the first line will be chekced.
6716 s By the scheduled date/time.
6717 d By deadline date/time.
6718 c By creation time, which is assumed to be the first inactive time stamp
6719 at the beginning of a line.
6720 p By priority according to the cookie.
6721 r By the value of a property.
6723 Capital letters will reverse the sort order.
6725 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6726 called with point at the beginning of the record. It must return either
6727 a string or a number that should serve as the sorting key for that record.
6729 Comparing entries ignores case by default. However, with an optional argument
6730 WITH-CASE, the sorting considers case as well."
6731 (interactive "P")
6732 (let ((case-func (if with-case 'identity 'downcase))
6733 start beg end stars re re2
6734 txt what tmp plain-list-p)
6735 ;; Find beginning and end of region to sort
6736 (cond
6737 ((org-region-active-p)
6738 ;; we will sort the region
6739 (setq end (region-end)
6740 what "region")
6741 (goto-char (region-beginning))
6742 (if (not (org-on-heading-p)) (outline-next-heading))
6743 (setq start (point)))
6744 ((org-at-item-p)
6745 ;; we will sort this plain list
6746 (org-beginning-of-item-list) (setq start (point))
6747 (org-end-of-item-list) (setq end (point))
6748 (goto-char start)
6749 (setq plain-list-p t
6750 what "plain list"))
6751 ((or (org-on-heading-p)
6752 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6753 ;; we will sort the children of the current headline
6754 (org-back-to-heading)
6755 (setq start (point)
6756 end (progn (org-end-of-subtree t t)
6757 (org-back-over-empty-lines)
6758 (point))
6759 what "children")
6760 (goto-char start)
6761 (show-subtree)
6762 (outline-next-heading))
6764 ;; we will sort the top-level entries in this file
6765 (goto-char (point-min))
6766 (or (org-on-heading-p) (outline-next-heading))
6767 (setq start (point) end (point-max) what "top-level")
6768 (goto-char start)
6769 (show-all)))
6771 (setq beg (point))
6772 (if (>= beg end) (error "Nothing to sort"))
6774 (unless plain-list-p
6775 (looking-at "\\(\\*+\\)")
6776 (setq stars (match-string 1)
6777 re (concat "^" (regexp-quote stars) " +")
6778 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6779 txt (buffer-substring beg end))
6780 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6781 (if (and (not (equal stars "*")) (string-match re2 txt))
6782 (error "Region to sort contains a level above the first entry")))
6784 (unless sorting-type
6785 (message
6786 (if plain-list-p
6787 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6788 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6789 [t]ime [s]cheduled [d]eadline [c]reated
6790 A/N/T/S/D/C/P/O/F means reversed:")
6791 what)
6792 (setq sorting-type (read-char-exclusive))
6794 (and (= (downcase sorting-type) ?f)
6795 (setq getkey-func
6796 (org-icompleting-read "Sort using function: "
6797 obarray 'fboundp t nil nil))
6798 (setq getkey-func (intern getkey-func)))
6800 (and (= (downcase sorting-type) ?r)
6801 (setq property
6802 (org-icompleting-read "Property: "
6803 (mapcar 'list (org-buffer-property-keys t))
6804 nil t))))
6806 (message "Sorting entries...")
6808 (save-restriction
6809 (narrow-to-region start end)
6811 (let ((dcst (downcase sorting-type))
6812 (case-fold-search nil)
6813 (now (current-time)))
6814 (sort-subr
6815 (/= dcst sorting-type)
6816 ;; This function moves to the beginning character of the "record" to
6817 ;; be sorted.
6818 (if plain-list-p
6819 (lambda nil
6820 (if (org-at-item-p) t (goto-char (point-max))))
6821 (lambda nil
6822 (if (re-search-forward re nil t)
6823 (goto-char (match-beginning 0))
6824 (goto-char (point-max)))))
6825 ;; This function moves to the last character of the "record" being
6826 ;; sorted.
6827 (if plain-list-p
6828 'org-end-of-item
6829 (lambda nil
6830 (save-match-data
6831 (condition-case nil
6832 (outline-forward-same-level 1)
6833 (error
6834 (goto-char (point-max)))))))
6836 ;; This function returns the value that gets sorted against.
6837 (if plain-list-p
6838 (lambda nil
6839 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6840 (cond
6841 ((= dcst ?n)
6842 (string-to-number (buffer-substring (match-end 0)
6843 (point-at-eol))))
6844 ((= dcst ?a)
6845 (buffer-substring (match-end 0) (point-at-eol)))
6846 ((= dcst ?t)
6847 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6848 (re-search-forward org-ts-regexp-both
6849 (point-at-eol) t))
6850 (org-time-string-to-seconds (match-string 0))
6851 (org-float-time now)))
6852 ((= dcst ?f)
6853 (if getkey-func
6854 (progn
6855 (setq tmp (funcall getkey-func))
6856 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6857 tmp)
6858 (error "Invalid key function `%s'" getkey-func)))
6859 (t (error "Invalid sorting type `%c'" sorting-type)))))
6860 (lambda nil
6861 (cond
6862 ((= dcst ?n)
6863 (if (looking-at org-complex-heading-regexp)
6864 (string-to-number (match-string 4))
6865 nil))
6866 ((= dcst ?a)
6867 (if (looking-at org-complex-heading-regexp)
6868 (funcall case-func (match-string 4))
6869 nil))
6870 ((= dcst ?t)
6871 (let ((end (save-excursion (outline-next-heading) (point))))
6872 (if (or (re-search-forward org-ts-regexp end t)
6873 (re-search-forward org-ts-regexp-both end t))
6874 (org-time-string-to-seconds (match-string 0))
6875 (org-float-time now))))
6876 ((= dcst ?c)
6877 (let ((end (save-excursion (outline-next-heading) (point))))
6878 (if (re-search-forward
6879 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6880 end t)
6881 (org-time-string-to-seconds (match-string 0))
6882 (org-float-time now))))
6883 ((= dcst ?s)
6884 (let ((end (save-excursion (outline-next-heading) (point))))
6885 (if (re-search-forward org-scheduled-time-regexp end t)
6886 (org-time-string-to-seconds (match-string 1))
6887 (org-float-time now))))
6888 ((= dcst ?d)
6889 (let ((end (save-excursion (outline-next-heading) (point))))
6890 (if (re-search-forward org-deadline-time-regexp end t)
6891 (org-time-string-to-seconds (match-string 1))
6892 (org-float-time now))))
6893 ((= dcst ?p)
6894 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6895 (string-to-char (match-string 2))
6896 org-default-priority))
6897 ((= dcst ?r)
6898 (or (org-entry-get nil property) ""))
6899 ((= dcst ?o)
6900 (if (looking-at org-complex-heading-regexp)
6901 (- 9999 (length (member (match-string 2)
6902 org-todo-keywords-1)))))
6903 ((= dcst ?f)
6904 (if getkey-func
6905 (progn
6906 (setq tmp (funcall getkey-func))
6907 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6908 tmp)
6909 (error "Invalid key function `%s'" getkey-func)))
6910 (t (error "Invalid sorting type `%c'" sorting-type)))))
6912 (cond
6913 ((= dcst ?a) 'string<)
6914 ((= dcst ?f) compare-func)
6915 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6916 (t nil)))))
6917 (run-hooks 'org-after-sorting-entries-or-items-hook)
6918 (message "Sorting entries...done")))
6920 (defun org-do-sort (table what &optional with-case sorting-type)
6921 "Sort TABLE of WHAT according to SORTING-TYPE.
6922 The user will be prompted for the SORTING-TYPE if the call to this
6923 function does not specify it. WHAT is only for the prompt, to indicate
6924 what is being sorted. The sorting key will be extracted from
6925 the car of the elements of the table.
6926 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6927 (unless sorting-type
6928 (message
6929 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6930 what)
6931 (setq sorting-type (read-char-exclusive)))
6932 (let ((dcst (downcase sorting-type))
6933 extractfun comparefun)
6934 ;; Define the appropriate functions
6935 (cond
6936 ((= dcst ?n)
6937 (setq extractfun 'string-to-number
6938 comparefun (if (= dcst sorting-type) '< '>)))
6939 ((= dcst ?a)
6940 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6941 (lambda(x) (downcase (org-sort-remove-invisible x))))
6942 comparefun (if (= dcst sorting-type)
6943 'string<
6944 (lambda (a b) (and (not (string< a b))
6945 (not (string= a b)))))))
6946 ((= dcst ?t)
6947 (setq extractfun
6948 (lambda (x)
6949 (if (or (string-match org-ts-regexp x)
6950 (string-match org-ts-regexp-both x))
6951 (org-float-time
6952 (org-time-string-to-time (match-string 0 x)))
6954 comparefun (if (= dcst sorting-type) '< '>)))
6955 (t (error "Invalid sorting type `%c'" sorting-type)))
6957 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6958 table)
6959 (lambda (a b) (funcall comparefun (car a) (car b))))))
6962 ;;; The orgstruct minor mode
6964 ;; Define a minor mode which can be used in other modes in order to
6965 ;; integrate the org-mode structure editing commands.
6967 ;; This is really a hack, because the org-mode structure commands use
6968 ;; keys which normally belong to the major mode. Here is how it
6969 ;; works: The minor mode defines all the keys necessary to operate the
6970 ;; structure commands, but wraps the commands into a function which
6971 ;; tests if the cursor is currently at a headline or a plain list
6972 ;; item. If that is the case, the structure command is used,
6973 ;; temporarily setting many Org-mode variables like regular
6974 ;; expressions for filling etc. However, when any of those keys is
6975 ;; used at a different location, function uses `key-binding' to look
6976 ;; up if the key has an associated command in another currently active
6977 ;; keymap (minor modes, major mode, global), and executes that
6978 ;; command. There might be problems if any of the keys is otherwise
6979 ;; used as a prefix key.
6981 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6982 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6983 ;; addresses this by checking explicitly for both bindings.
6985 (defvar orgstruct-mode-map (make-sparse-keymap)
6986 "Keymap for the minor `orgstruct-mode'.")
6988 (defvar org-local-vars nil
6989 "List of local variables, for use by `orgstruct-mode'")
6991 ;;;###autoload
6992 (define-minor-mode orgstruct-mode
6993 "Toggle the minor more `orgstruct-mode'.
6994 This mode is for using Org-mode structure commands in other modes.
6995 The following key behave as if Org-mode was active, if the cursor
6996 is on a headline, or on a plain list item (both in the definition
6997 of Org-mode).
6999 M-up Move entry/item up
7000 M-down Move entry/item down
7001 M-left Promote
7002 M-right Demote
7003 M-S-up Move entry/item up
7004 M-S-down Move entry/item down
7005 M-S-left Promote subtree
7006 M-S-right Demote subtree
7007 M-q Fill paragraph and items like in Org-mode
7008 C-c ^ Sort entries
7009 C-c - Cycle list bullet
7010 TAB Cycle item visibility
7011 M-RET Insert new heading/item
7012 S-M-RET Insert new TODO heading / Checkbox item
7013 C-c C-c Set tags / toggle checkbox"
7014 nil " OrgStruct" nil
7015 (org-load-modules-maybe)
7016 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7018 ;;;###autoload
7019 (defun turn-on-orgstruct ()
7020 "Unconditionally turn on `orgstruct-mode'."
7021 (orgstruct-mode 1))
7023 (defun orgstruct++-mode (&optional arg)
7024 "Toggle `orgstruct-mode', the enhanced version of it.
7025 In addition to setting orgstruct-mode, this also exports all indentation
7026 and autofilling variables from org-mode into the buffer. It will also
7027 recognize item context in multiline items.
7028 Note that turning off orgstruct-mode will *not* remove the
7029 indentation/paragraph settings. This can only be done by refreshing the
7030 major mode, for example with \\[normal-mode]."
7031 (interactive "P")
7032 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7033 (if (< arg 1)
7034 (orgstruct-mode -1)
7035 (orgstruct-mode 1)
7036 (let (var val)
7037 (mapc
7038 (lambda (x)
7039 (when (string-match
7040 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7041 (symbol-name (car x)))
7042 (setq var (car x) val (nth 1 x))
7043 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7044 org-local-vars)
7045 (org-set-local 'orgstruct-is-++ t))))
7047 (defvar orgstruct-is-++ nil
7048 "Is orgstruct-mode in ++ version in the current-buffer?")
7049 (make-variable-buffer-local 'orgstruct-is-++)
7051 ;;;###autoload
7052 (defun turn-on-orgstruct++ ()
7053 "Unconditionally turn on `orgstruct++-mode'."
7054 (orgstruct++-mode 1))
7056 (defun orgstruct-error ()
7057 "Error when there is no default binding for a structure key."
7058 (interactive)
7059 (error "This key has no function outside structure elements"))
7061 (defun orgstruct-setup ()
7062 "Setup orgstruct keymaps."
7063 (let ((nfunc 0)
7064 (bindings
7065 (list
7066 '([(meta up)] org-metaup)
7067 '([(meta down)] org-metadown)
7068 '([(meta left)] org-metaleft)
7069 '([(meta right)] org-metaright)
7070 '([(meta shift up)] org-shiftmetaup)
7071 '([(meta shift down)] org-shiftmetadown)
7072 '([(meta shift left)] org-shiftmetaleft)
7073 '([(meta shift right)] org-shiftmetaright)
7074 '([?\e (up)] org-metaup)
7075 '([?\e (down)] org-metadown)
7076 '([?\e (left)] org-metaleft)
7077 '([?\e (right)] org-metaright)
7078 '([?\e (shift up)] org-shiftmetaup)
7079 '([?\e (shift down)] org-shiftmetadown)
7080 '([?\e (shift left)] org-shiftmetaleft)
7081 '([?\e (shift right)] org-shiftmetaright)
7082 '([(shift up)] org-shiftup)
7083 '([(shift down)] org-shiftdown)
7084 '([(shift left)] org-shiftleft)
7085 '([(shift right)] org-shiftright)
7086 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7087 '("\M-q" fill-paragraph)
7088 '("\C-c^" org-sort)
7089 '("\C-c-" org-cycle-list-bullet)))
7090 elt key fun cmd)
7091 (while (setq elt (pop bindings))
7092 (setq nfunc (1+ nfunc))
7093 (setq key (org-key (car elt))
7094 fun (nth 1 elt)
7095 cmd (orgstruct-make-binding fun nfunc key))
7096 (org-defkey orgstruct-mode-map key cmd))
7098 ;; Special treatment needed for TAB and RET
7099 (org-defkey orgstruct-mode-map [(tab)]
7100 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7101 (org-defkey orgstruct-mode-map "\C-i"
7102 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7104 (org-defkey orgstruct-mode-map "\M-\C-m"
7105 (orgstruct-make-binding 'org-insert-heading 105
7106 "\M-\C-m" [(meta return)]))
7107 (org-defkey orgstruct-mode-map [(meta return)]
7108 (orgstruct-make-binding 'org-insert-heading 106
7109 [(meta return)] "\M-\C-m"))
7111 (org-defkey orgstruct-mode-map [(shift meta return)]
7112 (orgstruct-make-binding 'org-insert-todo-heading 107
7113 [(meta return)] "\M-\C-m"))
7115 (org-defkey orgstruct-mode-map "\e\C-m"
7116 (orgstruct-make-binding 'org-insert-heading 108
7117 "\e\C-m" [?\e (return)]))
7118 (org-defkey orgstruct-mode-map [?\e (return)]
7119 (orgstruct-make-binding 'org-insert-heading 109
7120 [?\e (return)] "\e\C-m"))
7121 (org-defkey orgstruct-mode-map [?\e (shift return)]
7122 (orgstruct-make-binding 'org-insert-todo-heading 110
7123 [?\e (return)] "\e\C-m"))
7125 (unless org-local-vars
7126 (setq org-local-vars (org-get-local-variables)))
7130 (defun orgstruct-make-binding (fun n &rest keys)
7131 "Create a function for binding in the structure minor mode.
7132 FUN is the command to call inside a table. N is used to create a unique
7133 command name. KEYS are keys that should be checked in for a command
7134 to execute outside of tables."
7135 (eval
7136 (list 'defun
7137 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7138 '(arg)
7139 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7140 "Outside of structure, run the binding of `"
7141 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7142 "'.")
7143 '(interactive "p")
7144 (list 'if
7145 `(org-context-p 'headline 'item
7146 (and orgstruct-is-++
7147 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7148 'item-body))
7149 (list 'org-run-like-in-org-mode (list 'quote fun))
7150 (list 'let '(orgstruct-mode)
7151 (list 'call-interactively
7152 (append '(or)
7153 (mapcar (lambda (k)
7154 (list 'key-binding k))
7155 keys)
7156 '('orgstruct-error))))))))
7158 (defun org-context-p (&rest contexts)
7159 "Check if local context is any of CONTEXTS.
7160 Possible values in the list of contexts are `table', `headline', and `item'."
7161 (let ((pos (point)))
7162 (goto-char (point-at-bol))
7163 (prog1 (or (and (memq 'table contexts)
7164 (looking-at "[ \t]*|"))
7165 (and (memq 'headline contexts)
7166 ;;????????? (looking-at "\\*+"))
7167 (looking-at outline-regexp))
7168 (and (memq 'item contexts)
7169 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7170 (and (memq 'item-body contexts)
7171 (org-in-item-p)))
7172 (goto-char pos))))
7174 (defun org-get-local-variables ()
7175 "Return a list of all local variables in an org-mode buffer."
7176 (let (varlist)
7177 (with-current-buffer (get-buffer-create "*Org tmp*")
7178 (erase-buffer)
7179 (org-mode)
7180 (setq varlist (buffer-local-variables)))
7181 (kill-buffer "*Org tmp*")
7182 (delq nil
7183 (mapcar
7184 (lambda (x)
7185 (setq x
7186 (if (symbolp x)
7187 (list x)
7188 (list (car x) (list 'quote (cdr x)))))
7189 (if (string-match
7190 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7191 (symbol-name (car x)))
7192 x nil))
7193 varlist))))
7195 ;;;###autoload
7196 (defun org-run-like-in-org-mode (cmd)
7197 "Run a command, pretending that the current buffer is in Org-mode.
7198 This will temporarily bind local variables that are typically bound in
7199 Org-mode to the values they have in Org-mode, and then interactively
7200 call CMD."
7201 (org-load-modules-maybe)
7202 (unless org-local-vars
7203 (setq org-local-vars (org-get-local-variables)))
7204 (eval (list 'let org-local-vars
7205 (list 'call-interactively (list 'quote cmd)))))
7207 ;;;; Archiving
7209 (defun org-get-category (&optional pos)
7210 "Get the category applying to position POS."
7211 (get-text-property (or pos (point)) 'org-category))
7213 (defun org-refresh-category-properties ()
7214 "Refresh category text properties in the buffer."
7215 (let ((def-cat (cond
7216 ((null org-category)
7217 (if buffer-file-name
7218 (file-name-sans-extension
7219 (file-name-nondirectory buffer-file-name))
7220 "???"))
7221 ((symbolp org-category) (symbol-name org-category))
7222 (t org-category)))
7223 beg end cat pos optionp)
7224 (org-unmodified
7225 (save-excursion
7226 (save-restriction
7227 (widen)
7228 (goto-char (point-min))
7229 (put-text-property (point) (point-max) 'org-category def-cat)
7230 (while (re-search-forward
7231 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7232 (setq pos (match-end 0)
7233 optionp (equal (char-after (match-beginning 0)) ?#)
7234 cat (org-trim (match-string 2)))
7235 (if optionp
7236 (setq beg (point-at-bol) end (point-max))
7237 (org-back-to-heading t)
7238 (setq beg (point) end (org-end-of-subtree t t)))
7239 (put-text-property beg end 'org-category cat)
7240 (goto-char pos)))))))
7243 ;;;; Link Stuff
7245 ;;; Link abbreviations
7247 (defun org-link-expand-abbrev (link)
7248 "Apply replacements as defined in `org-link-abbrev-alist."
7249 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7250 (let* ((key (match-string 1 link))
7251 (as (or (assoc key org-link-abbrev-alist-local)
7252 (assoc key org-link-abbrev-alist)))
7253 (tag (and (match-end 2) (match-string 3 link)))
7254 rpl)
7255 (if (not as)
7256 link
7257 (setq rpl (cdr as))
7258 (cond
7259 ((symbolp rpl) (funcall rpl tag))
7260 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7261 ((string-match "%h" rpl)
7262 (replace-match (url-hexify-string (or tag "")) t t rpl))
7263 (t (concat rpl tag)))))
7264 link))
7266 ;;; Storing and inserting links
7268 (defvar org-insert-link-history nil
7269 "Minibuffer history for links inserted with `org-insert-link'.")
7271 (defvar org-stored-links nil
7272 "Contains the links stored with `org-store-link'.")
7274 (defvar org-store-link-plist nil
7275 "Plist with info about the most recently link created with `org-store-link'.")
7277 (defvar org-link-protocols nil
7278 "Link protocols added to Org-mode using `org-add-link-type'.")
7280 (defvar org-store-link-functions nil
7281 "List of functions that are called to create and store a link.
7282 Each function will be called in turn until one returns a non-nil
7283 value. Each function should check if it is responsible for creating
7284 this link (for example by looking at the major mode).
7285 If not, it must exit and return nil.
7286 If yes, it should return a non-nil value after a calling
7287 `org-store-link-props' with a list of properties and values.
7288 Special properties are:
7290 :type The link prefix. like \"http\". This must be given.
7291 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7292 This is obligatory as well.
7293 :description Optional default description for the second pair
7294 of brackets in an Org-mode link. The user can still change
7295 this when inserting this link into an Org-mode buffer.
7297 In addition to these, any additional properties can be specified
7298 and then used in remember templates.")
7300 (defun org-add-link-type (type &optional follow export)
7301 "Add TYPE to the list of `org-link-types'.
7302 Re-compute all regular expressions depending on `org-link-types'
7304 FOLLOW and EXPORT are two functions.
7306 FOLLOW should take the link path as the single argument and do whatever
7307 is necessary to follow the link, for example find a file or display
7308 a mail message.
7310 EXPORT should format the link path for export to one of the export formats.
7311 It should be a function accepting three arguments:
7313 path the path of the link, the text after the prefix (like \"http:\")
7314 desc the description of the link, if any, nil if there was no description
7315 format the export format, a symbol like `html' or `latex'.
7317 The function may use the FORMAT information to return different values
7318 depending on the format. The return value will be put literally into
7319 the exported file.
7320 Org-mode has a built-in default for exporting links. If you are happy with
7321 this default, there is no need to define an export function for the link
7322 type. For a simple example of an export function, see `org-bbdb.el'."
7323 (add-to-list 'org-link-types type t)
7324 (org-make-link-regexps)
7325 (if (assoc type org-link-protocols)
7326 (setcdr (assoc type org-link-protocols) (list follow export))
7327 (push (list type follow export) org-link-protocols)))
7329 (defvar org-agenda-buffer-name)
7331 ;;;###autoload
7332 (defun org-store-link (arg)
7333 "\\<org-mode-map>Store an org-link to the current location.
7334 This link is added to `org-stored-links' and can later be inserted
7335 into an org-buffer with \\[org-insert-link].
7337 For some link types, a prefix arg is interpreted:
7338 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7339 For file links, arg negates `org-context-in-file-links'."
7340 (interactive "P")
7341 (org-load-modules-maybe)
7342 (setq org-store-link-plist nil) ; reset
7343 (let ((outline-regexp (org-get-limited-outline-regexp))
7344 link cpltxt desc description search txt custom-id)
7345 (cond
7347 ((run-hook-with-args-until-success 'org-store-link-functions)
7348 (setq link (plist-get org-store-link-plist :link)
7349 desc (or (plist-get org-store-link-plist :description) link)))
7351 ((equal (buffer-name) "*Org Edit Src Example*")
7352 (let (label gc)
7353 (while (or (not label)
7354 (save-excursion
7355 (save-restriction
7356 (widen)
7357 (goto-char (point-min))
7358 (re-search-forward
7359 (regexp-quote (format org-coderef-label-format label))
7360 nil t))))
7361 (when label (message "Label exists already") (sit-for 2))
7362 (setq label (read-string "Code line label: " label)))
7363 (end-of-line 1)
7364 (setq link (format org-coderef-label-format label))
7365 (setq gc (- 79 (length link)))
7366 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7367 (insert link)
7368 (setq link (concat "(" label ")") desc nil)))
7370 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7371 ;; We are in the agenda, link to referenced location
7372 (let ((m (or (get-text-property (point) 'org-hd-marker)
7373 (get-text-property (point) 'org-marker))))
7374 (when m
7375 (org-with-point-at m
7376 (call-interactively 'org-store-link)))))
7378 ((eq major-mode 'calendar-mode)
7379 (let ((cd (calendar-cursor-to-date)))
7380 (setq link
7381 (format-time-string
7382 (car org-time-stamp-formats)
7383 (apply 'encode-time
7384 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7385 nil nil nil))))
7386 (org-store-link-props :type "calendar" :date cd)))
7388 ((eq major-mode 'w3-mode)
7389 (setq cpltxt (if (and (buffer-name)
7390 (not (string-match "Untitled" (buffer-name))))
7391 (buffer-name)
7392 (url-view-url t))
7393 link (org-make-link (url-view-url t)))
7394 (org-store-link-props :type "w3" :url (url-view-url t)))
7396 ((eq major-mode 'w3m-mode)
7397 (setq cpltxt (or w3m-current-title w3m-current-url)
7398 link (org-make-link w3m-current-url))
7399 (org-store-link-props :type "w3m" :url (url-view-url t)))
7401 ((setq search (run-hook-with-args-until-success
7402 'org-create-file-search-functions))
7403 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7404 "::" search))
7405 (setq cpltxt (or description link)))
7407 ((eq major-mode 'image-mode)
7408 (setq cpltxt (concat "file:"
7409 (abbreviate-file-name buffer-file-name))
7410 link (org-make-link cpltxt))
7411 (org-store-link-props :type "image" :file buffer-file-name))
7413 ((eq major-mode 'dired-mode)
7414 ;; link to the file in the current line
7415 (setq cpltxt (concat "file:"
7416 (abbreviate-file-name
7417 (expand-file-name
7418 (dired-get-filename nil t))))
7419 link (org-make-link cpltxt)))
7421 ((and buffer-file-name (org-mode-p))
7422 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7423 (cond
7424 ((org-in-regexp "<<\\(.*?\\)>>")
7425 (setq cpltxt
7426 (concat "file:"
7427 (abbreviate-file-name buffer-file-name)
7428 "::" (match-string 1))
7429 link (org-make-link cpltxt)))
7430 ((and (featurep 'org-id)
7431 (or (eq org-link-to-org-use-id t)
7432 (and (eq org-link-to-org-use-id 'create-if-interactive)
7433 (interactive-p))
7434 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7435 (interactive-p)
7436 (not custom-id))
7437 (and org-link-to-org-use-id
7438 (condition-case nil
7439 (org-entry-get nil "ID")
7440 (error nil)))))
7441 ;; We can make a link using the ID.
7442 (setq link (condition-case nil
7443 (prog1 (org-id-store-link)
7444 (setq desc (plist-get org-store-link-plist
7445 :description)))
7446 (error
7447 ;; probably before first headline, link to file only
7448 (concat "file:"
7449 (abbreviate-file-name buffer-file-name))))))
7451 ;; Just link to current headline
7452 (setq cpltxt (concat "file:"
7453 (abbreviate-file-name buffer-file-name)))
7454 ;; Add a context search string
7455 (when (org-xor org-context-in-file-links arg)
7456 (setq txt (cond
7457 ((org-on-heading-p) nil)
7458 ((org-region-active-p)
7459 (buffer-substring (region-beginning) (region-end)))
7460 (t nil)))
7461 (when (or (null txt) (string-match "\\S-" txt))
7462 (setq cpltxt
7463 (concat cpltxt "::"
7464 (condition-case nil
7465 (org-make-org-heading-search-string txt)
7466 (error "")))
7467 desc (or (nth 4 (ignore-errors
7468 (org-heading-components))) "NONE"))))
7469 (if (string-match "::\\'" cpltxt)
7470 (setq cpltxt (substring cpltxt 0 -2)))
7471 (setq link (org-make-link cpltxt)))))
7473 ((buffer-file-name (buffer-base-buffer))
7474 ;; Just link to this file here.
7475 (setq cpltxt (concat "file:"
7476 (abbreviate-file-name
7477 (buffer-file-name (buffer-base-buffer)))))
7478 ;; Add a context string
7479 (when (org-xor org-context-in-file-links arg)
7480 (setq txt (if (org-region-active-p)
7481 (buffer-substring (region-beginning) (region-end))
7482 (buffer-substring (point-at-bol) (point-at-eol))))
7483 ;; Only use search option if there is some text.
7484 (when (string-match "\\S-" txt)
7485 (setq cpltxt
7486 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7487 desc "NONE")))
7488 (setq link (org-make-link cpltxt)))
7490 ((interactive-p)
7491 (error "Cannot link to a buffer which is not visiting a file"))
7493 (t (setq link nil)))
7495 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7496 (setq link (or link cpltxt)
7497 desc (or desc cpltxt))
7498 (if (equal desc "NONE") (setq desc nil))
7500 (if (and (or (interactive-p) executing-kbd-macro) link)
7501 (progn
7502 (setq org-stored-links
7503 (cons (list link desc) org-stored-links))
7504 (message "Stored: %s" (or desc link))
7505 (when custom-id
7506 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7507 "::#" custom-id))
7508 (setq org-stored-links
7509 (cons (list link desc) org-stored-links))))
7510 (and link (org-make-link-string link desc)))))
7512 (defun org-store-link-props (&rest plist)
7513 "Store link properties, extract names and addresses."
7514 (let (x adr)
7515 (when (setq x (plist-get plist :from))
7516 (setq adr (mail-extract-address-components x))
7517 (setq plist (plist-put plist :fromname (car adr)))
7518 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7519 (when (setq x (plist-get plist :to))
7520 (setq adr (mail-extract-address-components x))
7521 (setq plist (plist-put plist :toname (car adr)))
7522 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7523 (let ((from (plist-get plist :from))
7524 (to (plist-get plist :to)))
7525 (when (and from to org-from-is-user-regexp)
7526 (setq plist
7527 (plist-put plist :fromto
7528 (if (string-match org-from-is-user-regexp from)
7529 (concat "to %t")
7530 (concat "from %f"))))))
7531 (setq org-store-link-plist plist))
7533 (defun org-add-link-props (&rest plist)
7534 "Add these properties to the link property list."
7535 (let (key value)
7536 (while plist
7537 (setq key (pop plist) value (pop plist))
7538 (setq org-store-link-plist
7539 (plist-put org-store-link-plist key value)))))
7541 (defun org-email-link-description (&optional fmt)
7542 "Return the description part of an email link.
7543 This takes information from `org-store-link-plist' and formats it
7544 according to FMT (default from `org-email-link-description-format')."
7545 (setq fmt (or fmt org-email-link-description-format))
7546 (let* ((p org-store-link-plist)
7547 (to (plist-get p :toaddress))
7548 (from (plist-get p :fromaddress))
7549 (table
7550 (list
7551 (cons "%c" (plist-get p :fromto))
7552 (cons "%F" (plist-get p :from))
7553 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7554 (cons "%T" (plist-get p :to))
7555 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7556 (cons "%s" (plist-get p :subject))
7557 (cons "%m" (plist-get p :message-id)))))
7558 (when (string-match "%c" fmt)
7559 ;; Check if the user wrote this message
7560 (if (and org-from-is-user-regexp from to
7561 (save-match-data (string-match org-from-is-user-regexp from)))
7562 (setq fmt (replace-match "to %t" t t fmt))
7563 (setq fmt (replace-match "from %f" t t fmt))))
7564 (org-replace-escapes fmt table)))
7566 (defun org-make-org-heading-search-string (&optional string heading)
7567 "Make search string for STRING or current headline."
7568 (interactive)
7569 (let ((s (or string (org-get-heading))))
7570 (unless (and string (not heading))
7571 ;; We are using a headline, clean up garbage in there.
7572 (if (string-match org-todo-regexp s)
7573 (setq s (replace-match "" t t s)))
7574 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7575 (setq s (replace-match "" t t s)))
7576 (setq s (org-trim s))
7577 (if (string-match (concat "^\\(" org-quote-string "\\|"
7578 org-comment-string "\\)") s)
7579 (setq s (replace-match "" t t s)))
7580 (while (string-match org-ts-regexp s)
7581 (setq s (replace-match "" t t s))))
7582 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7583 (setq s (replace-match " " t t s)))
7584 (or string (setq s (concat "*" s))) ; Add * for headlines
7585 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7587 (defun org-make-link (&rest strings)
7588 "Concatenate STRINGS."
7589 (apply 'concat strings))
7591 (defun org-make-link-string (link &optional description)
7592 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7593 (unless (string-match "\\S-" link)
7594 (error "Empty link"))
7595 (when (stringp description)
7596 ;; Remove brackets from the description, they are fatal.
7597 (while (string-match "\\[" description)
7598 (setq description (replace-match "{" t t description)))
7599 (while (string-match "\\]" description)
7600 (setq description (replace-match "}" t t description))))
7601 (when (equal (org-link-escape link) description)
7602 ;; No description needed, it is identical
7603 (setq description nil))
7604 (when (and (not description)
7605 (not (equal link (org-link-escape link))))
7606 (setq description (org-extract-attributes link)))
7607 (concat "[[" (org-link-escape link) "]"
7608 (if description (concat "[" description "]") "")
7609 "]"))
7611 (defconst org-link-escape-chars
7612 '((?\ . "%20")
7613 (?\[ . "%5B")
7614 (?\] . "%5D")
7615 (?\340 . "%E0") ; `a
7616 (?\342 . "%E2") ; ^a
7617 (?\347 . "%E7") ; ,c
7618 (?\350 . "%E8") ; `e
7619 (?\351 . "%E9") ; 'e
7620 (?\352 . "%EA") ; ^e
7621 (?\356 . "%EE") ; ^i
7622 (?\364 . "%F4") ; ^o
7623 (?\371 . "%F9") ; `u
7624 (?\373 . "%FB") ; ^u
7625 (?\; . "%3B")
7626 (?? . "%3F")
7627 (?= . "%3D")
7628 (?+ . "%2B")
7630 "Association list of escapes for some characters problematic in links.
7631 This is the list that is used for internal purposes.")
7633 (defvar org-url-encoding-use-url-hexify nil)
7635 (defconst org-link-escape-chars-browser
7636 '((?\ . "%20")) ; 32 for the SPC char
7637 "Association list of escapes for some characters problematic in links.
7638 This is the list that is used before handing over to the browser.")
7640 (defun org-link-escape (text &optional table)
7641 "Escape characters in TEXT that are problematic for links."
7642 (if org-url-encoding-use-url-hexify
7643 (url-hexify-string text)
7644 (setq table (or table org-link-escape-chars))
7645 (when text
7646 (let ((re (mapconcat (lambda (x) (regexp-quote
7647 (char-to-string (car x))))
7648 table "\\|")))
7649 (while (string-match re text)
7650 (setq text
7651 (replace-match
7652 (cdr (assoc (string-to-char (match-string 0 text))
7653 table))
7654 t t text)))
7655 text))))
7657 (defun org-link-unescape (text &optional table)
7658 "Reverse the action of `org-link-escape'."
7659 (if org-url-encoding-use-url-hexify
7660 (url-unhex-string text)
7661 (setq table (or table org-link-escape-chars))
7662 (when text
7663 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7664 table "\\|")))
7665 (while (string-match re text)
7666 (setq text
7667 (replace-match
7668 (char-to-string (car (rassoc (match-string 0 text) table)))
7669 t t text)))
7670 text))))
7672 (defun org-xor (a b)
7673 "Exclusive or."
7674 (if a (not b) b))
7676 (defun org-fixup-message-id-for-http (s)
7677 "Replace special characters in a message id, so it can be used in an http query."
7678 (while (string-match "<" s)
7679 (setq s (replace-match "%3C" t t s)))
7680 (while (string-match ">" s)
7681 (setq s (replace-match "%3E" t t s)))
7682 (while (string-match "@" s)
7683 (setq s (replace-match "%40" t t s)))
7686 ;;;###autoload
7687 (defun org-insert-link-global ()
7688 "Insert a link like Org-mode does.
7689 This command can be called in any mode to insert a link in Org-mode syntax."
7690 (interactive)
7691 (org-load-modules-maybe)
7692 (org-run-like-in-org-mode 'org-insert-link))
7694 (defun org-insert-link (&optional complete-file link-location)
7695 "Insert a link. At the prompt, enter the link.
7697 Completion can be used to insert any of the link protocol prefixes like
7698 http or ftp in use.
7700 The history can be used to select a link previously stored with
7701 `org-store-link'. When the empty string is entered (i.e. if you just
7702 press RET at the prompt), the link defaults to the most recently
7703 stored link. As SPC triggers completion in the minibuffer, you need to
7704 use M-SPC or C-q SPC to force the insertion of a space character.
7706 You will also be prompted for a description, and if one is given, it will
7707 be displayed in the buffer instead of the link.
7709 If there is already a link at point, this command will allow you to edit link
7710 and description parts.
7712 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7713 be selected using completion. The path to the file will be relative to the
7714 current directory if the file is in the current directory or a subdirectory.
7715 Otherwise, the link will be the absolute path as completed in the minibuffer
7716 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7717 option `org-link-file-path-type'.
7719 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7720 the current directory or below.
7722 With three \\[universal-argument] prefixes, negate the meaning of
7723 `org-keep-stored-link-after-insertion'.
7725 If `org-make-link-description-function' is non-nil, this function will be
7726 called with the link target, and the result will be the default
7727 link description.
7729 If the LINK-LOCATION parameter is non-nil, this value will be
7730 used as the link location instead of reading one interactively."
7731 (interactive "P")
7732 (let* ((wcf (current-window-configuration))
7733 (region (if (org-region-active-p)
7734 (buffer-substring (region-beginning) (region-end))))
7735 (remove (and region (list (region-beginning) (region-end))))
7736 (desc region)
7737 tmphist ; byte-compile incorrectly complains about this
7738 (link link-location)
7739 entry file all-prefixes)
7740 (cond
7741 (link-location) ; specified by arg, just use it.
7742 ((org-in-regexp org-bracket-link-regexp 1)
7743 ;; We do have a link at point, and we are going to edit it.
7744 (setq remove (list (match-beginning 0) (match-end 0)))
7745 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7746 (setq link (read-string "Link: "
7747 (org-link-unescape
7748 (org-match-string-no-properties 1)))))
7749 ((or (org-in-regexp org-angle-link-re)
7750 (org-in-regexp org-plain-link-re))
7751 ;; Convert to bracket link
7752 (setq remove (list (match-beginning 0) (match-end 0))
7753 link (read-string "Link: "
7754 (org-remove-angle-brackets (match-string 0)))))
7755 ((member complete-file '((4) (16)))
7756 ;; Completing read for file names.
7757 (setq link (org-file-complete-link complete-file)))
7759 ;; Read link, with completion for stored links.
7760 (with-output-to-temp-buffer "*Org Links*"
7761 (princ "Insert a link.
7762 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7763 (when org-stored-links
7764 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7765 (princ (mapconcat
7766 (lambda (x)
7767 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7768 (reverse org-stored-links) "\n"))))
7769 (let ((cw (selected-window)))
7770 (select-window (get-buffer-window "*Org Links*"))
7771 (setq truncate-lines t)
7772 (unless (pos-visible-in-window-p (point-max))
7773 (org-fit-window-to-buffer))
7774 (and (window-live-p cw) (select-window cw)))
7775 ;; Fake a link history, containing the stored links.
7776 (setq tmphist (append (mapcar 'car org-stored-links)
7777 org-insert-link-history))
7778 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7779 (mapcar 'car org-link-abbrev-alist)
7780 org-link-types))
7781 (unwind-protect
7782 (progn
7783 (setq link
7784 (let ((org-completion-use-ido nil)
7785 (org-completion-use-iswitchb nil))
7786 (org-completing-read
7787 "Link: "
7788 (append
7789 (mapcar (lambda (x) (list (concat x ":")))
7790 all-prefixes)
7791 (mapcar 'car org-stored-links))
7792 nil nil nil
7793 'tmphist
7794 (car (car org-stored-links)))))
7795 (if (or (member link all-prefixes)
7796 (and (equal ":" (substring link -1))
7797 (member (substring link 0 -1) all-prefixes)
7798 (setq link (substring link 0 -1))))
7799 (setq link (org-link-try-special-completion link))))
7800 (set-window-configuration wcf)
7801 (kill-buffer "*Org Links*"))
7802 (setq entry (assoc link org-stored-links))
7803 (or entry (push link org-insert-link-history))
7804 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7805 (not org-keep-stored-link-after-insertion))
7806 (setq org-stored-links (delq (assoc link org-stored-links)
7807 org-stored-links)))
7808 (setq desc (or desc (nth 1 entry)))))
7810 (if (string-match org-plain-link-re link)
7811 ;; URL-like link, normalize the use of angular brackets.
7812 (setq link (org-make-link (org-remove-angle-brackets link))))
7814 ;; Check if we are linking to the current file with a search option
7815 ;; If yes, simplify the link by using only the search option.
7816 (when (and buffer-file-name
7817 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7818 (let* ((path (match-string 1 link))
7819 (case-fold-search nil)
7820 (search (match-string 2 link)))
7821 (save-match-data
7822 (if (equal (file-truename buffer-file-name) (file-truename path))
7823 ;; We are linking to this same file, with a search option
7824 (setq link search)))))
7826 ;; Check if we can/should use a relative path. If yes, simplify the link
7827 (when (string-match "^file:\\(.*\\)" link)
7828 (let* ((path (match-string 1 link))
7829 (origpath path)
7830 (case-fold-search nil))
7831 (cond
7832 ((or (eq org-link-file-path-type 'absolute)
7833 (equal complete-file '(16)))
7834 (setq path (abbreviate-file-name (expand-file-name path))))
7835 ((eq org-link-file-path-type 'noabbrev)
7836 (setq path (expand-file-name path)))
7837 ((eq org-link-file-path-type 'relative)
7838 (setq path (file-relative-name path)))
7840 (save-match-data
7841 (if (string-match (concat "^" (regexp-quote
7842 (file-name-as-directory
7843 (expand-file-name "."))))
7844 (expand-file-name path))
7845 ;; We are linking a file with relative path name.
7846 (setq path (substring (expand-file-name path)
7847 (match-end 0)))
7848 (setq path (abbreviate-file-name (expand-file-name path)))))))
7849 (setq link (concat "file:" path))
7850 (if (equal desc origpath)
7851 (setq desc path))))
7853 (if org-make-link-description-function
7854 (setq desc (funcall org-make-link-description-function link desc)))
7856 (setq desc (read-string "Description: " desc))
7857 (unless (string-match "\\S-" desc) (setq desc nil))
7858 (if remove (apply 'delete-region remove))
7859 (insert (org-make-link-string link desc))))
7861 (defun org-link-try-special-completion (type)
7862 "If there is completion support for link type TYPE, offer it."
7863 (let ((fun (intern (concat "org-" type "-complete-link"))))
7864 (if (functionp fun)
7865 (funcall fun)
7866 (read-string "Link (no completion support): " (concat type ":")))))
7868 (defun org-file-complete-link (&optional arg)
7869 "Create a file link using completion."
7870 (let (file link)
7871 (setq file (read-file-name "File: "))
7872 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7873 (pwd1 (file-name-as-directory (abbreviate-file-name
7874 (expand-file-name ".")))))
7875 (cond
7876 ((equal arg '(16))
7877 (setq link (org-make-link
7878 "file:"
7879 (abbreviate-file-name (expand-file-name file)))))
7880 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7881 (setq link (org-make-link "file:" (match-string 1 file))))
7882 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7883 (expand-file-name file))
7884 (setq link (org-make-link
7885 "file:" (match-string 1 (expand-file-name file)))))
7886 (t (setq link (org-make-link "file:" file)))))
7887 link))
7889 (defun org-completing-read (&rest args)
7890 "Completing-read with SPACE being a normal character."
7891 (let ((minibuffer-local-completion-map
7892 (copy-keymap minibuffer-local-completion-map)))
7893 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7894 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7895 (apply 'org-icompleting-read args)))
7897 (defun org-completing-read-no-i (&rest args)
7898 (let (org-completion-use-ido org-completion-use-iswitchb)
7899 (apply 'org-completing-read args)))
7901 (defun org-iswitchb-completing-read (prompt choices &rest args)
7902 "Use iswitch as a completing-read replacement to choose from choices.
7903 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7904 from."
7905 (let* ((iswitchb-use-virtual-buffers nil)
7906 (iswitchb-make-buflist-hook
7907 (lambda ()
7908 (setq iswitchb-temp-buflist choices))))
7909 (iswitchb-read-buffer prompt)))
7911 (defun org-icompleting-read (&rest args)
7912 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
7913 (org-without-partial-completion
7914 (if (and org-completion-use-ido
7915 (fboundp 'ido-completing-read)
7916 (boundp 'ido-mode) ido-mode
7917 (listp (second args)))
7918 (let ((ido-enter-matching-directory nil))
7919 (apply 'ido-completing-read (concat (car args))
7920 (if (consp (car (nth 1 args)))
7921 (mapcar (lambda (x) (car x)) (nth 1 args))
7922 (nth 1 args))
7923 (cddr args)))
7924 (if (and org-completion-use-iswitchb
7925 (boundp 'iswitchb-mode) iswitchb-mode
7926 (listp (second args)))
7927 (apply 'org-iswitchb-completing-read (concat (car args))
7928 (if (consp (car (nth 1 args)))
7929 (mapcar (lambda (x) (car x)) (nth 1 args))
7930 (nth 1 args))
7931 (cddr args))
7932 (apply 'completing-read args)))))
7934 (defun org-extract-attributes (s)
7935 "Extract the attributes cookie from a string and set as text property."
7936 (let (a attr (start 0) key value)
7937 (save-match-data
7938 (when (string-match "{{\\([^}]+\\)}}$" s)
7939 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7940 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7941 (setq key (match-string 1 a) value (match-string 2 a)
7942 start (match-end 0)
7943 attr (plist-put attr (intern key) value))))
7944 (org-add-props s nil 'org-attr attr))
7947 (defun org-extract-attributes-from-string (tag)
7948 (let (key value attr)
7949 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7950 (setq key (match-string 1 tag) value (match-string 2 tag)
7951 tag (replace-match "" t t tag)
7952 attr (plist-put attr (intern key) value)))
7953 (cons tag attr)))
7955 (defun org-attributes-to-string (plist)
7956 "Format a property list into an HTML attribute list."
7957 (let ((s "") key value)
7958 (while plist
7959 (setq key (pop plist) value (pop plist))
7960 (and value
7961 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7964 ;;; Opening/following a link
7966 (defvar org-link-search-failed nil)
7968 (defun org-next-link ()
7969 "Move forward to the next link.
7970 If the link is in hidden text, expose it."
7971 (interactive)
7972 (when (and org-link-search-failed (eq this-command last-command))
7973 (goto-char (point-min))
7974 (message "Link search wrapped back to beginning of buffer"))
7975 (setq org-link-search-failed nil)
7976 (let* ((pos (point))
7977 (ct (org-context))
7978 (a (assoc :link ct)))
7979 (if a (goto-char (nth 2 a)))
7980 (if (re-search-forward org-any-link-re nil t)
7981 (progn
7982 (goto-char (match-beginning 0))
7983 (if (org-invisible-p) (org-show-context)))
7984 (goto-char pos)
7985 (setq org-link-search-failed t)
7986 (error "No further link found"))))
7988 (defun org-previous-link ()
7989 "Move backward to the previous link.
7990 If the link is in hidden text, expose it."
7991 (interactive)
7992 (when (and org-link-search-failed (eq this-command last-command))
7993 (goto-char (point-max))
7994 (message "Link search wrapped back to end of buffer"))
7995 (setq org-link-search-failed nil)
7996 (let* ((pos (point))
7997 (ct (org-context))
7998 (a (assoc :link ct)))
7999 (if a (goto-char (nth 1 a)))
8000 (if (re-search-backward org-any-link-re nil t)
8001 (progn
8002 (goto-char (match-beginning 0))
8003 (if (org-invisible-p) (org-show-context)))
8004 (goto-char pos)
8005 (setq org-link-search-failed t)
8006 (error "No further link found"))))
8008 (defun org-translate-link (s)
8009 "Translate a link string if a translation function has been defined."
8010 (if (and org-link-translation-function
8011 (fboundp org-link-translation-function)
8012 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8013 (progn
8014 (setq s (funcall org-link-translation-function
8015 (match-string 1) (match-string 2)))
8016 (concat (car s) ":" (cdr s)))
8019 (defun org-translate-link-from-planner (type path)
8020 "Translate a link from Emacs Planner syntax so that Org can follow it.
8021 This is still an experimental function, your mileage may vary."
8022 (cond
8023 ((member type '("http" "https" "news" "ftp"))
8024 ;; standard Internet links are the same.
8025 nil)
8026 ((and (equal type "irc") (string-match "^//" path))
8027 ;; Planner has two / at the beginning of an irc link, we have 1.
8028 ;; We should have zero, actually....
8029 (setq path (substring path 1)))
8030 ((and (equal type "lisp") (string-match "^/" path))
8031 ;; Planner has a slash, we do not.
8032 (setq type "elisp" path (substring path 1)))
8033 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8034 ;; A typical message link. Planner has the id after the fina slash,
8035 ;; we separate it with a hash mark
8036 (setq path (concat (match-string 1 path) "#"
8037 (org-remove-angle-brackets (match-string 2 path)))))
8039 (cons type path))
8041 (defun org-find-file-at-mouse (ev)
8042 "Open file link or URL at mouse."
8043 (interactive "e")
8044 (mouse-set-point ev)
8045 (org-open-at-point 'in-emacs))
8047 (defun org-open-at-mouse (ev)
8048 "Open file link or URL at mouse."
8049 (interactive "e")
8050 (mouse-set-point ev)
8051 (if (eq major-mode 'org-agenda-mode)
8052 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8053 (org-open-at-point))
8055 (defvar org-window-config-before-follow-link nil
8056 "The window configuration before following a link.
8057 This is saved in case the need arises to restore it.")
8059 (defvar org-open-link-marker (make-marker)
8060 "Marker pointing to the location where `org-open-at-point; was called.")
8062 ;;;###autoload
8063 (defun org-open-at-point-global ()
8064 "Follow a link like Org-mode does.
8065 This command can be called in any mode to follow a link that has
8066 Org-mode syntax."
8067 (interactive)
8068 (org-run-like-in-org-mode 'org-open-at-point))
8070 ;;;###autoload
8071 (defun org-open-link-from-string (s &optional arg reference-buffer)
8072 "Open a link in the string S, as if it was in Org-mode."
8073 (interactive "sLink: \nP")
8074 (let ((reference-buffer (or reference-buffer (current-buffer))))
8075 (with-temp-buffer
8076 (let ((org-inhibit-startup t))
8077 (org-mode)
8078 (insert s)
8079 (goto-char (point-min))
8080 (org-open-at-point arg reference-buffer)))))
8082 (defun org-open-at-point (&optional in-emacs reference-buffer)
8083 "Open link at or after point.
8084 If there is no link at point, this function will search forward up to
8085 the end of the current line.
8086 Normally, files will be opened by an appropriate application. If the
8087 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8088 With a double prefix argument, try to open outside of Emacs, in the
8089 application the system uses for this file type."
8090 (interactive "P")
8091 (org-load-modules-maybe)
8092 (move-marker org-open-link-marker (point))
8093 (setq org-window-config-before-follow-link (current-window-configuration))
8094 (org-remove-occur-highlights nil nil t)
8095 (cond
8096 ((and (org-on-heading-p)
8097 (not (org-in-regexp
8098 (concat org-plain-link-re "\\|"
8099 org-bracket-link-regexp "\\|"
8100 org-angle-link-re "\\|"
8101 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8102 (or (org-offer-links-in-entry in-emacs)
8103 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8104 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8105 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8106 (org-footnote-action))
8108 (let (type path link line search (pos (point)))
8109 (catch 'match
8110 (save-excursion
8111 (skip-chars-forward "^]\n\r")
8112 (when (org-in-regexp org-bracket-link-regexp)
8113 (setq link (org-extract-attributes
8114 (org-link-unescape (org-match-string-no-properties 1))))
8115 (while (string-match " *\n *" link)
8116 (setq link (replace-match " " t t link)))
8117 (setq link (org-link-expand-abbrev link))
8118 (cond
8119 ((or (file-name-absolute-p link)
8120 (string-match "^\\.\\.?/" link))
8121 (setq type "file" path link))
8122 ((string-match org-link-re-with-space3 link)
8123 (setq type (match-string 1 link) path (match-string 2 link)))
8124 (t (setq type "thisfile" path link)))
8125 (throw 'match t)))
8127 (when (get-text-property (point) 'org-linked-text)
8128 (setq type "thisfile"
8129 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8130 (1+ (point)) (point))
8131 path (buffer-substring
8132 (previous-single-property-change pos 'org-linked-text)
8133 (next-single-property-change pos 'org-linked-text)))
8134 (throw 'match t))
8136 (save-excursion
8137 (when (or (org-in-regexp org-angle-link-re)
8138 (org-in-regexp org-plain-link-re))
8139 (setq type (match-string 1) path (match-string 2))
8140 (throw 'match t)))
8141 (save-excursion
8142 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8143 (setq type "tags"
8144 path (match-string 1))
8145 (while (string-match ":" path)
8146 (setq path (replace-match "+" t t path)))
8147 (throw 'match t)))
8148 (when (org-in-regexp "<\\([^><\n]+\\)>")
8149 (setq type "tree-match"
8150 path (match-string 1))
8151 (throw 'match t)))
8152 (unless path
8153 (error "No link found"))
8155 ;; switch back to reference buffer
8156 ;; needed when if called in a temporary buffer through
8157 ;; org-open-link-from-string
8158 (with-current-buffer (or reference-buffer (current-buffer))
8160 ;; Remove any trailing spaces in path
8161 (if (string-match " +\\'" path)
8162 (setq path (replace-match "" t t path)))
8163 (if (and org-link-translation-function
8164 (fboundp org-link-translation-function))
8165 ;; Check if we need to translate the link
8166 (let ((tmp (funcall org-link-translation-function type path)))
8167 (setq type (car tmp) path (cdr tmp))))
8169 (cond
8171 ((assoc type org-link-protocols)
8172 (funcall (nth 1 (assoc type org-link-protocols)) path))
8174 ((equal type "mailto")
8175 (let ((cmd (car org-link-mailto-program))
8176 (args (cdr org-link-mailto-program)) args1
8177 (address path) (subject "") a)
8178 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8179 (setq address (match-string 1 path)
8180 subject (org-link-escape (match-string 2 path))))
8181 (while args
8182 (cond
8183 ((not (stringp (car args))) (push (pop args) args1))
8184 (t (setq a (pop args))
8185 (if (string-match "%a" a)
8186 (setq a (replace-match address t t a)))
8187 (if (string-match "%s" a)
8188 (setq a (replace-match subject t t a)))
8189 (push a args1))))
8190 (apply cmd (nreverse args1))))
8192 ((member type '("http" "https" "ftp" "news"))
8193 (browse-url (concat type ":" (org-link-escape
8194 path org-link-escape-chars-browser))))
8196 ((member type '("message"))
8197 (browse-url (concat type ":" path)))
8199 ((string= type "tags")
8200 (org-tags-view in-emacs path))
8201 ((string= type "thisfile")
8202 (if in-emacs
8203 (switch-to-buffer-other-window
8204 (org-get-buffer-for-internal-link (current-buffer)))
8205 (org-mark-ring-push))
8206 (let ((cmd `(org-link-search
8207 ,path
8208 ,(cond ((equal in-emacs '(4)) 'occur)
8209 ((equal in-emacs '(16)) 'org-occur)
8210 (t nil))
8211 ,pos)))
8212 (condition-case nil (eval cmd)
8213 (error (progn (widen) (eval cmd))))))
8215 ((string= type "tree-match")
8216 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8218 ((string= type "file")
8219 (if (string-match "::\\([0-9]+\\)\\'" path)
8220 (setq line (string-to-number (match-string 1 path))
8221 path (substring path 0 (match-beginning 0)))
8222 (if (string-match "::\\(.+\\)\\'" path)
8223 (setq search (match-string 1 path)
8224 path (substring path 0 (match-beginning 0)))))
8225 (if (string-match "[*?{]" (file-name-nondirectory path))
8226 (dired path)
8227 (org-open-file path in-emacs line search)))
8229 ((string= type "news")
8230 (require 'org-gnus)
8231 (org-gnus-follow-link path))
8233 ((string= type "shell")
8234 (let ((cmd path))
8235 (if (or (not org-confirm-shell-link-function)
8236 (funcall org-confirm-shell-link-function
8237 (format "Execute \"%s\" in shell? "
8238 (org-add-props cmd nil
8239 'face 'org-warning))))
8240 (progn
8241 (message "Executing %s" cmd)
8242 (shell-command cmd))
8243 (error "Abort"))))
8245 ((string= type "elisp")
8246 (let ((cmd path))
8247 (if (or (not org-confirm-elisp-link-function)
8248 (funcall org-confirm-elisp-link-function
8249 (format "Execute \"%s\" as elisp? "
8250 (org-add-props cmd nil
8251 'face 'org-warning))))
8252 (message "%s => %s" cmd
8253 (if (equal (string-to-char cmd) ?\()
8254 (eval (read cmd))
8255 (call-interactively (read cmd))))
8256 (error "Abort"))))
8259 (browse-url-at-point)))))))
8260 (move-marker org-open-link-marker nil)
8261 (run-hook-with-args 'org-follow-link-hook))
8263 (defun org-offer-links-in-entry (&optional nth zero)
8264 "Offer links in the curren entry and follow the selected link.
8265 If there is only one link, follow it immediately as well.
8266 If NTH is an integer, immediately pick the NTH link found.
8267 If ZERO is a string, check also this string for a link, and if
8268 there is one, offer it as link number zero."
8269 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8270 "\\(" org-angle-link-re "\\)\\|"
8271 "\\(" org-plain-link-re "\\)"))
8272 (cnt ?0)
8273 (in-emacs (if (integerp nth) nil nth))
8274 have-zero end links link c)
8275 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8276 (push (match-string 0 zero) links)
8277 (setq cnt (1- cnt) have-zero t))
8278 (save-excursion
8279 (org-back-to-heading t)
8280 (setq end (save-excursion (outline-next-heading) (point)))
8281 (while (re-search-forward re end t)
8282 (push (match-string 0) links))
8283 (setq links (org-uniquify (reverse links))))
8285 (cond
8286 ((null links)
8287 (message "No links"))
8288 ((equal (length links) 1)
8289 (setq link (car links)))
8290 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8291 (setq link (nth (if have-zero nth (1- nth)) links)))
8292 (t ; we have to select a link
8293 (save-excursion
8294 (save-window-excursion
8295 (delete-other-windows)
8296 (with-output-to-temp-buffer "*Select Link*"
8297 (mapc (lambda (l)
8298 (if (not (string-match org-bracket-link-regexp l))
8299 (princ (format "[%c] %s\n" (incf cnt)
8300 (org-remove-angle-brackets l)))
8301 (if (match-end 3)
8302 (princ (format "[%c] %s (%s)\n" (incf cnt)
8303 (match-string 3 l) (match-string 1 l)))
8304 (princ (format "[%c] %s\n" (incf cnt)
8305 (match-string 1 l))))))
8306 links))
8307 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8308 (message "Select link to open:")
8309 (setq c (read-char-exclusive))
8310 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8311 (when (equal c ?q) (error "Abort"))
8312 (setq nth (- c ?0))
8313 (if have-zero (setq nth (1+ nth)))
8314 (unless (and (integerp nth) (>= (length links) nth))
8315 (error "Invalid link selection"))
8316 (setq link (nth (1- nth) links))))
8317 (if link
8318 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8319 nil)))
8321 ;;;; Time estimates
8323 (defun org-get-effort (&optional pom)
8324 "Get the effort estimate for the current entry."
8325 (org-entry-get pom org-effort-property))
8327 ;;; File search
8329 (defvar org-create-file-search-functions nil
8330 "List of functions to construct the right search string for a file link.
8331 These functions are called in turn with point at the location to
8332 which the link should point.
8334 A function in the hook should first test if it would like to
8335 handle this file type, for example by checking the major-mode or
8336 the file extension. If it decides not to handle this file, it
8337 should just return nil to give other functions a chance. If it
8338 does handle the file, it must return the search string to be used
8339 when following the link. The search string will be part of the
8340 file link, given after a double colon, and `org-open-at-point'
8341 will automatically search for it. If special measures must be
8342 taken to make the search successful, another function should be
8343 added to the companion hook `org-execute-file-search-functions',
8344 which see.
8346 A function in this hook may also use `setq' to set the variable
8347 `description' to provide a suggestion for the descriptive text to
8348 be used for this link when it gets inserted into an Org-mode
8349 buffer with \\[org-insert-link].")
8351 (defvar org-execute-file-search-functions nil
8352 "List of functions to execute a file search triggered by a link.
8354 Functions added to this hook must accept a single argument, the
8355 search string that was part of the file link, the part after the
8356 double colon. The function must first check if it would like to
8357 handle this search, for example by checking the major-mode or the
8358 file extension. If it decides not to handle this search, it
8359 should just return nil to give other functions a chance. If it
8360 does handle the search, it must return a non-nil value to keep
8361 other functions from trying.
8363 Each function can access the current prefix argument through the
8364 variable `current-prefix-argument'. Note that a single prefix is
8365 used to force opening a link in Emacs, so it may be good to only
8366 use a numeric or double prefix to guide the search function.
8368 In case this is needed, a function in this hook can also restore
8369 the window configuration before `org-open-at-point' was called using:
8371 (set-window-configuration org-window-config-before-follow-link)")
8373 (defun org-link-search (s &optional type avoid-pos)
8374 "Search for a link search option.
8375 If S is surrounded by forward slashes, it is interpreted as a
8376 regular expression. In org-mode files, this will create an `org-occur'
8377 sparse tree. In ordinary files, `occur' will be used to list matches.
8378 If the current buffer is in `dired-mode', grep will be used to search
8379 in all files. If AVOID-POS is given, ignore matches near that position."
8380 (let ((case-fold-search t)
8381 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8382 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8383 (append '(("") (" ") ("\t") ("\n"))
8384 org-emphasis-alist)
8385 "\\|") "\\)"))
8386 (pos (point))
8387 (pre nil) (post nil)
8388 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8389 (cond
8390 ;; First check if there are any special
8391 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8392 ;; Now try the builtin stuff
8393 ((and (equal (string-to-char s0) ?#)
8394 (> (length s0) 1)
8395 (save-excursion
8396 (goto-char (point-min))
8397 (and
8398 (re-search-forward
8399 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8400 (setq type 'dedicated
8401 pos (match-beginning 0))))
8402 ;; There is an exact target for this
8403 (goto-char pos)
8404 (org-back-to-heading t)))
8405 ((save-excursion
8406 (goto-char (point-min))
8407 (and
8408 (re-search-forward
8409 (concat "<<" (regexp-quote s0) ">>") nil t)
8410 (setq type 'dedicated
8411 pos (match-beginning 0))))
8412 ;; There is an exact target for this
8413 (goto-char pos))
8414 ((and (string-match "^(\\(.*\\))$" s0)
8415 (save-excursion
8416 (goto-char (point-min))
8417 (and
8418 (re-search-forward
8419 (concat "[^[]" (regexp-quote
8420 (format org-coderef-label-format
8421 (match-string 1 s0))))
8422 nil t)
8423 (setq type 'dedicated
8424 pos (1+ (match-beginning 0))))))
8425 ;; There is a coderef target for this
8426 (goto-char pos))
8427 ((string-match "^/\\(.*\\)/$" s)
8428 ;; A regular expression
8429 (cond
8430 ((org-mode-p)
8431 (org-occur (match-string 1 s)))
8432 ;;((eq major-mode 'dired-mode)
8433 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8434 (t (org-do-occur (match-string 1 s)))))
8436 ;; A normal search strings
8437 (when (equal (string-to-char s) ?*)
8438 ;; Anchor on headlines, post may include tags.
8439 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8440 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8441 s (substring s 1)))
8442 (remove-text-properties
8443 0 (length s)
8444 '(face nil mouse-face nil keymap nil fontified nil) s)
8445 ;; Make a series of regular expressions to find a match
8446 (setq words (org-split-string s "[ \n\r\t]+")
8448 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8449 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8450 "\\)" markers)
8451 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8452 re2a (concat "[ \t\r\n]" re2a_)
8453 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8454 re4 (concat "[^a-zA-Z_]" re4_)
8456 re1 (concat pre re2 post)
8457 re3 (concat pre (if pre re4_ re4) post)
8458 re5 (concat pre ".*" re4)
8459 re2 (concat pre re2)
8460 re2a (concat pre (if pre re2a_ re2a))
8461 re4 (concat pre (if pre re4_ re4))
8462 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8463 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8464 re5 "\\)"
8466 (cond
8467 ((eq type 'org-occur) (org-occur reall))
8468 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8469 (t (goto-char (point-min))
8470 (setq type 'fuzzy)
8471 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8472 (org-search-not-self 1 re1 nil t)
8473 (org-search-not-self 1 re2 nil t)
8474 (org-search-not-self 1 re2a nil t)
8475 (org-search-not-self 1 re3 nil t)
8476 (org-search-not-self 1 re4 nil t)
8477 (org-search-not-self 1 re5 nil t)
8479 (goto-char (match-beginning 1))
8480 (goto-char pos)
8481 (error "No match")))))
8483 ;; Normal string-search
8484 (goto-char (point-min))
8485 (if (search-forward s nil t)
8486 (goto-char (match-beginning 0))
8487 (error "No match"))))
8488 (and (org-mode-p) (org-show-context 'link-search))
8489 type))
8491 (defun org-search-not-self (group &rest args)
8492 "Execute `re-search-forward', but only accept matches that do not
8493 enclose the position of `org-open-link-marker'."
8494 (let ((m org-open-link-marker))
8495 (catch 'exit
8496 (while (apply 're-search-forward args)
8497 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8498 (goto-char (match-end group))
8499 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8500 (> (match-beginning 0) (marker-position m))
8501 (< (match-end 0) (marker-position m)))
8502 (save-match-data
8503 (or (not (org-in-regexp
8504 org-bracket-link-analytic-regexp 1))
8505 (not (match-end 4)) ; no description
8506 (and (<= (match-beginning 4) (point))
8507 (>= (match-end 4) (point))))))
8508 (throw 'exit (point))))))))
8510 (defun org-get-buffer-for-internal-link (buffer)
8511 "Return a buffer to be used for displaying the link target of internal links."
8512 (cond
8513 ((not org-display-internal-link-with-indirect-buffer)
8514 buffer)
8515 ((string-match "(Clone)$" (buffer-name buffer))
8516 (message "Buffer is already a clone, not making another one")
8517 ;; we also do not modify visibility in this case
8518 buffer)
8519 (t ; make a new indirect buffer for displaying the link
8520 (let* ((bn (buffer-name buffer))
8521 (ibn (concat bn "(Clone)"))
8522 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8523 (with-current-buffer ib (org-overview))
8524 ib))))
8526 (defun org-do-occur (regexp &optional cleanup)
8527 "Call the Emacs command `occur'.
8528 If CLEANUP is non-nil, remove the printout of the regular expression
8529 in the *Occur* buffer. This is useful if the regex is long and not useful
8530 to read."
8531 (occur regexp)
8532 (when cleanup
8533 (let ((cwin (selected-window)) win beg end)
8534 (when (setq win (get-buffer-window "*Occur*"))
8535 (select-window win))
8536 (goto-char (point-min))
8537 (when (re-search-forward "match[a-z]+" nil t)
8538 (setq beg (match-end 0))
8539 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8540 (setq end (1- (match-beginning 0)))))
8541 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8542 (goto-char (point-min))
8543 (select-window cwin))))
8545 ;;; The mark ring for links jumps
8547 (defvar org-mark-ring nil
8548 "Mark ring for positions before jumps in Org-mode.")
8549 (defvar org-mark-ring-last-goto nil
8550 "Last position in the mark ring used to go back.")
8551 ;; Fill and close the ring
8552 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8553 (loop for i from 1 to org-mark-ring-length do
8554 (push (make-marker) org-mark-ring))
8555 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8556 org-mark-ring)
8558 (defun org-mark-ring-push (&optional pos buffer)
8559 "Put the current position or POS into the mark ring and rotate it."
8560 (interactive)
8561 (setq pos (or pos (point)))
8562 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8563 (move-marker (car org-mark-ring)
8564 (or pos (point))
8565 (or buffer (current-buffer)))
8566 (message "%s"
8567 (substitute-command-keys
8568 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8570 (defun org-mark-ring-goto (&optional n)
8571 "Jump to the previous position in the mark ring.
8572 With prefix arg N, jump back that many stored positions. When
8573 called several times in succession, walk through the entire ring.
8574 Org-mode commands jumping to a different position in the current file,
8575 or to another Org-mode file, automatically push the old position
8576 onto the ring."
8577 (interactive "p")
8578 (let (p m)
8579 (if (eq last-command this-command)
8580 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8581 (setq p org-mark-ring))
8582 (setq org-mark-ring-last-goto p)
8583 (setq m (car p))
8584 (switch-to-buffer (marker-buffer m))
8585 (goto-char m)
8586 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8588 (defun org-remove-angle-brackets (s)
8589 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8590 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8592 (defun org-add-angle-brackets (s)
8593 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8594 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8596 (defun org-remove-double-quotes (s)
8597 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8598 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8601 ;;; Following specific links
8603 (defun org-follow-timestamp-link ()
8604 (cond
8605 ((org-at-date-range-p t)
8606 (let ((org-agenda-start-on-weekday)
8607 (t1 (match-string 1))
8608 (t2 (match-string 2)))
8609 (setq t1 (time-to-days (org-time-string-to-time t1))
8610 t2 (time-to-days (org-time-string-to-time t2)))
8611 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8612 ((org-at-timestamp-p t)
8613 (org-agenda-list nil (time-to-days (org-time-string-to-time
8614 (substring (match-string 1) 0 10)))
8616 (t (error "This should not happen"))))
8619 ;;; Following file links
8620 (defvar org-wait nil)
8621 (defun org-open-file (path &optional in-emacs line search)
8622 "Open the file at PATH.
8623 First, this expands any special file name abbreviations. Then the
8624 configuration variable `org-file-apps' is checked if it contains an
8625 entry for this file type, and if yes, the corresponding command is launched.
8627 If no application is found, Emacs simply visits the file.
8629 With optional prefix argument IN-EMACS, Emacs will visit the file.
8630 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8631 and o use an external application to visit the file.
8633 Optional LINE specifies a line to go to, optional SEARCH a string to
8634 search for. If LINE or SEARCH is given, the file will always be
8635 opened in Emacs.
8636 If the file does not exist, an error is thrown."
8637 (setq in-emacs (or in-emacs line search))
8638 (let* ((file (if (equal path "")
8639 buffer-file-name
8640 (substitute-in-file-name (expand-file-name path))))
8641 (apps (append org-file-apps (org-default-apps)))
8642 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8643 (dirp (if remp nil (file-directory-p file)))
8644 (file (if (and dirp org-open-directory-means-index-dot-org)
8645 (concat (file-name-as-directory file) "index.org")
8646 file))
8647 (a-m-a-p (assq 'auto-mode apps))
8648 (dfile (downcase file))
8649 (old-buffer (current-buffer))
8650 (old-pos (point))
8651 (old-mode major-mode)
8652 ext cmd)
8653 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8654 (setq ext (match-string 1 dfile))
8655 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8656 (setq ext (match-string 1 dfile))))
8657 (cond
8658 ((equal in-emacs '(16))
8659 (setq cmd (cdr (assoc 'system apps))))
8660 (in-emacs (setq cmd 'emacs))
8662 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8663 (and dirp (cdr (assoc 'directory apps)))
8664 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8665 'string-match)
8666 (cdr (assoc ext apps))
8667 (cdr (assoc t apps))))))
8668 (when (eq cmd 'system)
8669 (setq cmd (cdr (assoc 'system apps))))
8670 (when (eq cmd 'default)
8671 (setq cmd (cdr (assoc t apps))))
8672 (when (eq cmd 'mailcap)
8673 (require 'mailcap)
8674 (mailcap-parse-mailcaps)
8675 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8676 (command (mailcap-mime-info mime-type)))
8677 (if (stringp command)
8678 (setq cmd command)
8679 (setq cmd 'emacs))))
8680 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8681 (not (file-exists-p file))
8682 (not org-open-non-existing-files))
8683 (error "No such file: %s" file))
8684 (cond
8685 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8686 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8687 (while (string-match "['\"]%s['\"]" cmd)
8688 (setq cmd (replace-match "%s" t t cmd)))
8689 (while (string-match "%s" cmd)
8690 (setq cmd (replace-match
8691 (save-match-data
8692 (shell-quote-argument
8693 (convert-standard-filename file)))
8694 t t cmd)))
8695 (save-window-excursion
8696 (start-process-shell-command cmd nil cmd)
8697 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8699 ((or (stringp cmd)
8700 (eq cmd 'emacs))
8701 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8702 (widen)
8703 (if line (org-goto-line line)
8704 (if search (org-link-search search))))
8705 ((consp cmd)
8706 (let ((file (convert-standard-filename file)))
8707 (eval cmd)))
8708 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8709 (and (org-mode-p) (eq old-mode 'org-mode)
8710 (or (not (equal old-buffer (current-buffer)))
8711 (not (equal old-pos (point))))
8712 (org-mark-ring-push old-pos old-buffer))))
8714 (defun org-default-apps ()
8715 "Return the default applications for this operating system."
8716 (cond
8717 ((eq system-type 'darwin)
8718 org-file-apps-defaults-macosx)
8719 ((eq system-type 'windows-nt)
8720 org-file-apps-defaults-windowsnt)
8721 (t org-file-apps-defaults-gnu)))
8723 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8724 "Convert extensions to regular expressions in the cars of LIST.
8725 Also, weed out any non-string entries, because the return value is used
8726 only for regexp matching.
8727 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8728 point to the symbol `emacs', indicating that the file should
8729 be opened in Emacs."
8730 (append
8731 (delq nil
8732 (mapcar (lambda (x)
8733 (if (not (stringp (car x)))
8735 (if (string-match "\\W" (car x))
8737 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8738 list))
8739 (if add-auto-mode
8740 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8742 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8743 (defun org-file-remote-p (file)
8744 "Test whether FILE specifies a location on a remote system.
8745 Return non-nil if the location is indeed remote.
8747 For example, the filename \"/user@host:/foo\" specifies a location
8748 on the system \"/user@host:\"."
8749 (cond ((fboundp 'file-remote-p)
8750 (file-remote-p file))
8751 ((fboundp 'tramp-handle-file-remote-p)
8752 (tramp-handle-file-remote-p file))
8753 ((and (boundp 'ange-ftp-name-format)
8754 (string-match (car ange-ftp-name-format) file))
8756 (t nil)))
8759 ;;;; Refiling
8761 (defun org-get-org-file ()
8762 "Read a filename, with default directory `org-directory'."
8763 (let ((default (or org-default-notes-file remember-data-file)))
8764 (read-file-name (format "File name [%s]: " default)
8765 (file-name-as-directory org-directory)
8766 default)))
8768 (defun org-notes-order-reversed-p ()
8769 "Check if the current file should receive notes in reversed order."
8770 (cond
8771 ((not org-reverse-note-order) nil)
8772 ((eq t org-reverse-note-order) t)
8773 ((not (listp org-reverse-note-order)) nil)
8774 (t (catch 'exit
8775 (let ((all org-reverse-note-order)
8776 entry)
8777 (while (setq entry (pop all))
8778 (if (string-match (car entry) buffer-file-name)
8779 (throw 'exit (cdr entry))))
8780 nil)))))
8782 (defvar org-refile-target-table nil
8783 "The list of refile targets, created by `org-refile'.")
8785 (defvar org-agenda-new-buffers nil
8786 "Buffers created to visit agenda files.")
8788 (defun org-get-refile-targets (&optional default-buffer)
8789 "Produce a table with refile targets."
8790 (let ((case-fold-search nil)
8791 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8792 (entries (or org-refile-targets '((nil . (:level . 1)))))
8793 targets txt re files f desc descre fast-path-p level pos0)
8794 (message "Getting targets...")
8795 (with-current-buffer (or default-buffer (current-buffer))
8796 (while (setq entry (pop entries))
8797 (setq files (car entry) desc (cdr entry))
8798 (setq fast-path-p nil)
8799 (cond
8800 ((null files) (setq files (list (current-buffer))))
8801 ((eq files 'org-agenda-files)
8802 (setq files (org-agenda-files 'unrestricted)))
8803 ((and (symbolp files) (fboundp files))
8804 (setq files (funcall files)))
8805 ((and (symbolp files) (boundp files))
8806 (setq files (symbol-value files))))
8807 (if (stringp files) (setq files (list files)))
8808 (cond
8809 ((eq (car desc) :tag)
8810 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8811 ((eq (car desc) :todo)
8812 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8813 ((eq (car desc) :regexp)
8814 (setq descre (cdr desc)))
8815 ((eq (car desc) :level)
8816 (setq descre (concat "^\\*\\{" (number-to-string
8817 (if org-odd-levels-only
8818 (1- (* 2 (cdr desc)))
8819 (cdr desc)))
8820 "\\}[ \t]")))
8821 ((eq (car desc) :maxlevel)
8822 (setq fast-path-p t)
8823 (setq descre (concat "^\\*\\{1," (number-to-string
8824 (if org-odd-levels-only
8825 (1- (* 2 (cdr desc)))
8826 (cdr desc)))
8827 "\\}[ \t]")))
8828 (t (error "Bad refiling target description %s" desc)))
8829 (while (setq f (pop files))
8830 (save-excursion
8831 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8832 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8833 (setq f (expand-file-name f))
8834 (if (eq org-refile-use-outline-path 'file)
8835 (push (list (file-name-nondirectory f) f nil nil) targets))
8836 (save-excursion
8837 (save-restriction
8838 (widen)
8839 (goto-char (point-min))
8840 (while (re-search-forward descre nil t)
8841 (goto-char (setq pos0 (point-at-bol)))
8842 (catch 'next
8843 (when org-refile-target-verify-function
8844 (save-match-data
8845 (or (funcall org-refile-target-verify-function)
8846 (throw 'next t))))
8847 (when (looking-at org-complex-heading-regexp)
8848 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8849 txt (org-link-display-format (match-string 4))
8850 re (concat "^" (regexp-quote
8851 (buffer-substring (match-beginning 1)
8852 (match-end 4)))))
8853 (if (match-end 5) (setq re (concat re "[ \t]+"
8854 (regexp-quote
8855 (match-string 5)))))
8856 (setq re (concat re "[ \t]*$"))
8857 (when org-refile-use-outline-path
8858 (setq txt (mapconcat 'org-protect-slash
8859 (append
8860 (if (eq org-refile-use-outline-path 'file)
8861 (list (file-name-nondirectory
8862 (buffer-file-name (buffer-base-buffer))))
8863 (if (eq org-refile-use-outline-path 'full-file-path)
8864 (list (buffer-file-name (buffer-base-buffer)))))
8865 (org-get-outline-path fast-path-p level txt)
8866 (list txt))
8867 "/")))
8868 (push (list txt f re (point)) targets)))
8869 (when (= (point) pos0)
8870 ;; verification function has not moved point
8871 (goto-char (point-at-eol))))))))))
8872 (message "Getting targets...done")
8873 (nreverse targets)))
8875 (defun org-protect-slash (s)
8876 (while (string-match "/" s)
8877 (setq s (replace-match "\\" t t s)))
8880 (defvar org-olpa (make-vector 20 nil))
8882 (defun org-get-outline-path (&optional fastp level heading)
8883 "Return the outline path to the current entry, as a list."
8884 (if fastp
8885 (progn
8886 (if (> level 19)
8887 (error "Outline path failure, more than 19 levels."))
8888 (loop for i from level upto 19 do
8889 (aset org-olpa i nil))
8890 (prog1
8891 (delq nil (append org-olpa nil))
8892 (aset org-olpa level heading)))
8893 (let (rtn)
8894 (save-excursion
8895 (while (org-up-heading-safe)
8896 (when (looking-at org-complex-heading-regexp)
8897 (push (org-match-string-no-properties 4) rtn)))
8898 rtn))))
8900 (defvar org-refile-history nil
8901 "History for refiling operations.")
8903 (defvar org-after-refile-insert-hook nil
8904 "Hook run after `org-refile' has inserted its stuff at the new location.
8905 Note that this is still *before* the stuff will be removed from
8906 the *old* location.")
8908 (defun org-refile (&optional goto default-buffer rfloc)
8909 "Move the entry at point to another heading.
8910 The list of target headings is compiled using the information in
8911 `org-refile-targets', which see. This list is created before each use
8912 and will therefore always be up-to-date.
8914 At the target location, the entry is filed as a subitem of the target heading.
8915 Depending on `org-reverse-note-order', the new subitem will either be the
8916 first or the last subitem.
8918 If there is an active region, all entries in that region will be moved.
8919 However, the region must fulfil the requirement that the first heading
8920 is the first one sets the top-level of the moved text - at most siblings
8921 below it are allowed.
8923 With prefix arg GOTO, the command will only visit the target location,
8924 not actually move anything.
8925 With a double prefix `C-u C-u', go to the location where the last refiling
8926 operation has put the subtree.
8927 With a prefix argument of `2', refile to the running clock.
8929 RFLOC can be a refile location obtained in a different way.
8931 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8932 (interactive "P")
8933 (let* ((cbuf (current-buffer))
8934 (regionp (org-region-active-p))
8935 (region-start (and regionp (region-beginning)))
8936 (region-end (and regionp (region-end)))
8937 (region-length (and regionp (- region-end region-start)))
8938 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8939 pos it nbuf file re level reversed)
8940 (when regionp
8941 (goto-char region-start)
8942 (or (bolp) (goto-char (point-at-bol)))
8943 (setq region-start (point))
8944 (unless (org-kill-is-subtree-p
8945 (buffer-substring region-start region-end))
8946 (error "The region is not a (sequence of) subtree(s)")))
8947 (if (equal goto '(16))
8948 (org-refile-goto-last-stored)
8949 (when (or
8950 (and org-clock-hd-marker (marker-buffer org-clock-hd-marker)
8951 (prog1
8952 (setq it (list (or org-clock-heading "running clock")
8953 (buffer-file-name
8954 (marker-buffer org-clock-hd-marker))
8956 (marker-position org-clock-hd-marker)))
8957 (setq goto nil)))
8958 (setq it (or rfloc
8959 (save-excursion
8960 (org-refile-get-location
8961 (if goto "Goto: " "Refile to: ") default-buffer
8962 org-refile-allow-creating-parent-nodes)))))
8963 (setq file (nth 1 it)
8964 re (nth 2 it)
8965 pos (nth 3 it))
8966 (if (and (not goto)
8968 (equal (buffer-file-name) file)
8969 (if regionp
8970 (and (>= pos region-start)
8971 (<= pos region-end))
8972 (and (>= pos (point))
8973 (< pos (save-excursion
8974 (org-end-of-subtree t t))))))
8975 (error "Cannot refile to position inside the tree or region"))
8977 (setq nbuf (or (find-buffer-visiting file)
8978 (find-file-noselect file)))
8979 (if goto
8980 (progn
8981 (switch-to-buffer nbuf)
8982 (goto-char pos)
8983 (org-show-context 'org-goto))
8984 (if regionp
8985 (progn
8986 (org-kill-new (buffer-substring region-start region-end))
8987 (org-save-markers-in-region region-start region-end))
8988 (org-copy-subtree 1 nil t))
8989 (save-excursion
8990 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8991 (find-file-noselect file))))
8992 (setq reversed (org-notes-order-reversed-p))
8993 (save-excursion
8994 (save-restriction
8995 (widen)
8996 (if pos
8997 (progn
8998 (goto-char pos)
8999 (looking-at outline-regexp)
9000 (setq level (org-get-valid-level (funcall outline-level) 1))
9001 (goto-char
9002 (if reversed
9003 (or (outline-next-heading) (point-max))
9004 (or (save-excursion (org-get-next-sibling))
9005 (org-end-of-subtree t t)
9006 (point-max)))))
9007 (setq level 1)
9008 (if (not reversed)
9009 (goto-char (point-max))
9010 (goto-char (point-min))
9011 (or (outline-next-heading) (goto-char (point-max)))))
9012 (if (not (bolp)) (newline))
9013 (bookmark-set "org-refile-last-stored")
9014 (org-paste-subtree level)
9015 (if (fboundp 'deactivate-mark) (deactivate-mark))
9016 (run-hooks 'org-after-refile-insert-hook))))
9017 (if regionp
9018 (delete-region (point) (+ (point) region-length))
9019 (org-cut-subtree))
9020 (when (featurep 'org-inlinetask)
9021 (org-inlinetask-remove-END-maybe))
9022 (setq org-markers-to-move nil)
9023 (message "Refiled to \"%s\"" (car it))))))
9024 (org-reveal))
9026 (defun org-refile-goto-last-stored ()
9027 "Go to the location where the last refile was stored."
9028 (interactive)
9029 (bookmark-jump "org-refile-last-stored")
9030 (message "This is the location of the last refile"))
9032 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9033 "Prompt the user for a refile location, using PROMPT."
9034 (let ((org-refile-targets org-refile-targets)
9035 (org-refile-use-outline-path org-refile-use-outline-path))
9036 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9037 (unless org-refile-target-table
9038 (error "No refile targets"))
9039 (let* ((cbuf (current-buffer))
9040 (partial-completion-mode nil)
9041 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9042 (cfunc (if (and org-refile-use-outline-path
9043 org-outline-path-complete-in-steps)
9044 'org-olpath-completing-read
9045 'org-icompleting-read))
9046 (extra (if org-refile-use-outline-path "/" ""))
9047 (filename (and cfn (expand-file-name cfn)))
9048 (tbl (mapcar
9049 (lambda (x)
9050 (if (and (not (member org-refile-use-outline-path
9051 '(file full-file-path)))
9052 (not (equal filename (nth 1 x))))
9053 (cons (concat (car x) extra " ("
9054 (file-name-nondirectory (nth 1 x)) ")")
9055 (cdr x))
9056 (cons (concat (car x) extra) (cdr x))))
9057 org-refile-target-table))
9058 (completion-ignore-case t)
9059 pa answ parent-target child parent old-hist)
9060 (setq old-hist org-refile-history)
9061 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9062 nil 'org-refile-history))
9063 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9064 (if pa
9065 (progn
9066 (when (or (not org-refile-history)
9067 (not (eq old-hist org-refile-history))
9068 (not (equal (car pa) (car org-refile-history))))
9069 (setq org-refile-history
9070 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9071 org-refile-history
9072 (cdr org-refile-history))))
9073 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9074 (pop org-refile-history)))
9076 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9077 (setq parent (match-string 1 answ)
9078 child (match-string 2 answ))
9079 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9080 (when (and parent-target
9081 (or (eq new-nodes t)
9082 (and (eq new-nodes 'confirm)
9083 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9084 (org-refile-new-child parent-target child))))))
9086 (defun org-refile-new-child (parent-target child)
9087 "Use refile target PARENT-TARGET to add new CHILD below it."
9088 (unless parent-target
9089 (error "Cannot find parent for new node"))
9090 (let ((file (nth 1 parent-target))
9091 (pos (nth 3 parent-target))
9092 level)
9093 (with-current-buffer (or (find-buffer-visiting file)
9094 (find-file-noselect file))
9095 (save-excursion
9096 (save-restriction
9097 (widen)
9098 (if pos
9099 (goto-char pos)
9100 (goto-char (point-max))
9101 (if (not (bolp)) (newline)))
9102 (when (looking-at outline-regexp)
9103 (setq level (funcall outline-level))
9104 (org-end-of-subtree t t))
9105 (org-back-over-empty-lines)
9106 (insert "\n" (make-string
9107 (if pos (org-get-valid-level level 1) 1) ?*)
9108 " " child "\n")
9109 (beginning-of-line 0)
9110 (list (concat (car parent-target) "/" child) file "" (point)))))))
9112 (defun org-olpath-completing-read (prompt collection &rest args)
9113 "Read an outline path like a file name."
9114 (let ((thetable collection)
9115 (org-completion-use-ido nil) ; does not work with ido.
9116 (org-completion-use-iswitchb nil)) ; or iswitchb
9117 (apply
9118 'org-icompleting-read prompt
9119 (lambda (string predicate &optional flag)
9120 (let (rtn r f (l (length string)))
9121 (cond
9122 ((eq flag nil)
9123 ;; try completion
9124 (try-completion string thetable))
9125 ((eq flag t)
9126 ;; all-completions
9127 (setq rtn (all-completions string thetable predicate))
9128 (mapcar
9129 (lambda (x)
9130 (setq r (substring x l))
9131 (if (string-match " ([^)]*)$" x)
9132 (setq f (match-string 0 x))
9133 (setq f ""))
9134 (if (string-match "/" r)
9135 (concat string (substring r 0 (match-end 0)) f)
9137 rtn))
9138 ((eq flag 'lambda)
9139 ;; exact match?
9140 (assoc string thetable)))
9142 args)))
9144 ;;;; Dynamic blocks
9146 (defun org-find-dblock (name)
9147 "Find the first dynamic block with name NAME in the buffer.
9148 If not found, stay at current position and return nil."
9149 (let (pos)
9150 (save-excursion
9151 (goto-char (point-min))
9152 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9153 nil t)
9154 (match-beginning 0))))
9155 (if pos (goto-char pos))
9156 pos))
9158 (defconst org-dblock-start-re
9159 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9160 "Matches the startline of a dynamic block, with parameters.")
9162 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9163 "Matches the end of a dynamic block.")
9165 (defun org-create-dblock (plist)
9166 "Create a dynamic block section, with parameters taken from PLIST.
9167 PLIST must contain a :name entry which is used as name of the block."
9168 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9169 (end-of-line 1)
9170 (newline))
9171 (let ((col (current-column))
9172 (name (plist-get plist :name)))
9173 (insert "#+BEGIN: " name)
9174 (while plist
9175 (if (eq (car plist) :name)
9176 (setq plist (cddr plist))
9177 (insert " " (prin1-to-string (pop plist)))))
9178 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9179 (beginning-of-line -2)))
9181 (defun org-prepare-dblock ()
9182 "Prepare dynamic block for refresh.
9183 This empties the block, puts the cursor at the insert position and returns
9184 the property list including an extra property :name with the block name."
9185 (unless (looking-at org-dblock-start-re)
9186 (error "Not at a dynamic block"))
9187 (let* ((begdel (1+ (match-end 0)))
9188 (name (org-no-properties (match-string 1)))
9189 (params (append (list :name name)
9190 (read (concat "(" (match-string 3) ")")))))
9191 (save-excursion
9192 (beginning-of-line 1)
9193 (skip-chars-forward " \t")
9194 (setq params (plist-put params :indentation-column (current-column))))
9195 (unless (re-search-forward org-dblock-end-re nil t)
9196 (error "Dynamic block not terminated"))
9197 (setq params
9198 (append params
9199 (list :content (buffer-substring
9200 begdel (match-beginning 0)))))
9201 (delete-region begdel (match-beginning 0))
9202 (goto-char begdel)
9203 (open-line 1)
9204 params))
9206 (defun org-map-dblocks (&optional command)
9207 "Apply COMMAND to all dynamic blocks in the current buffer.
9208 If COMMAND is not given, use `org-update-dblock'."
9209 (let ((cmd (or command 'org-update-dblock))
9210 pos)
9211 (save-excursion
9212 (goto-char (point-min))
9213 (while (re-search-forward org-dblock-start-re nil t)
9214 (goto-char (setq pos (match-beginning 0)))
9215 (condition-case nil
9216 (funcall cmd)
9217 (error (message "Error during update of dynamic block")))
9218 (goto-char pos)
9219 (unless (re-search-forward org-dblock-end-re nil t)
9220 (error "Dynamic block not terminated"))))))
9222 (defun org-dblock-update (&optional arg)
9223 "User command for updating dynamic blocks.
9224 Update the dynamic block at point. With prefix ARG, update all dynamic
9225 blocks in the buffer."
9226 (interactive "P")
9227 (if arg
9228 (org-update-all-dblocks)
9229 (or (looking-at org-dblock-start-re)
9230 (org-beginning-of-dblock))
9231 (org-update-dblock)))
9233 (defun org-update-dblock ()
9234 "Update the dynamic block at point
9235 This means to empty the block, parse for parameters and then call
9236 the correct writing function."
9237 (save-window-excursion
9238 (let* ((pos (point))
9239 (line (org-current-line))
9240 (params (org-prepare-dblock))
9241 (name (plist-get params :name))
9242 (indent (plist-get params :indentation-column))
9243 (cmd (intern (concat "org-dblock-write:" name))))
9244 (message "Updating dynamic block `%s' at line %d..." name line)
9245 (funcall cmd params)
9246 (message "Updating dynamic block `%s' at line %d...done" name line)
9247 (goto-char pos)
9248 (when (and indent (> indent 0))
9249 (setq indent (make-string indent ?\ ))
9250 (save-excursion
9251 (org-beginning-of-dblock)
9252 (forward-line 1)
9253 (while (not (looking-at org-dblock-end-re))
9254 (insert indent)
9255 (beginning-of-line 2))
9256 (when (looking-at org-dblock-end-re)
9257 (and (looking-at "[ \t]+")
9258 (replace-match ""))
9259 (insert indent)))))))
9261 (defun org-beginning-of-dblock ()
9262 "Find the beginning of the dynamic block at point.
9263 Error if there is no such block at point."
9264 (let ((pos (point))
9265 beg)
9266 (end-of-line 1)
9267 (if (and (re-search-backward org-dblock-start-re nil t)
9268 (setq beg (match-beginning 0))
9269 (re-search-forward org-dblock-end-re nil t)
9270 (> (match-end 0) pos))
9271 (goto-char beg)
9272 (goto-char pos)
9273 (error "Not in a dynamic block"))))
9275 (defun org-update-all-dblocks ()
9276 "Update all dynamic blocks in the buffer.
9277 This function can be used in a hook."
9278 (when (org-mode-p)
9279 (org-map-dblocks 'org-update-dblock)))
9282 ;;;; Completion
9284 (defconst org-additional-option-like-keywords
9285 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9286 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9287 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "LATEX_CLASS:" "ATTR_LaTeX"
9288 "BEGIN:" "END:"
9289 "ORGTBL" "TBLFM:" "TBLNAME:"
9290 "BEGIN_EXAMPLE" "END_EXAMPLE"
9291 "BEGIN_QUOTE" "END_QUOTE"
9292 "BEGIN_VERSE" "END_VERSE"
9293 "BEGIN_CENTER" "END_CENTER"
9294 "BEGIN_SRC" "END_SRC"
9295 "CATEGORY" "COLUMNS"
9296 "CAPTION" "LABEL"
9297 "SETUPFILE"
9298 "BIND"
9299 "MACRO"))
9301 (defcustom org-structure-template-alist
9303 ("s" "#+begin_src ?\n\n#+end_src"
9304 "<src lang=\"?\">\n\n</src>")
9305 ("e" "#+begin_example\n?\n#+end_example"
9306 "<example>\n?\n</example>")
9307 ("q" "#+begin_quote\n?\n#+end_quote"
9308 "<quote>\n?\n</quote>")
9309 ("v" "#+begin_verse\n?\n#+end_verse"
9310 "<verse>\n?\n/verse>")
9311 ("c" "#+begin_center\n?\n#+end_center"
9312 "<center>\n?\n/center>")
9313 ("l" "#+begin_latex\n?\n#+end_latex"
9314 "<literal style=\"latex\">\n?\n</literal>")
9315 ("L" "#+latex: "
9316 "<literal style=\"latex\">?</literal>")
9317 ("h" "#+begin_html\n?\n#+end_html"
9318 "<literal style=\"html\">\n?\n</literal>")
9319 ("H" "#+html: "
9320 "<literal style=\"html\">?</literal>")
9321 ("a" "#+begin_ascii\n?\n#+end_ascii")
9322 ("A" "#+ascii: ")
9323 ("i" "#+include %file ?"
9324 "<include file=%file markup=\"?\">")
9326 "Structure completion elements.
9327 This is a list of abbreviation keys and values. The value gets inserted
9328 it you type @samp{.} followed by the key and then the completion key,
9329 usually `M-TAB'. %file will be replaced by a file name after prompting
9330 for the file using completion.
9331 There are two templates for each key, the first uses the original Org syntax,
9332 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9333 the default when the /org-mtags.el/ module has been loaded. See also the
9334 variable `org-mtags-prefer-muse-templates'.
9335 This is an experimental feature, it is undecided if it is going to stay in."
9336 :group 'org-completion
9337 :type '(repeat
9338 (string :tag "Key")
9339 (string :tag "Template")
9340 (string :tag "Muse Template")))
9342 (defun org-try-structure-completion ()
9343 "Try to complete a structure template before point.
9344 This looks for strings like \"<e\" on an otherwise empty line and
9345 expands them."
9346 (let ((l (buffer-substring (point-at-bol) (point)))
9348 (when (and (looking-at "[ \t]*$")
9349 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9350 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9351 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9352 (match-beginning 1)) a)
9353 t)))
9355 (defun org-complete-expand-structure-template (start cell)
9356 "Expand a structure template."
9357 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9358 (rpl (nth (if musep 2 1) cell))
9359 (ind ""))
9360 (delete-region start (point))
9361 (when (string-match "\\`#\\+" rpl)
9362 (cond
9363 ((bolp))
9364 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9365 (setq ind (buffer-substring (point-at-bol) (point))))
9366 (t (newline))))
9367 (setq start (point))
9368 (if (string-match "%file" rpl)
9369 (setq rpl (replace-match
9370 (concat
9371 "\""
9372 (save-match-data
9373 (abbreviate-file-name (read-file-name "Include file: ")))
9374 "\"")
9375 t t rpl)))
9376 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9377 (concat "\n" ind)))
9378 (insert rpl)
9379 (if (re-search-backward "\\?" start t) (delete-char 1))))
9382 (defun org-complete (&optional arg)
9383 "Perform completion on word at point.
9384 At the beginning of a headline, this completes TODO keywords as given in
9385 `org-todo-keywords'.
9386 If the current word is preceded by a backslash, completes the TeX symbols
9387 that are supported for HTML support.
9388 If the current word is preceded by \"#+\", completes special words for
9389 setting file options.
9390 In the line after \"#+STARTUP:, complete valid keywords.\"
9391 At all other locations, this simply calls the value of
9392 `org-completion-fallback-command'."
9393 (interactive "P")
9394 (org-without-partial-completion
9395 (catch 'exit
9396 (let* ((a nil)
9397 (end (point))
9398 (beg1 (save-excursion
9399 (skip-chars-backward (org-re "[:alnum:]_@"))
9400 (point)))
9401 (beg (save-excursion
9402 (skip-chars-backward "a-zA-Z0-9_:$")
9403 (point)))
9404 (confirm (lambda (x) (stringp (car x))))
9405 (searchhead (equal (char-before beg) ?*))
9406 (struct
9407 (when (and (member (char-before beg1) '(?. ?<))
9408 (setq a (assoc (buffer-substring beg1 (point))
9409 org-structure-template-alist)))
9410 (org-complete-expand-structure-template (1- beg1) a)
9411 (throw 'exit t)))
9412 (tag (and (equal (char-before beg1) ?:)
9413 (equal (char-after (point-at-bol)) ?*)))
9414 (prop (and (equal (char-before beg1) ?:)
9415 (not (equal (char-after (point-at-bol)) ?*))))
9416 (texp (equal (char-before beg) ?\\))
9417 (link (equal (char-before beg) ?\[))
9418 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9419 beg)
9420 "#+"))
9421 (startup (string-match "^#\\+STARTUP:.*"
9422 (buffer-substring (point-at-bol) (point))))
9423 (completion-ignore-case opt)
9424 (type nil)
9425 (tbl nil)
9426 (table (cond
9427 (opt
9428 (setq type :opt)
9429 (require 'org-exp)
9430 (append
9431 (delq nil
9432 (mapcar
9433 (lambda (x)
9434 (if (string-match
9435 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9436 (cons (match-string 2 x)
9437 (match-string 1 x))))
9438 (org-split-string (org-get-current-options) "\n")))
9439 (mapcar 'list org-additional-option-like-keywords)))
9440 (startup
9441 (setq type :startup)
9442 org-startup-options)
9443 (link (append org-link-abbrev-alist-local
9444 org-link-abbrev-alist))
9445 (texp
9446 (setq type :tex)
9447 org-html-entities)
9448 ((string-match "\\`\\*+[ \t]+\\'"
9449 (buffer-substring (point-at-bol) beg))
9450 (setq type :todo)
9451 (mapcar 'list org-todo-keywords-1))
9452 (searchhead
9453 (setq type :searchhead)
9454 (save-excursion
9455 (goto-char (point-min))
9456 (while (re-search-forward org-todo-line-regexp nil t)
9457 (push (list
9458 (org-make-org-heading-search-string
9459 (match-string 3) t))
9460 tbl)))
9461 tbl)
9462 (tag (setq type :tag beg beg1)
9463 (or org-tag-alist (org-get-buffer-tags)))
9464 (prop (setq type :prop beg beg1)
9465 (mapcar 'list (org-buffer-property-keys nil t t)))
9466 (t (progn
9467 (call-interactively org-completion-fallback-command)
9468 (throw 'exit nil)))))
9469 (pattern (buffer-substring-no-properties beg end))
9470 (completion (try-completion pattern table confirm)))
9471 (cond ((eq completion t)
9472 (if (not (assoc (upcase pattern) table))
9473 (message "Already complete")
9474 (if (and (equal type :opt)
9475 (not (member (car (assoc (upcase pattern) table))
9476 org-additional-option-like-keywords)))
9477 (insert (substring (cdr (assoc (upcase pattern) table))
9478 (length pattern)))
9479 (if (memq type '(:tag :prop)) (insert ":")))))
9480 ((null completion)
9481 (message "Can't find completion for \"%s\"" pattern)
9482 (ding))
9483 ((not (string= pattern completion))
9484 (delete-region beg end)
9485 (if (string-match " +$" completion)
9486 (setq completion (replace-match "" t t completion)))
9487 (insert completion)
9488 (if (get-buffer-window "*Completions*")
9489 (delete-window (get-buffer-window "*Completions*")))
9490 (if (assoc completion table)
9491 (if (eq type :todo) (insert " ")
9492 (if (memq type '(:tag :prop)) (insert ":"))))
9493 (if (and (equal type :opt) (assoc completion table))
9494 (message "%s" (substitute-command-keys
9495 "Press \\[org-complete] again to insert example settings"))))
9497 (message "Making completion list...")
9498 (let ((list (sort (all-completions pattern table confirm)
9499 'string<)))
9500 (with-output-to-temp-buffer "*Completions*"
9501 (condition-case nil
9502 ;; Protection needed for XEmacs and emacs 21
9503 (display-completion-list list pattern)
9504 (error (display-completion-list list)))))
9505 (message "Making completion list...%s" "done")))))))
9507 ;;;; TODO, DEADLINE, Comments
9509 (defun org-toggle-comment ()
9510 "Change the COMMENT state of an entry."
9511 (interactive)
9512 (save-excursion
9513 (org-back-to-heading)
9514 (let (case-fold-search)
9515 (if (looking-at (concat outline-regexp
9516 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9517 (replace-match "" t t nil 1)
9518 (if (looking-at outline-regexp)
9519 (progn
9520 (goto-char (match-end 0))
9521 (insert org-comment-string " ")))))))
9523 (defvar org-last-todo-state-is-todo nil
9524 "This is non-nil when the last TODO state change led to a TODO state.
9525 If the last change removed the TODO tag or switched to DONE, then
9526 this is nil.")
9528 (defvar org-setting-tags nil) ; dynamically skipped
9530 (defun org-parse-local-options (string var)
9531 "Parse STRING for startup setting relevant for variable VAR."
9532 (let ((rtn (symbol-value var))
9533 e opts)
9534 (save-match-data
9535 (if (or (not string) (not (string-match "\\S-" string)))
9537 (setq opts (delq nil (mapcar (lambda (x)
9538 (setq e (assoc x org-startup-options))
9539 (if (eq (nth 1 e) var) e nil))
9540 (org-split-string string "[ \t]+"))))
9541 (if (not opts)
9543 (setq rtn nil)
9544 (while (setq e (pop opts))
9545 (if (not (nth 3 e))
9546 (setq rtn (nth 2 e))
9547 (if (not (listp rtn)) (setq rtn nil))
9548 (push (nth 2 e) rtn)))
9549 rtn)))))
9551 (defvar org-todo-setup-filter-hook nil
9552 "Hook for functions that pre-filter todo specs.
9554 Each function takes a todo spec and returns either `nil' or the spec
9555 transformed into canonical form." )
9557 (defvar org-todo-get-default-hook nil
9558 "Hook for functions that get a default item for todo.
9560 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9561 `nil' or a string to be used for the todo mark." )
9563 (defvar org-agenda-headline-snapshot-before-repeat)
9565 (defun org-todo (&optional arg)
9566 "Change the TODO state of an item.
9567 The state of an item is given by a keyword at the start of the heading,
9568 like
9569 *** TODO Write paper
9570 *** DONE Call mom
9572 The different keywords are specified in the variable `org-todo-keywords'.
9573 By default the available states are \"TODO\" and \"DONE\".
9574 So for this example: when the item starts with TODO, it is changed to DONE.
9575 When it starts with DONE, the DONE is removed. And when neither TODO nor
9576 DONE are present, add TODO at the beginning of the heading.
9578 With C-u prefix arg, use completion to determine the new state.
9579 With numeric prefix arg, switch to that state.
9580 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9581 With a tripple C-u prefix, circumvent any state blocking.
9583 For calling through lisp, arg is also interpreted in the following way:
9584 'none -> empty state
9585 \"\"(empty string) -> switch to empty state
9586 'done -> switch to DONE
9587 'nextset -> switch to the next set of keywords
9588 'previousset -> switch to the previous set of keywords
9589 \"WAITING\" -> switch to the specified keyword, but only if it
9590 really is a member of `org-todo-keywords'."
9591 (interactive "P")
9592 (if (equal arg '(16)) (setq arg 'nextset))
9593 (let ((org-blocker-hook org-blocker-hook)
9594 (case-fold-search nil))
9595 (when (equal arg '(64))
9596 (setq arg nil org-blocker-hook nil))
9597 (when (and org-blocker-hook
9598 (or org-inhibit-blocking
9599 (org-entry-get nil "NOBLOCKING")))
9600 (setq org-blocker-hook nil))
9601 (save-excursion
9602 (catch 'exit
9603 (org-back-to-heading t)
9604 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9605 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9606 (looking-at " *"))
9607 (let* ((match-data (match-data))
9608 (startpos (point-at-bol))
9609 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9610 (org-log-done org-log-done)
9611 (org-log-repeat org-log-repeat)
9612 (org-todo-log-states org-todo-log-states)
9613 (this (match-string 1))
9614 (hl-pos (match-beginning 0))
9615 (head (org-get-todo-sequence-head this))
9616 (ass (assoc head org-todo-kwd-alist))
9617 (interpret (nth 1 ass))
9618 (done-word (nth 3 ass))
9619 (final-done-word (nth 4 ass))
9620 (last-state (or this ""))
9621 (completion-ignore-case t)
9622 (member (member this org-todo-keywords-1))
9623 (tail (cdr member))
9624 (state (cond
9625 ((and org-todo-key-trigger
9626 (or (and (equal arg '(4))
9627 (eq org-use-fast-todo-selection 'prefix))
9628 (and (not arg) org-use-fast-todo-selection
9629 (not (eq org-use-fast-todo-selection
9630 'prefix)))))
9631 ;; Use fast selection
9632 (org-fast-todo-selection))
9633 ((and (equal arg '(4))
9634 (or (not org-use-fast-todo-selection)
9635 (not org-todo-key-trigger)))
9636 ;; Read a state with completion
9637 (org-icompleting-read
9638 "State: " (mapcar (lambda(x) (list x))
9639 org-todo-keywords-1)
9640 nil t))
9641 ((eq arg 'right)
9642 (if this
9643 (if tail (car tail) nil)
9644 (car org-todo-keywords-1)))
9645 ((eq arg 'left)
9646 (if (equal member org-todo-keywords-1)
9648 (if this
9649 (nth (- (length org-todo-keywords-1)
9650 (length tail) 2)
9651 org-todo-keywords-1)
9652 (org-last org-todo-keywords-1))))
9653 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9654 (setq arg nil))) ; hack to fall back to cycling
9655 (arg
9656 ;; user or caller requests a specific state
9657 (cond
9658 ((equal arg "") nil)
9659 ((eq arg 'none) nil)
9660 ((eq arg 'done) (or done-word (car org-done-keywords)))
9661 ((eq arg 'nextset)
9662 (or (car (cdr (member head org-todo-heads)))
9663 (car org-todo-heads)))
9664 ((eq arg 'previousset)
9665 (let ((org-todo-heads (reverse org-todo-heads)))
9666 (or (car (cdr (member head org-todo-heads)))
9667 (car org-todo-heads))))
9668 ((car (member arg org-todo-keywords-1)))
9669 ((stringp arg)
9670 (error "State `%s' not valid in this file" arg))
9671 ((nth (1- (prefix-numeric-value arg))
9672 org-todo-keywords-1))))
9673 ((null member) (or head (car org-todo-keywords-1)))
9674 ((equal this final-done-word) nil) ;; -> make empty
9675 ((null tail) nil) ;; -> first entry
9676 ((memq interpret '(type priority))
9677 (if (eq this-command last-command)
9678 (car tail)
9679 (if (> (length tail) 0)
9680 (or done-word (car org-done-keywords))
9681 nil)))
9683 (car tail))))
9684 (state (or
9685 (run-hook-with-args-until-success
9686 'org-todo-get-default-hook state last-state)
9687 state))
9688 (next (if state (concat " " state " ") " "))
9689 (change-plist (list :type 'todo-state-change :from this :to state
9690 :position startpos))
9691 dolog now-done-p)
9692 (when org-blocker-hook
9693 (setq org-last-todo-state-is-todo
9694 (not (member this org-done-keywords)))
9695 (unless (save-excursion
9696 (save-match-data
9697 (run-hook-with-args-until-failure
9698 'org-blocker-hook change-plist)))
9699 (if (interactive-p)
9700 (error "TODO state change from %s to %s blocked" this state)
9701 ;; fail silently
9702 (message "TODO state change from %s to %s blocked" this state)
9703 (throw 'exit nil))))
9704 (store-match-data match-data)
9705 (replace-match next t t)
9706 (unless (pos-visible-in-window-p hl-pos)
9707 (message "TODO state changed to %s" (org-trim next)))
9708 (unless head
9709 (setq head (org-get-todo-sequence-head state)
9710 ass (assoc head org-todo-kwd-alist)
9711 interpret (nth 1 ass)
9712 done-word (nth 3 ass)
9713 final-done-word (nth 4 ass)))
9714 (when (memq arg '(nextset previousset))
9715 (message "Keyword-Set %d/%d: %s"
9716 (- (length org-todo-sets) -1
9717 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9718 (length org-todo-sets)
9719 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9720 (setq org-last-todo-state-is-todo
9721 (not (member state org-done-keywords)))
9722 (setq now-done-p (and (member state org-done-keywords)
9723 (not (member this org-done-keywords))))
9724 (and logging (org-local-logging logging))
9725 (when (and (or org-todo-log-states org-log-done)
9726 (not (eq org-inhibit-logging t))
9727 (not (memq arg '(nextset previousset))))
9728 ;; we need to look at recording a time and note
9729 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9730 (nth 2 (assoc this org-todo-log-states))))
9731 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9732 (setq dolog 'time))
9733 (when (and state
9734 (member state org-not-done-keywords)
9735 (not (member this org-not-done-keywords)))
9736 ;; This is now a todo state and was not one before
9737 ;; If there was a CLOSED time stamp, get rid of it.
9738 (org-add-planning-info nil nil 'closed))
9739 (when (and now-done-p org-log-done)
9740 ;; It is now done, and it was not done before
9741 (org-add-planning-info 'closed (org-current-time))
9742 (if (and (not dolog) (eq 'note org-log-done))
9743 (org-add-log-setup 'done state this 'findpos 'note)))
9744 (when (and state dolog)
9745 ;; This is a non-nil state, and we need to log it
9746 (org-add-log-setup 'state state this 'findpos dolog)))
9747 ;; Fixup tag positioning
9748 (org-todo-trigger-tag-changes state)
9749 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9750 (when org-provide-todo-statistics
9751 (org-update-parent-todo-statistics))
9752 (run-hooks 'org-after-todo-state-change-hook)
9753 (if (and arg (not (member state org-done-keywords)))
9754 (setq head (org-get-todo-sequence-head state)))
9755 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9756 ;; Do we need to trigger a repeat?
9757 (when now-done-p
9758 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9759 ;; This is for the agenda, take a snapshot of the headline.
9760 (save-match-data
9761 (setq org-agenda-headline-snapshot-before-repeat
9762 (org-get-heading))))
9763 (org-auto-repeat-maybe state))
9764 ;; Fixup cursor location if close to the keyword
9765 (if (and (outline-on-heading-p)
9766 (not (bolp))
9767 (save-excursion (beginning-of-line 1)
9768 (looking-at org-todo-line-regexp))
9769 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9770 (progn
9771 (goto-char (or (match-end 2) (match-end 1)))
9772 (and (looking-at " ") (just-one-space))))
9773 (when org-trigger-hook
9774 (save-excursion
9775 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9777 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9778 "Block turning an entry into a TODO, using the hierarchy.
9779 This checks whether the current task should be blocked from state
9780 changes. Such blocking occurs when:
9782 1. The task has children which are not all in a completed state.
9784 2. A task has a parent with the property :ORDERED:, and there
9785 are siblings prior to the current task with incomplete
9786 status.
9788 3. The parent of the task is blocked because it has siblings that should
9789 be done first, or is child of a block grandparent TODO entry."
9791 (catch 'dont-block
9792 ;; If this is not a todo state change, or if this entry is already DONE,
9793 ;; do not block
9794 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9795 (member (plist-get change-plist :from)
9796 (cons 'done org-done-keywords))
9797 (member (plist-get change-plist :to)
9798 (cons 'todo org-not-done-keywords)))
9799 (throw 'dont-block t))
9800 ;; If this task has children, and any are undone, it's blocked
9801 (save-excursion
9802 (org-back-to-heading t)
9803 (let ((this-level (funcall outline-level)))
9804 (outline-next-heading)
9805 (let ((child-level (funcall outline-level)))
9806 (while (and (not (eobp))
9807 (> child-level this-level))
9808 ;; this todo has children, check whether they are all
9809 ;; completed
9810 (if (and (not (org-entry-is-done-p))
9811 (org-entry-is-todo-p))
9812 (throw 'dont-block nil))
9813 (outline-next-heading)
9814 (setq child-level (funcall outline-level))))))
9815 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9816 ;; any previous siblings are undone, it's blocked
9817 (save-excursion
9818 (org-back-to-heading t)
9819 (let* ((pos (point))
9820 (parent-pos (and (org-up-heading-safe) (point))))
9821 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9822 (when (and (org-entry-get (point) "ORDERED")
9823 (forward-line 1)
9824 (re-search-forward org-not-done-heading-regexp pos t))
9825 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9826 ;; Search further up the hierarchy, to see if an anchestor is blocked
9827 (while t
9828 (goto-char parent-pos)
9829 (if (not (looking-at org-not-done-heading-regexp))
9830 (throw 'dont-block t)) ; do not block, parent is not a TODO
9831 (setq pos (point))
9832 (setq parent-pos (and (org-up-heading-safe) (point)))
9833 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9834 (when (and (org-entry-get (point) "ORDERED")
9835 (forward-line 1)
9836 (re-search-forward org-not-done-heading-regexp pos t))
9837 (throw 'dont-block nil))))))) ; block, older sibling not done.
9839 (defcustom org-track-ordered-property-with-tag nil
9840 "Should the ORDERED property also be shown as a tag?
9841 The ORDERED property decides if an entry should require subtasks to be
9842 completed in sequence. Since a property is not very visible, setting
9843 this option means that toggling the ORDERED property with the command
9844 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9845 not relevant for the behavior, but it makes things more visible.
9847 Note that toggling the tag with tags commands will not change the property
9848 and therefore not influence behavior!
9850 This can be t, meaning the tag ORDERED should be used, It can also be a
9851 string to select a different tag for this task."
9852 :group 'org-todo
9853 :type '(choice
9854 (const :tag "No tracking" nil)
9855 (const :tag "Track with ORDERED tag" t)
9856 (string :tag "Use other tag")))
9858 (defun org-toggle-ordered-property ()
9859 "Toggle the ORDERED property of the current entry.
9860 For better visibility, you can track the value of this property with a tag.
9861 See variable `org-track-ordered-property-with-tag'."
9862 (interactive)
9863 (let* ((t1 org-track-ordered-property-with-tag)
9864 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9865 (save-excursion
9866 (org-back-to-heading)
9867 (if (org-entry-get nil "ORDERED")
9868 (progn
9869 (org-delete-property "ORDERED")
9870 (and tag (org-toggle-tag tag 'off))
9871 (message "Subtasks can be completed in arbitrary order"))
9872 (org-entry-put nil "ORDERED" "t")
9873 (and tag (org-toggle-tag tag 'on))
9874 (message "Subtasks must be completed in sequence")))))
9876 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9877 (defun org-block-todo-from-checkboxes (change-plist)
9878 "Block turning an entry into a TODO, using checkboxes.
9879 This checks whether the current task should be blocked from state
9880 changes because there are uncheckd boxes in this entry."
9881 (catch 'dont-block
9882 ;; If this is not a todo state change, or if this entry is already DONE,
9883 ;; do not block
9884 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9885 (member (plist-get change-plist :from)
9886 (cons 'done org-done-keywords))
9887 (member (plist-get change-plist :to)
9888 (cons 'todo org-not-done-keywords)))
9889 (throw 'dont-block t))
9890 ;; If this task has checkboxes that are not checked, it's blocked
9891 (save-excursion
9892 (org-back-to-heading t)
9893 (let ((beg (point)) end)
9894 (outline-next-heading)
9895 (setq end (point))
9896 (goto-char beg)
9897 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9898 end t)
9899 (progn
9900 (if (boundp 'org-blocked-by-checkboxes)
9901 (setq org-blocked-by-checkboxes t))
9902 (throw 'dont-block nil)))))
9903 t)) ; do not block
9905 (defun org-update-statistics-cookies (all)
9906 "Update the statistics cookie, either from TODO or from checkboxes.
9907 This should be called with the cursor in a line with a statistics cookie."
9908 (interactive "P")
9909 (if all
9910 (progn
9911 (org-update-checkbox-count 'all)
9912 (org-map-entries 'org-update-parent-todo-statistics))
9913 (if (not (org-on-heading-p))
9914 (org-update-checkbox-count)
9915 (let ((pos (move-marker (make-marker) (point)))
9916 end l1 l2)
9917 (ignore-errors (org-back-to-heading t))
9918 (if (not (org-on-heading-p))
9919 (org-update-checkbox-count)
9920 (setq l1 (org-outline-level))
9921 (setq end (save-excursion
9922 (outline-next-heading)
9923 (if (org-on-heading-p) (setq l2 (org-outline-level)))
9924 (point)))
9925 (if (and (save-excursion (re-search-forward
9926 "^[ \t]*[-+*] \\[[- X]\\]" end t))
9927 (not (save-excursion (re-search-forward
9928 ":COOKIE_DATA:.*\\<todo\\>" end t))))
9929 (org-update-checkbox-count)
9930 (if (and l2 (> l2 l1))
9931 (progn
9932 (goto-char end)
9933 (org-update-parent-todo-statistics))
9934 (error "No data for statistics cookie"))))
9935 (goto-char pos)
9936 (move-marker pos nil)))))
9938 (defvar org-entry-property-inherited-from) ;; defined below
9939 (defun org-update-parent-todo-statistics ()
9940 "Update any statistics cookie in the parent of the current headline.
9941 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9942 the entire subtree and this will travel up the hierarchy and update
9943 statistics everywhere."
9944 (interactive)
9945 (let* ((lim 0) prop
9946 (recursive (or (not org-hierarchical-todo-statistics)
9947 (string-match
9948 "\\<recursive\\>"
9949 (or (setq prop (org-entry-get
9950 nil "COOKIE_DATA" 'inherit)) ""))))
9951 (lim (or (and prop (marker-position
9952 org-entry-property-inherited-from))
9953 lim))
9954 (first t)
9955 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9956 level ltoggle l1 new ndel
9957 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9958 (catch 'exit
9959 (save-excursion
9960 (beginning-of-line 1)
9961 (if (org-at-heading-p)
9962 (setq ltoggle (funcall outline-level))
9963 (error "This should not happen"))
9964 (while (and (setq level (org-up-heading-safe))
9965 (or recursive first)
9966 (>= (point) lim))
9967 (setq first nil)
9968 (unless (and level
9969 (not (string-match
9970 "\\<checkbox\\>"
9971 (downcase
9972 (or (org-entry-get
9973 nil "COOKIE_DATA")
9974 "")))))
9975 (throw 'exit nil))
9976 (while (re-search-forward box-re (point-at-eol) t)
9977 (setq cnt-all 0 cnt-done 0 cookie-present t)
9978 (setq is-percent (match-end 2))
9979 (save-match-data
9980 (unless (outline-next-heading) (throw 'exit nil))
9981 (while (and (looking-at org-complex-heading-regexp)
9982 (> (setq l1 (length (match-string 1))) level))
9983 (setq kwd (and (or recursive (= l1 ltoggle))
9984 (match-string 2)))
9985 (if (or (eq org-provide-todo-statistics 'all-headlines)
9986 (and (listp org-provide-todo-statistics)
9987 (or (member kwd org-provide-todo-statistics)
9988 (member kwd org-done-keywords))))
9989 (setq cnt-all (1+ cnt-all))
9990 (if (eq org-provide-todo-statistics t)
9991 (and kwd (setq cnt-all (1+ cnt-all)))))
9992 (and (member kwd org-done-keywords)
9993 (setq cnt-done (1+ cnt-done)))
9994 (outline-next-heading)))
9995 (setq new
9996 (if is-percent
9997 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9998 (format "[%d/%d]" cnt-done cnt-all))
9999 ndel (- (match-end 0) (match-beginning 0)))
10000 (goto-char (match-beginning 0))
10001 (insert new)
10002 (delete-region (point) (+ (point) ndel))))
10003 (when cookie-present
10004 (run-hook-with-args 'org-after-todo-statistics-hook
10005 cnt-done (- cnt-all cnt-done)))))
10006 (run-hooks 'org-todo-statistics-hook)))
10008 (defvar org-after-todo-statistics-hook nil
10009 "Hook that is called after a TODO statistics cookie has been updated.
10010 Each function is called with two arguments: the number of not-done entries
10011 and the number of done entries.
10013 For example, the following function, when added to this hook, will switch
10014 an entry to DONE when all children are done, and back to TODO when new
10015 entries are set to a TODO status. Note that this hook is only called
10016 when there is a statistics cookie in the headline!
10018 (defun org-summary-todo (n-done n-not-done)
10019 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10020 (let (org-log-done org-log-states) ; turn off logging
10021 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10024 (defvar org-todo-statistics-hook nil
10025 "Hook that is run whenever Org thinks TODO statistics should be updated.
10026 This hook runs even if there is no statisics cookie present, in which case
10027 `org-after-todo-statistics-hook' would not run.")
10029 (defun org-todo-trigger-tag-changes (state)
10030 "Apply the changes defined in `org-todo-state-tags-triggers'."
10031 (let ((l org-todo-state-tags-triggers)
10032 changes)
10033 (when (or (not state) (equal state ""))
10034 (setq changes (append changes (cdr (assoc "" l)))))
10035 (when (and (stringp state) (> (length state) 0))
10036 (setq changes (append changes (cdr (assoc state l)))))
10037 (when (member state org-not-done-keywords)
10038 (setq changes (append changes (cdr (assoc 'todo l)))))
10039 (when (member state org-done-keywords)
10040 (setq changes (append changes (cdr (assoc 'done l)))))
10041 (dolist (c changes)
10042 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10044 (defun org-local-logging (value)
10045 "Get logging settings from a property VALUE."
10046 (let* (words w a)
10047 ;; directly set the variables, they are already local.
10048 (setq org-log-done nil
10049 org-log-repeat nil
10050 org-todo-log-states nil)
10051 (setq words (org-split-string value))
10052 (while (setq w (pop words))
10053 (cond
10054 ((setq a (assoc w org-startup-options))
10055 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10056 (set (nth 1 a) (nth 2 a))))
10057 ((setq a (org-extract-log-state-settings w))
10058 (and (member (car a) org-todo-keywords-1)
10059 (push a org-todo-log-states)))))))
10061 (defun org-get-todo-sequence-head (kwd)
10062 "Return the head of the TODO sequence to which KWD belongs.
10063 If KWD is not set, check if there is a text property remembering the
10064 right sequence."
10065 (let (p)
10066 (cond
10067 ((not kwd)
10068 (or (get-text-property (point-at-bol) 'org-todo-head)
10069 (progn
10070 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10071 nil (point-at-eol)))
10072 (get-text-property p 'org-todo-head))))
10073 ((not (member kwd org-todo-keywords-1))
10074 (car org-todo-keywords-1))
10075 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10077 (defun org-fast-todo-selection ()
10078 "Fast TODO keyword selection with single keys.
10079 Returns the new TODO keyword, or nil if no state change should occur."
10080 (let* ((fulltable org-todo-key-alist)
10081 (done-keywords org-done-keywords) ;; needed for the faces.
10082 (maxlen (apply 'max (mapcar
10083 (lambda (x)
10084 (if (stringp (car x)) (string-width (car x)) 0))
10085 fulltable)))
10086 (expert nil)
10087 (fwidth (+ maxlen 3 1 3))
10088 (ncol (/ (- (window-width) 4) fwidth))
10089 tg cnt e c tbl
10090 groups ingroup)
10091 (save-excursion
10092 (save-window-excursion
10093 (if expert
10094 (set-buffer (get-buffer-create " *Org todo*"))
10095 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10096 (erase-buffer)
10097 (org-set-local 'org-done-keywords done-keywords)
10098 (setq tbl fulltable cnt 0)
10099 (while (setq e (pop tbl))
10100 (cond
10101 ((equal e '(:startgroup))
10102 (push '() groups) (setq ingroup t)
10103 (when (not (= cnt 0))
10104 (setq cnt 0)
10105 (insert "\n"))
10106 (insert "{ "))
10107 ((equal e '(:endgroup))
10108 (setq ingroup nil cnt 0)
10109 (insert "}\n"))
10110 ((equal e '(:newline))
10111 (when (not (= cnt 0))
10112 (setq cnt 0)
10113 (insert "\n")
10114 (setq e (car tbl))
10115 (while (equal (car tbl) '(:newline))
10116 (insert "\n")
10117 (setq tbl (cdr tbl)))))
10119 (setq tg (car e) c (cdr e))
10120 (if ingroup (push tg (car groups)))
10121 (setq tg (org-add-props tg nil 'face
10122 (org-get-todo-face tg)))
10123 (if (and (= cnt 0) (not ingroup)) (insert " "))
10124 (insert "[" c "] " tg (make-string
10125 (- fwidth 4 (length tg)) ?\ ))
10126 (when (= (setq cnt (1+ cnt)) ncol)
10127 (insert "\n")
10128 (if ingroup (insert " "))
10129 (setq cnt 0)))))
10130 (insert "\n")
10131 (goto-char (point-min))
10132 (if (not expert) (org-fit-window-to-buffer))
10133 (message "[a-z..]:Set [SPC]:clear")
10134 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10135 (cond
10136 ((or (= c ?\C-g)
10137 (and (= c ?q) (not (rassoc c fulltable))))
10138 (setq quit-flag t))
10139 ((= c ?\ ) nil)
10140 ((setq e (rassoc c fulltable) tg (car e))
10142 (t (setq quit-flag t)))))))
10144 (defun org-entry-is-todo-p ()
10145 (member (org-get-todo-state) org-not-done-keywords))
10147 (defun org-entry-is-done-p ()
10148 (member (org-get-todo-state) org-done-keywords))
10150 (defun org-get-todo-state ()
10151 (save-excursion
10152 (org-back-to-heading t)
10153 (and (looking-at org-todo-line-regexp)
10154 (match-end 2)
10155 (match-string 2))))
10157 (defun org-at-date-range-p (&optional inactive-ok)
10158 "Is the cursor inside a date range?"
10159 (interactive)
10160 (save-excursion
10161 (catch 'exit
10162 (let ((pos (point)))
10163 (skip-chars-backward "^[<\r\n")
10164 (skip-chars-backward "<[")
10165 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10166 (>= (match-end 0) pos)
10167 (throw 'exit t))
10168 (skip-chars-backward "^<[\r\n")
10169 (skip-chars-backward "<[")
10170 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10171 (>= (match-end 0) pos)
10172 (throw 'exit t)))
10173 nil)))
10175 (defun org-get-repeat (&optional tagline)
10176 "Check if there is a deadline/schedule with repeater in this entry."
10177 (save-match-data
10178 (save-excursion
10179 (org-back-to-heading t)
10180 (and (re-search-forward (if tagline
10181 (concat tagline "\\s-*" org-repeat-re)
10182 org-repeat-re)
10183 (org-entry-end-position) t)
10184 (match-string-no-properties 1)))))
10186 (defvar org-last-changed-timestamp)
10187 (defvar org-last-inserted-timestamp)
10188 (defvar org-log-post-message)
10189 (defvar org-log-note-purpose)
10190 (defvar org-log-note-how)
10191 (defvar org-log-note-extra)
10192 (defun org-auto-repeat-maybe (done-word)
10193 "Check if the current headline contains a repeated deadline/schedule.
10194 If yes, set TODO state back to what it was and change the base date
10195 of repeating deadline/scheduled time stamps to new date.
10196 This function is run automatically after each state change to a DONE state."
10197 ;; last-state is dynamically scoped into this function
10198 (let* ((repeat (org-get-repeat))
10199 (aa (assoc last-state org-todo-kwd-alist))
10200 (interpret (nth 1 aa))
10201 (head (nth 2 aa))
10202 (whata '(("d" . day) ("m" . month) ("y" . year)))
10203 (msg "Entry repeats: ")
10204 (org-log-done nil)
10205 (org-todo-log-states nil)
10206 (nshiftmax 10) (nshift 0)
10207 re type n what ts time)
10208 (when repeat
10209 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10210 (org-todo (if (eq interpret 'type) last-state head))
10211 (org-entry-put nil "LAST_REPEAT" (format-time-string
10212 (org-time-stamp-format t t)))
10213 (when org-log-repeat
10214 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10215 (memq 'org-add-log-note post-command-hook))
10216 ;; OK, we are already setup for some record
10217 (if (eq org-log-repeat 'note)
10218 ;; make sure we take a note, not only a time stamp
10219 (setq org-log-note-how 'note))
10220 ;; Set up for taking a record
10221 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10222 last-state
10223 'findpos org-log-repeat)))
10224 (org-back-to-heading t)
10225 (org-add-planning-info nil nil 'closed)
10226 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10227 org-deadline-time-regexp "\\)\\|\\("
10228 org-ts-regexp "\\)"))
10229 (while (re-search-forward
10230 re (save-excursion (outline-next-heading) (point)) t)
10231 (setq type (if (match-end 1) org-scheduled-string
10232 (if (match-end 3) org-deadline-string "Plain:"))
10233 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10234 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10235 (setq n (string-to-number (match-string 2 ts))
10236 what (match-string 3 ts))
10237 (if (equal what "w") (setq n (* n 7) what "d"))
10238 ;; Preparation, see if we need to modify the start date for the change
10239 (when (match-end 1)
10240 (setq time (save-match-data (org-time-string-to-time ts)))
10241 (cond
10242 ((equal (match-string 1 ts) ".")
10243 ;; Shift starting date to today
10244 (org-timestamp-change
10245 (- (time-to-days (current-time)) (time-to-days time))
10246 'day))
10247 ((equal (match-string 1 ts) "+")
10248 (while (or (= nshift 0)
10249 (<= (time-to-days time) (time-to-days (current-time))))
10250 (when (= (incf nshift) nshiftmax)
10251 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10252 (error "Abort")))
10253 (org-timestamp-change n (cdr (assoc what whata)))
10254 (org-at-timestamp-p t)
10255 (setq ts (match-string 1))
10256 (setq time (save-match-data (org-time-string-to-time ts))))
10257 (org-timestamp-change (- n) (cdr (assoc what whata)))
10258 ;; rematch, so that we have everything in place for the real shift
10259 (org-at-timestamp-p t)
10260 (setq ts (match-string 1))
10261 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10262 (org-timestamp-change n (cdr (assoc what whata)))
10263 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10264 (setq org-log-post-message msg)
10265 (message "%s" msg))))
10267 (defun org-show-todo-tree (arg)
10268 "Make a compact tree which shows all headlines marked with TODO.
10269 The tree will show the lines where the regexp matches, and all higher
10270 headlines above the match.
10271 With a \\[universal-argument] prefix, prompt for a regexp to match.
10272 With a numeric prefix N, construct a sparse tree for the Nth element
10273 of `org-todo-keywords-1'."
10274 (interactive "P")
10275 (let ((case-fold-search nil)
10276 (kwd-re
10277 (cond ((null arg) org-not-done-regexp)
10278 ((equal arg '(4))
10279 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10280 (mapcar 'list org-todo-keywords-1))))
10281 (concat "\\("
10282 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10283 "\\)\\>")))
10284 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10285 (regexp-quote (nth (1- (prefix-numeric-value arg))
10286 org-todo-keywords-1)))
10287 (t (error "Invalid prefix argument: %s" arg)))))
10288 (message "%d TODO entries found"
10289 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10291 (defun org-deadline (&optional remove time)
10292 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10293 With argument REMOVE, remove any deadline from the item.
10294 When TIME is set, it should be an internal time specification, and the
10295 scheduling will use the corresponding date."
10296 (interactive "P")
10297 (if remove
10298 (progn
10299 (org-remove-timestamp-with-keyword org-deadline-string)
10300 (message "Item no longer has a deadline."))
10301 (if (org-get-repeat)
10302 (error "Cannot change deadline on task with repeater, please do that by hand")
10303 (org-add-planning-info 'deadline time 'closed)
10304 (message "Deadline on %s" org-last-inserted-timestamp))))
10306 (defun org-schedule (&optional remove time)
10307 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10308 With argument REMOVE, remove any scheduling date from the item.
10309 When TIME is set, it should be an internal time specification, and the
10310 scheduling will use the corresponding date."
10311 (interactive "P")
10312 (if remove
10313 (progn
10314 (org-remove-timestamp-with-keyword org-scheduled-string)
10315 (message "Item is no longer scheduled."))
10316 (if (org-get-repeat)
10317 (error "Cannot reschedule task with repeater, please do that by hand")
10318 (org-add-planning-info 'scheduled time 'closed)
10319 (message "Scheduled to %s" org-last-inserted-timestamp))))
10321 (defun org-get-scheduled-time (pom &optional inherit)
10322 "Get the scheduled time as a time tuple, of a format suitable
10323 for calling org-schedule with, or if there is no scheduling,
10324 returns nil."
10325 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10326 (when time
10327 (apply 'encode-time (org-parse-time-string time)))))
10329 (defun org-get-deadline-time (pom &optional inherit)
10330 "Get the deadine as a time tuple, of a format suitable for
10331 calling org-deadlin with, or if there is no scheduling, returns
10332 nil."
10333 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10334 (when time
10335 (apply 'encode-time (org-parse-time-string time)))))
10337 (defun org-remove-timestamp-with-keyword (keyword)
10338 "Remove all time stamps with KEYWORD in the current entry."
10339 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10340 beg)
10341 (save-excursion
10342 (org-back-to-heading t)
10343 (setq beg (point))
10344 (outline-next-heading)
10345 (while (re-search-backward re beg t)
10346 (replace-match "")
10347 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10348 (equal (char-before) ?\ ))
10349 (backward-delete-char 1)
10350 (if (string-match "^[ \t]*$" (buffer-substring
10351 (point-at-bol) (point-at-eol)))
10352 (delete-region (point-at-bol)
10353 (min (point-max) (1+ (point-at-eol))))))))))
10355 (defun org-add-planning-info (what &optional time &rest remove)
10356 "Insert new timestamp with keyword in the line directly after the headline.
10357 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10358 If non is given, the user is prompted for a date.
10359 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10360 be removed."
10361 (interactive)
10362 (let (org-time-was-given org-end-time-was-given ts
10363 end default-time default-input)
10365 (catch 'exit
10366 (when (and (not time) (memq what '(scheduled deadline)))
10367 ;; Try to get a default date/time from existing timestamp
10368 (save-excursion
10369 (org-back-to-heading t)
10370 (setq end (save-excursion (outline-next-heading) (point)))
10371 (when (re-search-forward (if (eq what 'scheduled)
10372 org-scheduled-time-regexp
10373 org-deadline-time-regexp)
10374 end t)
10375 (setq ts (match-string 1)
10376 default-time
10377 (apply 'encode-time (org-parse-time-string ts))
10378 default-input (and ts (org-get-compact-tod ts))))))
10379 (when what
10380 ;; If necessary, get the time from the user
10381 (setq time (or time (org-read-date nil 'to-time nil nil
10382 default-time default-input))))
10384 (when (and org-insert-labeled-timestamps-at-point
10385 (member what '(scheduled deadline)))
10386 (insert
10387 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10388 (org-insert-time-stamp time org-time-was-given
10389 nil nil nil (list org-end-time-was-given))
10390 (setq what nil))
10391 (save-excursion
10392 (save-restriction
10393 (let (col list elt ts buffer-invisibility-spec)
10394 (org-back-to-heading t)
10395 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10396 (goto-char (match-end 1))
10397 (setq col (current-column))
10398 (goto-char (match-end 0))
10399 (if (eobp) (insert "\n") (forward-char 1))
10400 (when (and (not what)
10401 (not (looking-at
10402 (concat "[ \t]*"
10403 org-keyword-time-not-clock-regexp))))
10404 ;; Nothing to add, nothing to remove...... :-)
10405 (throw 'exit nil))
10406 (if (and (not (looking-at outline-regexp))
10407 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10408 "[^\r\n]*"))
10409 (not (equal (match-string 1) org-clock-string)))
10410 (narrow-to-region (match-beginning 0) (match-end 0))
10411 (insert-before-markers "\n")
10412 (backward-char 1)
10413 (narrow-to-region (point) (point))
10414 (and org-adapt-indentation (org-indent-to-column col)))
10415 ;; Check if we have to remove something.
10416 (setq list (cons what remove))
10417 (while list
10418 (setq elt (pop list))
10419 (goto-char (point-min))
10420 (when (or (and (eq elt 'scheduled)
10421 (re-search-forward org-scheduled-time-regexp nil t))
10422 (and (eq elt 'deadline)
10423 (re-search-forward org-deadline-time-regexp nil t))
10424 (and (eq elt 'closed)
10425 (re-search-forward org-closed-time-regexp nil t)))
10426 (replace-match "")
10427 (if (looking-at "--+<[^>]+>") (replace-match ""))
10428 (skip-chars-backward " ")
10429 (if (looking-at " +") (replace-match ""))))
10430 (goto-char (point-max))
10431 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10432 (when what
10433 (insert
10434 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10435 (cond ((eq what 'scheduled) org-scheduled-string)
10436 ((eq what 'deadline) org-deadline-string)
10437 ((eq what 'closed) org-closed-string))
10438 " ")
10439 (setq ts (org-insert-time-stamp
10440 time
10441 (or org-time-was-given
10442 (and (eq what 'closed) org-log-done-with-time))
10443 (eq what 'closed)
10444 nil nil (list org-end-time-was-given)))
10445 (end-of-line 1))
10446 (goto-char (point-min))
10447 (widen)
10448 (if (and (looking-at "[ \t]+\n")
10449 (equal (char-before) ?\n))
10450 (delete-region (1- (point)) (point-at-eol)))
10451 ts))))))
10453 (defvar org-log-note-marker (make-marker))
10454 (defvar org-log-note-purpose nil)
10455 (defvar org-log-note-state nil)
10456 (defvar org-log-note-previous-state nil)
10457 (defvar org-log-note-how nil)
10458 (defvar org-log-note-extra nil)
10459 (defvar org-log-note-window-configuration nil)
10460 (defvar org-log-note-return-to (make-marker))
10461 (defvar org-log-post-message nil
10462 "Message to be displayed after a log note has been stored.
10463 The auto-repeater uses this.")
10465 (defun org-add-note ()
10466 "Add a note to the current entry.
10467 This is done in the same way as adding a state change note."
10468 (interactive)
10469 (org-add-log-setup 'note nil nil 'findpos nil))
10471 (defvar org-property-end-re)
10472 (defun org-add-log-setup (&optional purpose state prev-state
10473 findpos how &optional extra)
10474 "Set up the post command hook to take a note.
10475 If this is about to TODO state change, the new state is expected in STATE.
10476 When FINDPOS is non-nil, find the correct position for the note in
10477 the current entry. If not, assume that it can be inserted at point.
10478 HOW is an indicator what kind of note should be created.
10479 EXTRA is additional text that will be inserted into the notes buffer."
10480 (let* ((org-log-into-drawer (org-log-into-drawer))
10481 (drawer (cond ((stringp org-log-into-drawer)
10482 org-log-into-drawer)
10483 (org-log-into-drawer "LOGBOOK")
10484 (t nil))))
10485 (save-restriction
10486 (save-excursion
10487 (when findpos
10488 (org-back-to-heading t)
10489 (narrow-to-region (point) (save-excursion
10490 (outline-next-heading) (point)))
10491 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10492 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10493 "[^\r\n]*\\)?"))
10494 (goto-char (match-end 0))
10495 (cond
10496 (drawer
10497 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10498 nil t)
10499 (progn
10500 (goto-char (match-end 0))
10501 (or org-log-states-order-reversed
10502 (and (re-search-forward org-property-end-re nil t)
10503 (goto-char (1- (match-beginning 0))))))
10504 (insert "\n:" drawer ":\n:END:")
10505 (beginning-of-line 0)
10506 (org-indent-line-function)
10507 (beginning-of-line 2)
10508 (org-indent-line-function)
10509 (end-of-line 0)))
10510 ((and org-log-state-notes-insert-after-drawers
10511 (save-excursion
10512 (forward-line) (looking-at org-drawer-regexp)))
10513 (forward-line)
10514 (while (looking-at org-drawer-regexp)
10515 (goto-char (match-end 0))
10516 (re-search-forward org-property-end-re (point-max) t)
10517 (forward-line))
10518 (forward-line -1)))
10519 (unless org-log-states-order-reversed
10520 (and (= (char-after) ?\n) (forward-char 1))
10521 (org-skip-over-state-notes)
10522 (skip-chars-backward " \t\n\r")))
10523 (move-marker org-log-note-marker (point))
10524 (setq org-log-note-purpose purpose
10525 org-log-note-state state
10526 org-log-note-previous-state prev-state
10527 org-log-note-how how
10528 org-log-note-extra extra)
10529 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10531 (defun org-skip-over-state-notes ()
10532 "Skip past the list of State notes in an entry."
10533 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10534 (while (looking-at "[ \t]*- State")
10535 (condition-case nil
10536 (org-next-item)
10537 (error (org-end-of-item)))))
10539 (defun org-add-log-note (&optional purpose)
10540 "Pop up a window for taking a note, and add this note later at point."
10541 (remove-hook 'post-command-hook 'org-add-log-note)
10542 (setq org-log-note-window-configuration (current-window-configuration))
10543 (delete-other-windows)
10544 (move-marker org-log-note-return-to (point))
10545 (switch-to-buffer (marker-buffer org-log-note-marker))
10546 (goto-char org-log-note-marker)
10547 (org-switch-to-buffer-other-window "*Org Note*")
10548 (erase-buffer)
10549 (if (memq org-log-note-how '(time state))
10550 (let (current-prefix-arg) (org-store-log-note))
10551 (let ((org-inhibit-startup t)) (org-mode))
10552 (insert (format "# Insert note for %s.
10553 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10554 (cond
10555 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10556 ((eq org-log-note-purpose 'done) "closed todo item")
10557 ((eq org-log-note-purpose 'state)
10558 (format "state change from \"%s\" to \"%s\""
10559 (or org-log-note-previous-state "")
10560 (or org-log-note-state "")))
10561 ((eq org-log-note-purpose 'note)
10562 "this entry")
10563 (t (error "This should not happen")))))
10564 (if org-log-note-extra (insert org-log-note-extra))
10565 (org-set-local 'org-finish-function 'org-store-log-note)))
10567 (defvar org-note-abort nil) ; dynamically scoped
10568 (defun org-store-log-note ()
10569 "Finish taking a log note, and insert it to where it belongs."
10570 (let ((txt (buffer-string))
10571 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10572 lines ind)
10573 (kill-buffer (current-buffer))
10574 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10575 (setq txt (replace-match "" t t txt)))
10576 (if (string-match "\\s-+\\'" txt)
10577 (setq txt (replace-match "" t t txt)))
10578 (setq lines (org-split-string txt "\n"))
10579 (when (and note (string-match "\\S-" note))
10580 (setq note
10581 (org-replace-escapes
10582 note
10583 (list (cons "%u" (user-login-name))
10584 (cons "%U" user-full-name)
10585 (cons "%t" (format-time-string
10586 (org-time-stamp-format 'long 'inactive)
10587 (current-time)))
10588 (cons "%s" (if org-log-note-state
10589 (concat "\"" org-log-note-state "\"")
10590 ""))
10591 (cons "%S" (if org-log-note-previous-state
10592 (concat "\"" org-log-note-previous-state "\"")
10593 "\"\"")))))
10594 (if lines (setq note (concat note " \\\\")))
10595 (push note lines))
10596 (when (or current-prefix-arg org-note-abort)
10597 (when org-log-into-drawer
10598 (org-remove-empty-drawer-at
10599 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10600 org-log-note-marker))
10601 (setq lines nil))
10602 (when lines
10603 (save-excursion
10604 (set-buffer (marker-buffer org-log-note-marker))
10605 (save-excursion
10606 (goto-char org-log-note-marker)
10607 (move-marker org-log-note-marker nil)
10608 (end-of-line 1)
10609 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10610 (insert "- " (pop lines))
10611 (org-indent-line-function)
10612 (beginning-of-line 1)
10613 (looking-at "[ \t]*")
10614 (setq ind (concat (match-string 0) " "))
10615 (end-of-line 1)
10616 (while lines (insert "\n" ind (pop lines)))
10617 (message "Note stored")
10618 (org-back-to-heading t)
10619 (org-cycle-hide-drawers 'children)))))
10620 (set-window-configuration org-log-note-window-configuration)
10621 (with-current-buffer (marker-buffer org-log-note-return-to)
10622 (goto-char org-log-note-return-to))
10623 (move-marker org-log-note-return-to nil)
10624 (and org-log-post-message (message "%s" org-log-post-message)))
10626 (defun org-remove-empty-drawer-at (drawer pos)
10627 "Remove an emptyr DARWER drawer at position POS.
10628 POS may also be a marker."
10629 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10630 (save-excursion
10631 (save-restriction
10632 (widen)
10633 (goto-char pos)
10634 (if (org-in-regexp
10635 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10636 (replace-match ""))))))
10638 (defun org-sparse-tree (&optional arg)
10639 "Create a sparse tree, prompt for the details.
10640 This command can create sparse trees. You first need to select the type
10641 of match used to create the tree:
10643 t Show entries with a specific TODO keyword.
10644 m Show entries selected by a tags/property match.
10645 p Enter a property name and its value (both with completion on existing
10646 names/values) and show entries with that property.
10647 r Show entries matching a regular expression.
10648 d Show deadlines due within `org-deadline-warning-days'.
10649 b Show deadlines and scheduled items before a date.
10650 a Show deadlines and scheduled items after a date."
10651 (interactive "P")
10652 (let (ans kwd value)
10653 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10654 (setq ans (read-char-exclusive))
10655 (cond
10656 ((equal ans ?d)
10657 (call-interactively 'org-check-deadlines))
10658 ((equal ans ?b)
10659 (call-interactively 'org-check-before-date))
10660 ((equal ans ?a)
10661 (call-interactively 'org-check-after-date))
10662 ((equal ans ?t)
10663 (org-show-todo-tree '(4)))
10664 ((member ans '(?T ?m))
10665 (call-interactively 'org-match-sparse-tree))
10666 ((member ans '(?p ?P))
10667 (setq kwd (org-icompleting-read "Property: "
10668 (mapcar 'list (org-buffer-property-keys))))
10669 (setq value (org-icompleting-read "Value: "
10670 (mapcar 'list (org-property-values kwd))))
10671 (unless (string-match "\\`{.*}\\'" value)
10672 (setq value (concat "\"" value "\"")))
10673 (org-match-sparse-tree arg (concat kwd "=" value)))
10674 ((member ans '(?r ?R ?/))
10675 (call-interactively 'org-occur))
10676 (t (error "No such sparse tree command \"%c\"" ans)))))
10678 (defvar org-occur-highlights nil
10679 "List of overlays used for occur matches.")
10680 (make-variable-buffer-local 'org-occur-highlights)
10681 (defvar org-occur-parameters nil
10682 "Parameters of the active org-occur calls.
10683 This is a list, each call to org-occur pushes as cons cell,
10684 containing the regular expression and the callback, onto the list.
10685 The list can contain several entries if `org-occur' has been called
10686 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10687 will only contain one set of parameters. When the highlights are
10688 removed (for example with `C-c C-c', or with the next edit (depending
10689 on `org-remove-highlights-with-change'), this variable is emptied
10690 as well.")
10691 (make-variable-buffer-local 'org-occur-parameters)
10693 (defun org-occur (regexp &optional keep-previous callback)
10694 "Make a compact tree which shows all matches of REGEXP.
10695 The tree will show the lines where the regexp matches, and all higher
10696 headlines above the match. It will also show the heading after the match,
10697 to make sure editing the matching entry is easy.
10698 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10699 call to `org-occur' will be kept, to allow stacking of calls to this
10700 command.
10701 If CALLBACK is non-nil, it is a function which is called to confirm
10702 that the match should indeed be shown."
10703 (interactive "sRegexp: \nP")
10704 (when (equal regexp "")
10705 (error "Regexp cannot be empty"))
10706 (unless keep-previous
10707 (org-remove-occur-highlights nil nil t))
10708 (push (cons regexp callback) org-occur-parameters)
10709 (let ((cnt 0))
10710 (save-excursion
10711 (goto-char (point-min))
10712 (if (or (not keep-previous) ; do not want to keep
10713 (not org-occur-highlights)) ; no previous matches
10714 ;; hide everything
10715 (org-overview))
10716 (while (re-search-forward regexp nil t)
10717 (when (or (not callback)
10718 (save-match-data (funcall callback)))
10719 (setq cnt (1+ cnt))
10720 (when org-highlight-sparse-tree-matches
10721 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10722 (org-show-context 'occur-tree))))
10723 (when org-remove-highlights-with-change
10724 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10725 nil 'local))
10726 (unless org-sparse-tree-open-archived-trees
10727 (org-hide-archived-subtrees (point-min) (point-max)))
10728 (run-hooks 'org-occur-hook)
10729 (if (interactive-p)
10730 (message "%d match(es) for regexp %s" cnt regexp))
10731 cnt))
10733 (defun org-show-context (&optional key)
10734 "Make sure point and context and visible.
10735 How much context is shown depends upon the variables
10736 `org-show-hierarchy-above', `org-show-following-heading'. and
10737 `org-show-siblings'."
10738 (let ((heading-p (org-on-heading-p t))
10739 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10740 (following-p (org-get-alist-option org-show-following-heading key))
10741 (entry-p (org-get-alist-option org-show-entry-below key))
10742 (siblings-p (org-get-alist-option org-show-siblings key)))
10743 (catch 'exit
10744 ;; Show heading or entry text
10745 (if (and heading-p (not entry-p))
10746 (org-flag-heading nil) ; only show the heading
10747 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10748 (org-show-hidden-entry))) ; show entire entry
10749 (when following-p
10750 ;; Show next sibling, or heading below text
10751 (save-excursion
10752 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10753 (org-flag-heading nil))))
10754 (when siblings-p (org-show-siblings))
10755 (when hierarchy-p
10756 ;; show all higher headings, possibly with siblings
10757 (save-excursion
10758 (while (and (condition-case nil
10759 (progn (org-up-heading-all 1) t)
10760 (error nil))
10761 (not (bobp)))
10762 (org-flag-heading nil)
10763 (when siblings-p (org-show-siblings))))))))
10765 (defun org-reveal (&optional siblings)
10766 "Show current entry, hierarchy above it, and the following headline.
10767 This can be used to show a consistent set of context around locations
10768 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10769 not t for the search context.
10771 With optional argument SIBLINGS, on each level of the hierarchy all
10772 siblings are shown. This repairs the tree structure to what it would
10773 look like when opened with hierarchical calls to `org-cycle'."
10774 (interactive "P")
10775 (let ((org-show-hierarchy-above t)
10776 (org-show-following-heading t)
10777 (org-show-siblings (if siblings t org-show-siblings)))
10778 (org-show-context nil)))
10780 (defun org-highlight-new-match (beg end)
10781 "Highlight from BEG to END and mark the highlight is an occur headline."
10782 (let ((ov (org-make-overlay beg end)))
10783 (org-overlay-put ov 'face 'secondary-selection)
10784 (push ov org-occur-highlights)))
10786 (defun org-remove-occur-highlights (&optional beg end noremove)
10787 "Remove the occur highlights from the buffer.
10788 BEG and END are ignored. If NOREMOVE is nil, remove this function
10789 from the `before-change-functions' in the current buffer."
10790 (interactive)
10791 (unless org-inhibit-highlight-removal
10792 (mapc 'org-delete-overlay org-occur-highlights)
10793 (setq org-occur-highlights nil)
10794 (setq org-occur-parameters nil)
10795 (unless noremove
10796 (remove-hook 'before-change-functions
10797 'org-remove-occur-highlights 'local))))
10799 ;;;; Priorities
10801 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10802 "Regular expression matching the priority indicator.")
10804 (defvar org-remove-priority-next-time nil)
10806 (defun org-priority-up ()
10807 "Increase the priority of the current item."
10808 (interactive)
10809 (org-priority 'up))
10811 (defun org-priority-down ()
10812 "Decrease the priority of the current item."
10813 (interactive)
10814 (org-priority 'down))
10816 (defun org-priority (&optional action)
10817 "Change the priority of an item by ARG.
10818 ACTION can be `set', `up', `down', or a character."
10819 (interactive)
10820 (unless org-enable-priority-commands
10821 (error "Priority commands are disabled"))
10822 (setq action (or action 'set))
10823 (let (current new news have remove)
10824 (save-excursion
10825 (org-back-to-heading t)
10826 (if (looking-at org-priority-regexp)
10827 (setq current (string-to-char (match-string 2))
10828 have t)
10829 (setq current org-default-priority))
10830 (cond
10831 ((eq action 'remove)
10832 (setq remove t new ?\ ))
10833 ((or (eq action 'set)
10834 (if (featurep 'xemacs) (characterp action) (integerp action)))
10835 (if (not (eq action 'set))
10836 (setq new action)
10837 (message "Priority %c-%c, SPC to remove: "
10838 org-highest-priority org-lowest-priority)
10839 (setq new (read-char-exclusive)))
10840 (if (and (= (upcase org-highest-priority) org-highest-priority)
10841 (= (upcase org-lowest-priority) org-lowest-priority))
10842 (setq new (upcase new)))
10843 (cond ((equal new ?\ ) (setq remove t))
10844 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10845 (error "Priority must be between `%c' and `%c'"
10846 org-highest-priority org-lowest-priority))))
10847 ((eq action 'up)
10848 (if (and (not have) (eq last-command this-command))
10849 (setq new org-lowest-priority)
10850 (setq new (if (and org-priority-start-cycle-with-default (not have))
10851 org-default-priority (1- current)))))
10852 ((eq action 'down)
10853 (if (and (not have) (eq last-command this-command))
10854 (setq new org-highest-priority)
10855 (setq new (if (and org-priority-start-cycle-with-default (not have))
10856 org-default-priority (1+ current)))))
10857 (t (error "Invalid action")))
10858 (if (or (< (upcase new) org-highest-priority)
10859 (> (upcase new) org-lowest-priority))
10860 (setq remove t))
10861 (setq news (format "%c" new))
10862 (if have
10863 (if remove
10864 (replace-match "" t t nil 1)
10865 (replace-match news t t nil 2))
10866 (if remove
10867 (error "No priority cookie found in line")
10868 (let ((case-fold-search nil))
10869 (looking-at org-todo-line-regexp))
10870 (if (match-end 2)
10871 (progn
10872 (goto-char (match-end 2))
10873 (insert " [#" news "]"))
10874 (goto-char (match-beginning 3))
10875 (insert "[#" news "] "))))
10876 (org-preserve-lc (org-set-tags nil 'align)))
10877 (if remove
10878 (message "Priority removed")
10879 (message "Priority of current item set to %s" news))))
10881 (defun org-get-priority (s)
10882 "Find priority cookie and return priority."
10883 (save-match-data
10884 (if (not (string-match org-priority-regexp s))
10885 (* 1000 (- org-lowest-priority org-default-priority))
10886 (* 1000 (- org-lowest-priority
10887 (string-to-char (match-string 2 s)))))))
10889 ;;;; Tags
10891 (defvar org-agenda-archives-mode)
10892 (defvar org-map-continue-from nil
10893 "Position from where mapping should continue.
10894 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10896 (defvar org-scanner-tags nil
10897 "The current tag list while the tags scanner is running.")
10898 (defvar org-trust-scanner-tags nil
10899 "Should `org-get-tags-at' use the tags fro the scanner.
10900 This is for internal dynamical scoping only.
10901 When this is non-nil, the function `org-get-tags-at' will return the value
10902 of `org-scanner-tags' instead of building the list by itself. This
10903 can lead to large speed-ups when the tags scanner is used in a file with
10904 many entries, and when the list of tags is retrieved, for example to
10905 obtain a list of properties. Building the tags list for each entry in such
10906 a file becomes an N^2 operation - but with this variable set, it scales
10907 as N.")
10909 (defun org-scan-tags (action matcher &optional todo-only)
10910 "Scan headline tags with inheritance and produce output ACTION.
10912 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10913 or `agenda' to produce an entry list for an agenda view. It can also be
10914 a Lisp form or a function that should be called at each matched headline, in
10915 this case the return value is a list of all return values from these calls.
10917 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10918 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10919 only lines with a TODO keyword are included in the output."
10920 (require 'org-agenda)
10921 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10922 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10923 (org-re
10924 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10925 (props (list 'face 'default
10926 'done-face 'org-agenda-done
10927 'undone-face 'default
10928 'mouse-face 'highlight
10929 'org-not-done-regexp org-not-done-regexp
10930 'org-todo-regexp org-todo-regexp
10931 'keymap org-agenda-keymap
10932 'help-echo
10933 (format "mouse-2 or RET jump to org file %s"
10934 (abbreviate-file-name
10935 (or (buffer-file-name (buffer-base-buffer))
10936 (buffer-name (buffer-base-buffer)))))))
10937 (case-fold-search nil)
10938 (org-map-continue-from nil)
10939 lspos tags tags-list
10940 (tags-alist (list (cons 0 org-file-tags)))
10941 (llast 0) rtn rtn1 level category i txt
10942 todo marker entry priority)
10943 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10944 (setq action (list 'lambda nil action)))
10945 (save-excursion
10946 (goto-char (point-min))
10947 (when (eq action 'sparse-tree)
10948 (org-overview)
10949 (org-remove-occur-highlights))
10950 (while (re-search-forward re nil t)
10951 (catch :skip
10952 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10953 tags (if (match-end 4) (org-match-string-no-properties 4)))
10954 (goto-char (setq lspos (match-beginning 0)))
10955 (setq level (org-reduced-level (funcall outline-level))
10956 category (org-get-category))
10957 (setq i llast llast level)
10958 ;; remove tag lists from same and sublevels
10959 (while (>= i level)
10960 (when (setq entry (assoc i tags-alist))
10961 (setq tags-alist (delete entry tags-alist)))
10962 (setq i (1- i)))
10963 ;; add the next tags
10964 (when tags
10965 (setq tags (org-split-string tags ":")
10966 tags-alist
10967 (cons (cons level tags) tags-alist)))
10968 ;; compile tags for current headline
10969 (setq tags-list
10970 (if org-use-tag-inheritance
10971 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10972 tags)
10973 org-scanner-tags tags-list)
10974 (when org-use-tag-inheritance
10975 (setcdr (car tags-alist)
10976 (mapcar (lambda (x)
10977 (setq x (copy-sequence x))
10978 (org-add-prop-inherited x))
10979 (cdar tags-alist))))
10980 (when (and tags org-use-tag-inheritance
10981 (or (not (eq t org-use-tag-inheritance))
10982 org-tags-exclude-from-inheritance))
10983 ;; selective inheritance, remove uninherited ones
10984 (setcdr (car tags-alist)
10985 (org-remove-uniherited-tags (cdar tags-alist))))
10986 (when (and (or (not todo-only)
10987 (and (member todo org-not-done-keywords)
10988 (or (not org-agenda-tags-todo-honor-ignore-options)
10989 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10990 (let ((case-fold-search t)) (eval matcher))
10992 (not (member org-archive-tag tags-list))
10993 ;; we have an archive tag, should we use this anyway?
10994 (or (not org-agenda-skip-archived-trees)
10995 (and (eq action 'agenda) org-agenda-archives-mode))))
10996 (unless (eq action 'sparse-tree) (org-agenda-skip))
10998 ;; select this headline
11000 (cond
11001 ((eq action 'sparse-tree)
11002 (and org-highlight-sparse-tree-matches
11003 (org-get-heading) (match-end 0)
11004 (org-highlight-new-match
11005 (match-beginning 0) (match-beginning 1)))
11006 (org-show-context 'tags-tree))
11007 ((eq action 'agenda)
11008 (setq txt (org-format-agenda-item
11010 (concat
11011 (if (eq org-tags-match-list-sublevels 'indented)
11012 (make-string (1- level) ?.) "")
11013 (org-get-heading))
11014 category
11015 tags-list
11017 priority (org-get-priority txt))
11018 (goto-char lspos)
11019 (setq marker (org-agenda-new-marker))
11020 (org-add-props txt props
11021 'org-marker marker 'org-hd-marker marker 'org-category category
11022 'todo-state todo
11023 'priority priority 'type "tagsmatch")
11024 (push txt rtn))
11025 ((functionp action)
11026 (setq org-map-continue-from nil)
11027 (save-excursion
11028 (setq rtn1 (funcall action))
11029 (push rtn1 rtn)))
11030 (t (error "Invalid action")))
11032 ;; if we are to skip sublevels, jump to end of subtree
11033 (unless org-tags-match-list-sublevels
11034 (org-end-of-subtree t)
11035 (backward-char 1))))
11036 ;; Get the correct position from where to continue
11037 (if org-map-continue-from
11038 (goto-char org-map-continue-from)
11039 (and (= (point) lspos) (end-of-line 1)))))
11040 (when (and (eq action 'sparse-tree)
11041 (not org-sparse-tree-open-archived-trees))
11042 (org-hide-archived-subtrees (point-min) (point-max)))
11043 (nreverse rtn)))
11045 (defun org-remove-uniherited-tags (tags)
11046 "Remove all tags that are not inherited from the list TAGS."
11047 (cond
11048 ((eq org-use-tag-inheritance t)
11049 (if org-tags-exclude-from-inheritance
11050 (org-delete-all org-tags-exclude-from-inheritance tags)
11051 tags))
11052 ((not org-use-tag-inheritance) nil)
11053 ((stringp org-use-tag-inheritance)
11054 (delq nil (mapcar
11055 (lambda (x)
11056 (if (and (string-match org-use-tag-inheritance x)
11057 (not (member x org-tags-exclude-from-inheritance)))
11058 x nil))
11059 tags)))
11060 ((listp org-use-tag-inheritance)
11061 (delq nil (mapcar
11062 (lambda (x)
11063 (if (member x org-use-tag-inheritance) x nil))
11064 tags)))))
11066 (defvar todo-only) ;; dynamically scoped
11068 (defun org-match-sparse-tree (&optional todo-only match)
11069 "Create a sparse tree according to tags string MATCH.
11070 MATCH can contain positive and negative selection of tags, like
11071 \"+WORK+URGENT-WITHBOSS\".
11072 If optional argument TODO-ONLY is non-nil, only select lines that are
11073 also TODO lines."
11074 (interactive "P")
11075 (org-prepare-agenda-buffers (list (current-buffer)))
11076 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11078 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11080 (defvar org-cached-props nil)
11081 (defun org-cached-entry-get (pom property)
11082 (if (or (eq t org-use-property-inheritance)
11083 (and (stringp org-use-property-inheritance)
11084 (string-match org-use-property-inheritance property))
11085 (and (listp org-use-property-inheritance)
11086 (member property org-use-property-inheritance)))
11087 ;; Caching is not possible, check it directly
11088 (org-entry-get pom property 'inherit)
11089 ;; Get all properties, so that we can do complicated checks easily
11090 (cdr (assoc property (or org-cached-props
11091 (setq org-cached-props
11092 (org-entry-properties pom)))))))
11094 (defun org-global-tags-completion-table (&optional files)
11095 "Return the list of all tags in all agenda buffer/files."
11096 (save-excursion
11097 (org-uniquify
11098 (delq nil
11099 (apply 'append
11100 (mapcar
11101 (lambda (file)
11102 (set-buffer (find-file-noselect file))
11103 (append (org-get-buffer-tags)
11104 (mapcar (lambda (x) (if (stringp (car-safe x))
11105 (list (car-safe x)) nil))
11106 org-tag-alist)))
11107 (if (and files (car files))
11108 files
11109 (org-agenda-files))))))))
11111 (defun org-make-tags-matcher (match)
11112 "Create the TAGS//TODO matcher form for the selection string MATCH."
11113 ;; todo-only is scoped dynamically into this function, and the function
11114 ;; may change it if the matcher asks for it.
11115 (unless match
11116 ;; Get a new match request, with completion
11117 (let ((org-last-tags-completion-table
11118 (org-global-tags-completion-table)))
11119 (setq match (org-completing-read-no-i
11120 "Match: " 'org-tags-completion-function nil nil nil
11121 'org-tags-history))))
11123 ;; Parse the string and create a lisp form
11124 (let ((match0 match)
11125 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11126 minus tag mm
11127 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11128 orterms term orlist re-p str-p level-p level-op time-p
11129 prop-p pn pv po cat-p gv rest)
11130 (if (string-match "/+" match)
11131 ;; match contains also a todo-matching request
11132 (progn
11133 (setq tagsmatch (substring match 0 (match-beginning 0))
11134 todomatch (substring match (match-end 0)))
11135 (if (string-match "^!" todomatch)
11136 (setq todo-only t todomatch (substring todomatch 1)))
11137 (if (string-match "^\\s-*$" todomatch)
11138 (setq todomatch nil)))
11139 ;; only matching tags
11140 (setq tagsmatch match todomatch nil))
11142 ;; Make the tags matcher
11143 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11144 (setq tagsmatcher t)
11145 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11146 (while (setq term (pop orterms))
11147 (while (and (equal (substring term -1) "\\") orterms)
11148 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11149 (while (string-match re term)
11150 (setq rest (substring term (match-end 0))
11151 minus (and (match-end 1)
11152 (equal (match-string 1 term) "-"))
11153 tag (match-string 2 term)
11154 re-p (equal (string-to-char tag) ?{)
11155 level-p (match-end 4)
11156 prop-p (match-end 5)
11157 mm (cond
11158 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11159 (level-p
11160 (setq level-op (org-op-to-function (match-string 3 term)))
11161 `(,level-op level ,(string-to-number
11162 (match-string 4 term))))
11163 (prop-p
11164 (setq pn (match-string 5 term)
11165 po (match-string 6 term)
11166 pv (match-string 7 term)
11167 cat-p (equal pn "CATEGORY")
11168 re-p (equal (string-to-char pv) ?{)
11169 str-p (equal (string-to-char pv) ?\")
11170 time-p (save-match-data
11171 (string-match "^\"[[<].*[]>]\"$" pv))
11172 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11173 (if time-p (setq pv (org-matcher-time pv)))
11174 (setq po (org-op-to-function po (if time-p 'time str-p)))
11175 (cond
11176 ((equal pn "CATEGORY")
11177 (setq gv '(get-text-property (point) 'org-category)))
11178 ((equal pn "TODO")
11179 (setq gv 'todo))
11181 (setq gv `(org-cached-entry-get nil ,pn))))
11182 (if re-p
11183 (if (eq po 'org<>)
11184 `(not (string-match ,pv (or ,gv "")))
11185 `(string-match ,pv (or ,gv "")))
11186 (if str-p
11187 `(,po (or ,gv "") ,pv)
11188 `(,po (string-to-number (or ,gv ""))
11189 ,(string-to-number pv) ))))
11190 (t `(member ,tag tags-list)))
11191 mm (if minus (list 'not mm) mm)
11192 term rest)
11193 (push mm tagsmatcher))
11194 (push (if (> (length tagsmatcher) 1)
11195 (cons 'and tagsmatcher)
11196 (car tagsmatcher))
11197 orlist)
11198 (setq tagsmatcher nil))
11199 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11200 (setq tagsmatcher
11201 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11202 ;; Make the todo matcher
11203 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11204 (setq todomatcher t)
11205 (setq orterms (org-split-string todomatch "|") orlist nil)
11206 (while (setq term (pop orterms))
11207 (while (string-match re term)
11208 (setq minus (and (match-end 1)
11209 (equal (match-string 1 term) "-"))
11210 kwd (match-string 2 term)
11211 re-p (equal (string-to-char kwd) ?{)
11212 term (substring term (match-end 0))
11213 mm (if re-p
11214 `(string-match ,(substring kwd 1 -1) todo)
11215 (list 'equal 'todo kwd))
11216 mm (if minus (list 'not mm) mm))
11217 (push mm todomatcher))
11218 (push (if (> (length todomatcher) 1)
11219 (cons 'and todomatcher)
11220 (car todomatcher))
11221 orlist)
11222 (setq todomatcher nil))
11223 (setq todomatcher (if (> (length orlist) 1)
11224 (cons 'or orlist) (car orlist))))
11226 ;; Return the string and lisp forms of the matcher
11227 (setq matcher (if todomatcher
11228 (list 'and tagsmatcher todomatcher)
11229 tagsmatcher))
11230 (cons match0 matcher)))
11232 (defun org-op-to-function (op &optional stringp)
11233 "Turn an operator into the appropriate function."
11234 (setq op
11235 (cond
11236 ((equal op "<" ) '(< string< org-time<))
11237 ((equal op ">" ) '(> org-string> org-time>))
11238 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11239 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11240 ((member op '("=" "==")) '(= string= org-time=))
11241 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11242 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11244 (defun org<> (a b) (not (= a b)))
11245 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11246 (defun org-string>= (a b) (not (string< a b)))
11247 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11248 (defun org-string<> (a b) (not (string= a b)))
11249 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11250 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11251 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11252 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11253 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11254 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11255 (defun org-2ft (s)
11256 "Convert S to a floating point time.
11257 If S is already a number, just return it. If it is a string, parse
11258 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11259 (cond
11260 ((numberp s) s)
11261 ((stringp s)
11262 (condition-case nil
11263 (float-time (apply 'encode-time (org-parse-time-string s)))
11264 (error 0.)))
11265 (t 0.)))
11267 (defun org-time-today ()
11268 "Time in seconds today at 0:00.
11269 Returns the float number of seconds since the beginning of the
11270 epoch to the beginning of today (00:00)."
11271 (float-time (apply 'encode-time
11272 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11274 (defun org-matcher-time (s)
11275 "Interpret a time comparison value."
11276 (save-match-data
11277 (cond
11278 ((string= s "<now>") (float-time))
11279 ((string= s "<today>") (org-time-today))
11280 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11281 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11282 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11283 (+ (org-time-today)
11284 (* (string-to-number (match-string 1 s))
11285 (cdr (assoc (match-string 2 s)
11286 '(("d" . 86400.0) ("w" . 604800.0)
11287 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11288 (t (org-2ft s)))))
11290 (defun org-match-any-p (re list)
11291 "Does re match any element of list?"
11292 (setq list (mapcar (lambda (x) (string-match re x)) list))
11293 (delq nil list))
11295 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11296 (defvar org-tags-overlay (org-make-overlay 1 1))
11297 (org-detach-overlay org-tags-overlay)
11299 (defun org-get-local-tags-at (&optional pos)
11300 "Get a list of tags defined in the current headline."
11301 (org-get-tags-at pos 'local))
11303 (defun org-get-local-tags ()
11304 "Get a list of tags defined in the current headline."
11305 (org-get-tags-at nil 'local))
11307 (defun org-get-tags-at (&optional pos local)
11308 "Get a list of all headline tags applicable at POS.
11309 POS defaults to point. If tags are inherited, the list contains
11310 the targets in the same sequence as the headlines appear, i.e.
11311 the tags of the current headline come last.
11312 When LOCAL is non-nil, only return tags from the current headline,
11313 ignore inherited ones."
11314 (interactive)
11315 (if (and org-trust-scanner-tags
11316 (or (not pos) (equal pos (point)))
11317 (not local))
11318 org-scanner-tags
11319 (let (tags ltags lastpos parent)
11320 (save-excursion
11321 (save-restriction
11322 (widen)
11323 (goto-char (or pos (point)))
11324 (save-match-data
11325 (catch 'done
11326 (condition-case nil
11327 (progn
11328 (org-back-to-heading t)
11329 (while (not (equal lastpos (point)))
11330 (setq lastpos (point))
11331 (when (looking-at
11332 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11333 (setq ltags (org-split-string
11334 (org-match-string-no-properties 1) ":"))
11335 (when parent
11336 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11337 (setq tags (append
11338 (if parent
11339 (org-remove-uniherited-tags ltags)
11340 ltags)
11341 tags)))
11342 (or org-use-tag-inheritance (throw 'done t))
11343 (if local (throw 'done t))
11344 (or (org-up-heading-safe) (error nil))
11345 (setq parent t)))
11346 (error nil)))))
11347 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11349 (defun org-add-prop-inherited (s)
11350 (add-text-properties 0 (length s) '(inherited t) s)
11353 (defun org-toggle-tag (tag &optional onoff)
11354 "Toggle the tag TAG for the current line.
11355 If ONOFF is `on' or `off', don't toggle but set to this state."
11356 (let (res current)
11357 (save-excursion
11358 (org-back-to-heading t)
11359 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11360 (point-at-eol) t)
11361 (progn
11362 (setq current (match-string 1))
11363 (replace-match ""))
11364 (setq current ""))
11365 (setq current (nreverse (org-split-string current ":")))
11366 (cond
11367 ((eq onoff 'on)
11368 (setq res t)
11369 (or (member tag current) (push tag current)))
11370 ((eq onoff 'off)
11371 (or (not (member tag current)) (setq current (delete tag current))))
11372 (t (if (member tag current)
11373 (setq current (delete tag current))
11374 (setq res t)
11375 (push tag current))))
11376 (end-of-line 1)
11377 (if current
11378 (progn
11379 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11380 (org-set-tags nil t))
11381 (delete-horizontal-space))
11382 (run-hooks 'org-after-tags-change-hook))
11383 res))
11385 (defun org-align-tags-here (to-col)
11386 ;; Assumes that this is a headline
11387 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11388 (beginning-of-line 1)
11389 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11390 (< pos (match-beginning 2)))
11391 (progn
11392 (setq tags-l (- (match-end 2) (match-beginning 2)))
11393 (goto-char (match-beginning 1))
11394 (insert " ")
11395 (delete-region (point) (1+ (match-beginning 2)))
11396 (setq ncol (max (1+ (current-column))
11397 (1+ col)
11398 (if (> to-col 0)
11399 to-col
11400 (- (abs to-col) tags-l))))
11401 (setq p (point))
11402 (insert (make-string (- ncol (current-column)) ?\ ))
11403 (setq ncol (current-column))
11404 (when indent-tabs-mode (tabify p (point-at-eol)))
11405 (org-move-to-column (min ncol col) t))
11406 (goto-char pos))))
11408 (defun org-set-tags-command (&optional arg just-align)
11409 "Call the set-tags command for the current entry."
11410 (interactive "P")
11411 (if (org-on-heading-p)
11412 (org-set-tags arg just-align)
11413 (save-excursion
11414 (org-back-to-heading t)
11415 (org-set-tags arg just-align))))
11417 (defun org-set-tags-to (data)
11418 "Set the tags of the current entry to DATA, replacing the current tags.
11419 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11420 If DATA is nil or the empty string, any tags will be removed."
11421 (interactive "sTags: ")
11422 (setq data
11423 (cond
11424 ((eq data nil) "")
11425 ((equal data "") "")
11426 ((stringp data)
11427 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11428 ":"))
11429 ((listp data)
11430 (concat ":" (mapconcat 'identity data ":") ":"))
11431 (t nil)))
11432 (when data
11433 (save-excursion
11434 (org-back-to-heading t)
11435 (when (looking-at org-complex-heading-regexp)
11436 (if (match-end 5)
11437 (progn
11438 (goto-char (match-beginning 5))
11439 (insert data)
11440 (delete-region (point) (point-at-eol))
11441 (org-set-tags nil 'align))
11442 (goto-char (point-at-eol))
11443 (insert " " data)
11444 (org-set-tags nil 'align)))
11445 (beginning-of-line 1)
11446 (if (looking-at ".*?\\([ \t]+\\)$")
11447 (delete-region (match-beginning 1) (match-end 1))))))
11449 (defun org-set-tags (&optional arg just-align)
11450 "Set the tags for the current headline.
11451 With prefix ARG, realign all tags in headings in the current buffer."
11452 (interactive "P")
11453 (let* ((re (concat "^" outline-regexp))
11454 (current (org-get-tags-string))
11455 (col (current-column))
11456 (org-setting-tags t)
11457 table current-tags inherited-tags ; computed below when needed
11458 tags p0 c0 c1 rpl)
11459 (if arg
11460 (save-excursion
11461 (goto-char (point-min))
11462 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11463 (while (re-search-forward re nil t)
11464 (org-set-tags nil t)
11465 (end-of-line 1)))
11466 (message "All tags realigned to column %d" org-tags-column))
11467 (if just-align
11468 (setq tags current)
11469 ;; Get a new set of tags from the user
11470 (save-excursion
11471 (setq table (append org-tag-persistent-alist
11472 (or org-tag-alist (org-get-buffer-tags)))
11473 org-last-tags-completion-table table
11474 current-tags (org-split-string current ":")
11475 inherited-tags (nreverse
11476 (nthcdr (length current-tags)
11477 (nreverse (org-get-tags-at))))
11478 tags
11479 (if (or (eq t org-use-fast-tag-selection)
11480 (and org-use-fast-tag-selection
11481 (delq nil (mapcar 'cdr table))))
11482 (org-fast-tag-selection
11483 current-tags inherited-tags table
11484 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11485 (let ((org-add-colon-after-tag-completion t))
11486 (org-trim
11487 (org-without-partial-completion
11488 (org-icompleting-read "Tags: " 'org-tags-completion-function
11489 nil nil current 'org-tags-history)))))))
11490 (while (string-match "[-+&]+" tags)
11491 ;; No boolean logic, just a list
11492 (setq tags (replace-match ":" t t tags))))
11494 (if org-tags-sort-function
11495 (setq tags (mapconcat 'identity
11496 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11497 org-tags-sort-function) ":")))
11499 (if (string-match "\\`[\t ]*\\'" tags)
11500 (setq tags "")
11501 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11502 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11504 ;; Insert new tags at the correct column
11505 (beginning-of-line 1)
11506 (cond
11507 ((and (equal current "") (equal tags "")))
11508 ((re-search-forward
11509 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11510 (point-at-eol) t)
11511 (if (equal tags "")
11512 (setq rpl "")
11513 (goto-char (match-beginning 0))
11514 (setq c0 (current-column) p0 (point)
11515 c1 (max (1+ c0) (if (> org-tags-column 0)
11516 org-tags-column
11517 (- (- org-tags-column) (length tags))))
11518 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11519 (replace-match rpl t t)
11520 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11521 tags)
11522 (t (error "Tags alignment failed")))
11523 (org-move-to-column col)
11524 (unless just-align
11525 (run-hooks 'org-after-tags-change-hook)))))
11527 (defun org-change-tag-in-region (beg end tag off)
11528 "Add or remove TAG for each entry in the region.
11529 This works in the agenda, and also in an org-mode buffer."
11530 (interactive
11531 (list (region-beginning) (region-end)
11532 (let ((org-last-tags-completion-table
11533 (if (org-mode-p)
11534 (org-get-buffer-tags)
11535 (org-global-tags-completion-table))))
11536 (org-icompleting-read
11537 "Tag: " 'org-tags-completion-function nil nil nil
11538 'org-tags-history))
11539 (progn
11540 (message "[s]et or [r]emove? ")
11541 (equal (read-char-exclusive) ?r))))
11542 (if (fboundp 'deactivate-mark) (deactivate-mark))
11543 (let ((agendap (equal major-mode 'org-agenda-mode))
11544 l1 l2 m buf pos newhead (cnt 0))
11545 (goto-char end)
11546 (setq l2 (1- (org-current-line)))
11547 (goto-char beg)
11548 (setq l1 (org-current-line))
11549 (loop for l from l1 to l2 do
11550 (org-goto-line l)
11551 (setq m (get-text-property (point) 'org-hd-marker))
11552 (when (or (and (org-mode-p) (org-on-heading-p))
11553 (and agendap m))
11554 (setq buf (if agendap (marker-buffer m) (current-buffer))
11555 pos (if agendap m (point)))
11556 (with-current-buffer buf
11557 (save-excursion
11558 (save-restriction
11559 (goto-char pos)
11560 (setq cnt (1+ cnt))
11561 (org-toggle-tag tag (if off 'off 'on))
11562 (setq newhead (org-get-heading)))))
11563 (and agendap (org-agenda-change-all-lines newhead m))))
11564 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11566 (defun org-tags-completion-function (string predicate &optional flag)
11567 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11568 (confirm (lambda (x) (stringp (car x)))))
11569 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11570 (setq s1 (match-string 1 string)
11571 s2 (match-string 2 string))
11572 (setq s1 "" s2 string))
11573 (cond
11574 ((eq flag nil)
11575 ;; try completion
11576 (setq rtn (try-completion s2 ctable confirm))
11577 (if (stringp rtn)
11578 (setq rtn
11579 (concat s1 s2 (substring rtn (length s2))
11580 (if (and org-add-colon-after-tag-completion
11581 (assoc rtn ctable))
11582 ":" ""))))
11583 rtn)
11584 ((eq flag t)
11585 ;; all-completions
11586 (all-completions s2 ctable confirm)
11588 ((eq flag 'lambda)
11589 ;; exact match?
11590 (assoc s2 ctable)))
11593 (defun org-fast-tag-insert (kwd tags face &optional end)
11594 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11595 (insert (format "%-12s" (concat kwd ":"))
11596 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11597 (or end "")))
11599 (defun org-fast-tag-show-exit (flag)
11600 (save-excursion
11601 (org-goto-line 3)
11602 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11603 (replace-match ""))
11604 (when flag
11605 (end-of-line 1)
11606 (org-move-to-column (- (window-width) 19) t)
11607 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11609 (defun org-set-current-tags-overlay (current prefix)
11610 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11611 (if (featurep 'xemacs)
11612 (org-overlay-display org-tags-overlay (concat prefix s)
11613 'secondary-selection)
11614 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11615 (org-overlay-display org-tags-overlay (concat prefix s)))))
11617 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11618 "Fast tag selection with single keys.
11619 CURRENT is the current list of tags in the headline, INHERITED is the
11620 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11621 possibly with grouping information. TODO-TABLE is a similar table with
11622 TODO keywords, should these have keys assigned to them.
11623 If the keys are nil, a-z are automatically assigned.
11624 Returns the new tags string, or nil to not change the current settings."
11625 (let* ((fulltable (append table todo-table))
11626 (maxlen (apply 'max (mapcar
11627 (lambda (x)
11628 (if (stringp (car x)) (string-width (car x)) 0))
11629 fulltable)))
11630 (buf (current-buffer))
11631 (expert (eq org-fast-tag-selection-single-key 'expert))
11632 (buffer-tags nil)
11633 (fwidth (+ maxlen 3 1 3))
11634 (ncol (/ (- (window-width) 4) fwidth))
11635 (i-face 'org-done)
11636 (c-face 'org-todo)
11637 tg cnt e c char c1 c2 ntable tbl rtn
11638 ov-start ov-end ov-prefix
11639 (exit-after-next org-fast-tag-selection-single-key)
11640 (done-keywords org-done-keywords)
11641 groups ingroup)
11642 (save-excursion
11643 (beginning-of-line 1)
11644 (if (looking-at
11645 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11646 (setq ov-start (match-beginning 1)
11647 ov-end (match-end 1)
11648 ov-prefix "")
11649 (setq ov-start (1- (point-at-eol))
11650 ov-end (1+ ov-start))
11651 (skip-chars-forward "^\n\r")
11652 (setq ov-prefix
11653 (concat
11654 (buffer-substring (1- (point)) (point))
11655 (if (> (current-column) org-tags-column)
11657 (make-string (- org-tags-column (current-column)) ?\ ))))))
11658 (org-move-overlay org-tags-overlay ov-start ov-end)
11659 (save-window-excursion
11660 (if expert
11661 (set-buffer (get-buffer-create " *Org tags*"))
11662 (delete-other-windows)
11663 (split-window-vertically)
11664 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11665 (erase-buffer)
11666 (org-set-local 'org-done-keywords done-keywords)
11667 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11668 (org-fast-tag-insert "Current" current c-face "\n\n")
11669 (org-fast-tag-show-exit exit-after-next)
11670 (org-set-current-tags-overlay current ov-prefix)
11671 (setq tbl fulltable char ?a cnt 0)
11672 (while (setq e (pop tbl))
11673 (cond
11674 ((equal (car e) :startgroup)
11675 (push '() groups) (setq ingroup t)
11676 (when (not (= cnt 0))
11677 (setq cnt 0)
11678 (insert "\n"))
11679 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11680 ((equal (car e) :endgroup)
11681 (setq ingroup nil cnt 0)
11682 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11683 ((equal e '(:newline))
11684 (when (not (= cnt 0))
11685 (setq cnt 0)
11686 (insert "\n")
11687 (setq e (car tbl))
11688 (while (equal (car tbl) '(:newline))
11689 (insert "\n")
11690 (setq tbl (cdr tbl)))))
11692 (setq tg (copy-sequence (car e)) c2 nil)
11693 (if (cdr e)
11694 (setq c (cdr e))
11695 ;; automatically assign a character.
11696 (setq c1 (string-to-char
11697 (downcase (substring
11698 tg (if (= (string-to-char tg) ?@) 1 0)))))
11699 (if (or (rassoc c1 ntable) (rassoc c1 table))
11700 (while (or (rassoc char ntable) (rassoc char table))
11701 (setq char (1+ char)))
11702 (setq c2 c1))
11703 (setq c (or c2 char)))
11704 (if ingroup (push tg (car groups)))
11705 (setq tg (org-add-props tg nil 'face
11706 (cond
11707 ((not (assoc tg table))
11708 (org-get-todo-face tg))
11709 ((member tg current) c-face)
11710 ((member tg inherited) i-face)
11711 (t nil))))
11712 (if (and (= cnt 0) (not ingroup)) (insert " "))
11713 (insert "[" c "] " tg (make-string
11714 (- fwidth 4 (length tg)) ?\ ))
11715 (push (cons tg c) ntable)
11716 (when (= (setq cnt (1+ cnt)) ncol)
11717 (insert "\n")
11718 (if ingroup (insert " "))
11719 (setq cnt 0)))))
11720 (setq ntable (nreverse ntable))
11721 (insert "\n")
11722 (goto-char (point-min))
11723 (if (not expert) (org-fit-window-to-buffer))
11724 (setq rtn
11725 (catch 'exit
11726 (while t
11727 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11728 (if (not groups) "no " "")
11729 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11730 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11731 (cond
11732 ((= c ?\r) (throw 'exit t))
11733 ((= c ?!)
11734 (setq groups (not groups))
11735 (goto-char (point-min))
11736 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11737 ((= c ?\C-c)
11738 (if (not expert)
11739 (org-fast-tag-show-exit
11740 (setq exit-after-next (not exit-after-next)))
11741 (setq expert nil)
11742 (delete-other-windows)
11743 (split-window-vertically)
11744 (org-switch-to-buffer-other-window " *Org tags*")
11745 (org-fit-window-to-buffer)))
11746 ((or (= c ?\C-g)
11747 (and (= c ?q) (not (rassoc c ntable))))
11748 (org-detach-overlay org-tags-overlay)
11749 (setq quit-flag t))
11750 ((= c ?\ )
11751 (setq current nil)
11752 (if exit-after-next (setq exit-after-next 'now)))
11753 ((= c ?\t)
11754 (condition-case nil
11755 (setq tg (org-icompleting-read
11756 "Tag: "
11757 (or buffer-tags
11758 (with-current-buffer buf
11759 (org-get-buffer-tags)))))
11760 (quit (setq tg "")))
11761 (when (string-match "\\S-" tg)
11762 (add-to-list 'buffer-tags (list tg))
11763 (if (member tg current)
11764 (setq current (delete tg current))
11765 (push tg current)))
11766 (if exit-after-next (setq exit-after-next 'now)))
11767 ((setq e (rassoc c todo-table) tg (car e))
11768 (with-current-buffer buf
11769 (save-excursion (org-todo tg)))
11770 (if exit-after-next (setq exit-after-next 'now)))
11771 ((setq e (rassoc c ntable) tg (car e))
11772 (if (member tg current)
11773 (setq current (delete tg current))
11774 (loop for g in groups do
11775 (if (member tg g)
11776 (mapc (lambda (x)
11777 (setq current (delete x current)))
11778 g)))
11779 (push tg current))
11780 (if exit-after-next (setq exit-after-next 'now))))
11782 ;; Create a sorted list
11783 (setq current
11784 (sort current
11785 (lambda (a b)
11786 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11787 (if (eq exit-after-next 'now) (throw 'exit t))
11788 (goto-char (point-min))
11789 (beginning-of-line 2)
11790 (delete-region (point) (point-at-eol))
11791 (org-fast-tag-insert "Current" current c-face)
11792 (org-set-current-tags-overlay current ov-prefix)
11793 (while (re-search-forward
11794 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11795 (setq tg (match-string 1))
11796 (add-text-properties
11797 (match-beginning 1) (match-end 1)
11798 (list 'face
11799 (cond
11800 ((member tg current) c-face)
11801 ((member tg inherited) i-face)
11802 (t (get-text-property (match-beginning 1) 'face))))))
11803 (goto-char (point-min)))))
11804 (org-detach-overlay org-tags-overlay)
11805 (if rtn
11806 (mapconcat 'identity current ":")
11807 nil))))
11809 (defun org-get-tags-string ()
11810 "Get the TAGS string in the current headline."
11811 (unless (org-on-heading-p t)
11812 (error "Not on a heading"))
11813 (save-excursion
11814 (beginning-of-line 1)
11815 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11816 (org-match-string-no-properties 1)
11817 "")))
11819 (defun org-get-tags ()
11820 "Get the list of tags specified in the current headline."
11821 (org-split-string (org-get-tags-string) ":"))
11823 (defun org-get-buffer-tags ()
11824 "Get a table of all tags used in the buffer, for completion."
11825 (let (tags)
11826 (save-excursion
11827 (goto-char (point-min))
11828 (while (re-search-forward
11829 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11830 (when (equal (char-after (point-at-bol 0)) ?*)
11831 (mapc (lambda (x) (add-to-list 'tags x))
11832 (org-split-string (org-match-string-no-properties 1) ":")))))
11833 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
11834 (mapcar 'list tags)))
11836 ;;;; The mapping API
11838 ;;;###autoload
11839 (defun org-map-entries (func &optional match scope &rest skip)
11840 "Call FUNC at each headline selected by MATCH in SCOPE.
11842 FUNC is a function or a lisp form. The function will be called without
11843 arguments, with the cursor positioned at the beginning of the headline.
11844 The return values of all calls to the function will be collected and
11845 returned as a list.
11847 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11848 does not need to preserve point. After evaluation, the cursor will be
11849 moved to the end of the line (presumably of the headline of the
11850 processed entry) and search continues from there. Under some
11851 circumstances, this may not produce the wanted results. For example,
11852 if you have removed (e.g. archived) the current (sub)tree it could
11853 mean that the next entry will be skipped entirely. In such cases, you
11854 can specify the position from where search should continue by making
11855 FUNC set the variable `org-map-continue-from' to the desired buffer
11856 position.
11858 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11859 Only headlines that are matched by this query will be considered during
11860 the iteration. When MATCH is nil or t, all headlines will be
11861 visited by the iteration.
11863 SCOPE determines the scope of this command. It can be any of:
11865 nil The current buffer, respecting the restriction if any
11866 tree The subtree started with the entry at point
11867 file The current buffer, without restriction
11868 file-with-archives
11869 The current buffer, and any archives associated with it
11870 agenda All agenda files
11871 agenda-with-archives
11872 All agenda files with any archive files associated with them
11873 \(file1 file2 ...)
11874 If this is a list, all files in the list will be scanned
11876 The remaining args are treated as settings for the skipping facilities of
11877 the scanner. The following items can be given here:
11879 archive skip trees with the archive tag.
11880 comment skip trees with the COMMENT keyword
11881 function or Emacs Lisp form:
11882 will be used as value for `org-agenda-skip-function', so whenever
11883 the function returns t, FUNC will not be called for that
11884 entry and search will continue from the point where the
11885 function leaves it.
11887 If your function needs to retrieve the tags including inherited tags
11888 at the *current* entry, you can use the value of the variable
11889 `org-scanner-tags' which will be much faster than getting the value
11890 with `org-get-tags-at'. If your function gets properties with
11891 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11892 to t around the call to `org-entry-properties' to get the same speedup.
11893 Note that if your function moves around to retrieve tags and properties at
11894 a *different* entry, you cannot use these techniques."
11895 (let* ((org-agenda-archives-mode nil) ; just to make sure
11896 (org-agenda-skip-archived-trees (memq 'archive skip))
11897 (org-agenda-skip-comment-trees (memq 'comment skip))
11898 (org-agenda-skip-function
11899 (car (org-delete-all '(comment archive) skip)))
11900 (org-tags-match-list-sublevels t)
11901 matcher file res
11902 org-todo-keywords-for-agenda
11903 org-done-keywords-for-agenda
11904 org-todo-keyword-alist-for-agenda
11905 org-drawers-for-agenda
11906 org-tag-alist-for-agenda)
11908 (cond
11909 ((eq match t) (setq matcher t))
11910 ((eq match nil) (setq matcher t))
11911 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11913 (save-excursion
11914 (save-restriction
11915 (when (eq scope 'tree)
11916 (org-back-to-heading t)
11917 (org-narrow-to-subtree)
11918 (setq scope nil))
11920 (if (not scope)
11921 (progn
11922 (org-prepare-agenda-buffers
11923 (list (buffer-file-name (current-buffer))))
11924 (setq res (org-scan-tags func matcher)))
11925 ;; Get the right scope
11926 (cond
11927 ((and scope (listp scope) (symbolp (car scope)))
11928 (setq scope (eval scope)))
11929 ((eq scope 'agenda)
11930 (setq scope (org-agenda-files t)))
11931 ((eq scope 'agenda-with-archives)
11932 (setq scope (org-agenda-files t))
11933 (setq scope (org-add-archive-files scope)))
11934 ((eq scope 'file)
11935 (setq scope (list (buffer-file-name))))
11936 ((eq scope 'file-with-archives)
11937 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11938 (org-prepare-agenda-buffers scope)
11939 (while (setq file (pop scope))
11940 (with-current-buffer (org-find-base-buffer-visiting file)
11941 (save-excursion
11942 (save-restriction
11943 (widen)
11944 (goto-char (point-min))
11945 (setq res (append res (org-scan-tags func matcher))))))))))
11946 res))
11948 ;;;; Properties
11950 ;;; Setting and retrieving properties
11952 (defconst org-special-properties
11953 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11954 "TIMESTAMP" "TIMESTAMP_IA")
11955 "The special properties valid in Org-mode.
11957 These are properties that are not defined in the property drawer,
11958 but in some other way.")
11960 (defconst org-default-properties
11961 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11962 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11963 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11964 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11965 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11966 "CLOCK_MODELINE_TOTAL" "STYLE")
11967 "Some properties that are used by Org-mode for various purposes.
11968 Being in this list makes sure that they are offered for completion.")
11970 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11971 "Regular expression matching the first line of a property drawer.")
11973 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11974 "Regular expression matching the first line of a property drawer.")
11976 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11977 "Regular expression matching the first line of a property drawer.")
11979 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11980 "Regular expression matching the first line of a property drawer.")
11982 (defconst org-property-drawer-re
11983 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11984 org-property-end-re "\\)\n?")
11985 "Matches an entire property drawer.")
11987 (defconst org-clock-drawer-re
11988 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11989 org-property-end-re "\\)\n?")
11990 "Matches an entire clock drawer.")
11992 (defun org-property-action ()
11993 "Do an action on properties."
11994 (interactive)
11995 (let (c)
11996 (org-at-property-p)
11997 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11998 (setq c (read-char-exclusive))
11999 (cond
12000 ((equal c ?s)
12001 (call-interactively 'org-set-property))
12002 ((equal c ?d)
12003 (call-interactively 'org-delete-property))
12004 ((equal c ?D)
12005 (call-interactively 'org-delete-property-globally))
12006 ((equal c ?c)
12007 (call-interactively 'org-compute-property-at-point))
12008 (t (error "No such property action %c" c)))))
12010 (defun org-set-effort (&optional value)
12011 "Set the effort property of the current entry.
12012 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12013 allowed value."
12014 (interactive "P")
12015 (if (equal value 0) (setq value 10))
12016 (let* ((completion-ignore-case t)
12017 (prop org-effort-property)
12018 (cur (org-entry-get nil prop))
12019 (allowed (org-property-get-allowed-values nil prop 'table))
12020 (existing (mapcar 'list (org-property-values prop)))
12021 (val (cond
12022 ((stringp value) value)
12023 ((and allowed (integerp value))
12024 (or (car (nth (1- value) allowed))
12025 (car (org-last allowed))))
12026 (allowed
12027 (org-completing-read "Value: " allowed nil 'req-match))
12029 (let (org-completion-use-ido org-completion-use-iswitchb)
12030 (org-completing-read
12031 (concat "Value " (if (and cur (string-match "\\S-" cur))
12032 (concat "[" cur "]") "")
12033 ": ")
12034 existing nil nil "" nil cur))))))
12035 (unless (equal (org-entry-get nil prop) val)
12036 (org-entry-put nil prop val))
12037 (message "%s is now %s" prop val)))
12039 (defun org-at-property-p ()
12040 "Is the cursor in a property line?"
12041 ;; FIXME: Does not check if we are actually in the drawer.
12042 ;; FIXME: also returns true on any drawers.....
12043 ;; This is used by C-c C-c for property action.
12044 (save-excursion
12045 (beginning-of-line 1)
12046 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12048 (defun org-get-property-block (&optional beg end force)
12049 "Return the (beg . end) range of the body of the property drawer.
12050 BEG and END can be beginning and end of subtree, if not given
12051 they will be found.
12052 If the drawer does not exist and FORCE is non-nil, create the drawer."
12053 (catch 'exit
12054 (save-excursion
12055 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12056 (end (or end (progn (outline-next-heading) (point)))))
12057 (goto-char beg)
12058 (if (re-search-forward org-property-start-re end t)
12059 (setq beg (1+ (match-end 0)))
12060 (if force
12061 (save-excursion
12062 (org-insert-property-drawer)
12063 (setq end (progn (outline-next-heading) (point))))
12064 (throw 'exit nil))
12065 (goto-char beg)
12066 (if (re-search-forward org-property-start-re end t)
12067 (setq beg (1+ (match-end 0)))))
12068 (if (re-search-forward org-property-end-re end t)
12069 (setq end (match-beginning 0))
12070 (or force (throw 'exit nil))
12071 (goto-char beg)
12072 (setq end beg)
12073 (org-indent-line-function)
12074 (insert ":END:\n"))
12075 (cons beg end)))))
12077 (defun org-entry-properties (&optional pom which)
12078 "Get all properties of the entry at point-or-marker POM.
12079 This includes the TODO keyword, the tags, time strings for deadline,
12080 scheduled, and clocking, and any additional properties defined in the
12081 entry. The return value is an alist, keys may occur multiple times
12082 if the property key was used several times.
12083 POM may also be nil, in which case the current entry is used.
12084 If WHICH is nil or `all', get all properties. If WHICH is
12085 `special' or `standard', only get that subclass."
12086 (setq which (or which 'all))
12087 (org-with-point-at pom
12088 (let ((clockstr (substring org-clock-string 0 -1))
12089 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12090 beg end range props sum-props key value string clocksum)
12091 (save-excursion
12092 (when (condition-case nil
12093 (and (org-mode-p) (org-back-to-heading t))
12094 (error nil))
12095 (setq beg (point))
12096 (setq sum-props (get-text-property (point) 'org-summaries))
12097 (setq clocksum (get-text-property (point) :org-clock-minutes))
12098 (outline-next-heading)
12099 (setq end (point))
12100 (when (memq which '(all special))
12101 ;; Get the special properties, like TODO and tags
12102 (goto-char beg)
12103 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12104 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12105 (when (looking-at org-priority-regexp)
12106 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12107 (when (and (setq value (org-get-tags-string))
12108 (string-match "\\S-" value))
12109 (push (cons "TAGS" value) props))
12110 (when (setq value (org-get-tags-at))
12111 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12112 props))
12113 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12114 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12115 string (if (equal key clockstr)
12116 (org-no-properties
12117 (org-trim
12118 (buffer-substring
12119 (match-beginning 3) (goto-char (point-at-eol)))))
12120 (substring (org-match-string-no-properties 3) 1 -1)))
12121 (unless key
12122 (if (= (char-after (match-beginning 3)) ?\[)
12123 (setq key "TIMESTAMP_IA")
12124 (setq key "TIMESTAMP")))
12125 (when (or (equal key clockstr) (not (assoc key props)))
12126 (push (cons key string) props)))
12130 (when (memq which '(all standard))
12131 ;; Get the standard properties, like :PROP: ...
12132 (setq range (org-get-property-block beg end))
12133 (when range
12134 (goto-char (car range))
12135 (while (re-search-forward
12136 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12137 (cdr range) t)
12138 (setq key (org-match-string-no-properties 1)
12139 value (org-trim (or (org-match-string-no-properties 2) "")))
12140 (unless (member key excluded)
12141 (push (cons key (or value "")) props)))))
12142 (if clocksum
12143 (push (cons "CLOCKSUM"
12144 (org-columns-number-to-string (/ (float clocksum) 60.)
12145 'add_times))
12146 props))
12147 (unless (assoc "CATEGORY" props)
12148 (setq value (or (org-get-category)
12149 (progn (org-refresh-category-properties)
12150 (org-get-category))))
12151 (push (cons "CATEGORY" value) props))
12152 (append sum-props (nreverse props)))))))
12154 (defun org-entry-get (pom property &optional inherit)
12155 "Get value of PROPERTY for entry at point-or-marker POM.
12156 If INHERIT is non-nil and the entry does not have the property,
12157 then also check higher levels of the hierarchy.
12158 If INHERIT is the symbol `selective', use inheritance only if the setting
12159 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12160 If the property is present but empty, the return value is the empty string.
12161 If the property is not present at all, nil is returned."
12162 (org-with-point-at pom
12163 (if (and inherit (if (eq inherit 'selective)
12164 (org-property-inherit-p property)
12166 (org-entry-get-with-inheritance property)
12167 (if (member property org-special-properties)
12168 ;; We need a special property. Use brute force, get all properties.
12169 (cdr (assoc property (org-entry-properties nil 'special)))
12170 (let ((range (org-get-property-block)))
12171 (if (and range
12172 (goto-char (car range))
12173 (re-search-forward
12174 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12175 (cdr range) t))
12176 ;; Found the property, return it.
12177 (if (match-end 1)
12178 (org-match-string-no-properties 1)
12179 "")))))))
12181 (defun org-property-or-variable-value (var &optional inherit)
12182 "Check if there is a property fixing the value of VAR.
12183 If yes, return this value. If not, return the current value of the variable."
12184 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12185 (if (and prop (stringp prop) (string-match "\\S-" prop))
12186 (read prop)
12187 (symbol-value var))))
12189 (defun org-entry-delete (pom property)
12190 "Delete the property PROPERTY from entry at point-or-marker POM."
12191 (org-with-point-at pom
12192 (if (member property org-special-properties)
12193 nil ; cannot delete these properties.
12194 (let ((range (org-get-property-block)))
12195 (if (and range
12196 (goto-char (car range))
12197 (re-search-forward
12198 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12199 (cdr range) t))
12200 (progn
12201 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12203 nil)))))
12205 ;; Multi-values properties are properties that contain multiple values
12206 ;; These values are assumed to be single words, separated by whitespace.
12207 (defun org-entry-add-to-multivalued-property (pom property value)
12208 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12209 (let* ((old (org-entry-get pom property))
12210 (values (and old (org-split-string old "[ \t]"))))
12211 (setq value (org-entry-protect-space value))
12212 (unless (member value values)
12213 (setq values (cons value values))
12214 (org-entry-put pom property
12215 (mapconcat 'identity values " ")))))
12217 (defun org-entry-remove-from-multivalued-property (pom property value)
12218 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12219 (let* ((old (org-entry-get pom property))
12220 (values (and old (org-split-string old "[ \t]"))))
12221 (setq value (org-entry-protect-space value))
12222 (when (member value values)
12223 (setq values (delete value values))
12224 (org-entry-put pom property
12225 (mapconcat 'identity values " ")))))
12227 (defun org-entry-member-in-multivalued-property (pom property value)
12228 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12229 (let* ((old (org-entry-get pom property))
12230 (values (and old (org-split-string old "[ \t]"))))
12231 (setq value (org-entry-protect-space value))
12232 (member value values)))
12234 (defun org-entry-get-multivalued-property (pom property)
12235 "Return a list of values in a multivalued property."
12236 (let* ((value (org-entry-get pom property))
12237 (values (and value (org-split-string value "[ \t]"))))
12238 (mapcar 'org-entry-restore-space values)))
12240 (defun org-entry-put-multivalued-property (pom property &rest values)
12241 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12242 VALUES should be a list of strings. Spaces will be protected."
12243 (org-entry-put pom property
12244 (mapconcat 'org-entry-protect-space values " "))
12245 (let* ((value (org-entry-get pom property))
12246 (values (and value (org-split-string value "[ \t]"))))
12247 (mapcar 'org-entry-restore-space values)))
12249 (defun org-entry-protect-space (s)
12250 "Protect spaces and newline in string S."
12251 (while (string-match " " s)
12252 (setq s (replace-match "%20" t t s)))
12253 (while (string-match "\n" s)
12254 (setq s (replace-match "%0A" t t s)))
12257 (defun org-entry-restore-space (s)
12258 "Restore spaces and newline in string S."
12259 (while (string-match "%20" s)
12260 (setq s (replace-match " " t t s)))
12261 (while (string-match "%0A" s)
12262 (setq s (replace-match "\n" t t s)))
12265 (defvar org-entry-property-inherited-from (make-marker)
12266 "Marker pointing to the entry from where a property was inherited.
12267 Each call to `org-entry-get-with-inheritance' will set this marker to the
12268 location of the entry where the inheritance search matched. If there was
12269 no match, the marker will point nowhere.
12270 Note that also `org-entry-get' calls this function, if the INHERIT flag
12271 is set.")
12273 (defun org-entry-get-with-inheritance (property)
12274 "Get entry property, and search higher levels if not present."
12275 (move-marker org-entry-property-inherited-from nil)
12276 (let (tmp)
12277 (save-excursion
12278 (save-restriction
12279 (widen)
12280 (catch 'ex
12281 (while t
12282 (when (setq tmp (org-entry-get nil property))
12283 (org-back-to-heading t)
12284 (move-marker org-entry-property-inherited-from (point))
12285 (throw 'ex tmp))
12286 (or (org-up-heading-safe) (throw 'ex nil)))))
12287 (or tmp
12288 (cdr (assoc property org-file-properties))
12289 (cdr (assoc property org-global-properties))
12290 (cdr (assoc property org-global-properties-fixed))))))
12292 (defun org-entry-put (pom property value)
12293 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12294 (org-with-point-at pom
12295 (org-back-to-heading t)
12296 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12297 range)
12298 (cond
12299 ((equal property "TODO")
12300 (when (and (stringp value) (string-match "\\S-" value)
12301 (not (member value org-todo-keywords-1)))
12302 (error "\"%s\" is not a valid TODO state" value))
12303 (if (or (not value)
12304 (not (string-match "\\S-" value)))
12305 (setq value 'none))
12306 (org-todo value)
12307 (org-set-tags nil 'align))
12308 ((equal property "PRIORITY")
12309 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12310 (string-to-char value) ?\ ))
12311 (org-set-tags nil 'align))
12312 ((equal property "SCHEDULED")
12313 (if (re-search-forward org-scheduled-time-regexp end t)
12314 (cond
12315 ((eq value 'earlier) (org-timestamp-change -1 'day))
12316 ((eq value 'later) (org-timestamp-change 1 'day))
12317 (t (call-interactively 'org-schedule)))
12318 (call-interactively 'org-schedule)))
12319 ((equal property "DEADLINE")
12320 (if (re-search-forward org-deadline-time-regexp end t)
12321 (cond
12322 ((eq value 'earlier) (org-timestamp-change -1 'day))
12323 ((eq value 'later) (org-timestamp-change 1 'day))
12324 (t (call-interactively 'org-deadline)))
12325 (call-interactively 'org-deadline)))
12326 ((member property org-special-properties)
12327 (error "The %s property can not yet be set with `org-entry-put'"
12328 property))
12329 (t ; a non-special property
12330 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12331 (setq range (org-get-property-block beg end 'force))
12332 (goto-char (car range))
12333 (if (re-search-forward
12334 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12335 (progn
12336 (delete-region (match-beginning 1) (match-end 1))
12337 (goto-char (match-beginning 1)))
12338 (goto-char (cdr range))
12339 (insert "\n")
12340 (backward-char 1)
12341 (org-indent-line-function)
12342 (insert ":" property ":"))
12343 (and value (insert " " value))
12344 (org-indent-line-function)))))))
12346 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12347 "Get all property keys in the current buffer.
12348 With INCLUDE-SPECIALS, also list the special properties that reflect things
12349 like tags and TODO state.
12350 With INCLUDE-DEFAULTS, also include properties that has special meaning
12351 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12352 With INCLUDE-COLUMNS, also include property names given in COLUMN
12353 formats in the current buffer."
12354 (let (rtn range cfmt s p)
12355 (save-excursion
12356 (save-restriction
12357 (widen)
12358 (goto-char (point-min))
12359 (while (re-search-forward org-property-start-re nil t)
12360 (setq range (org-get-property-block))
12361 (goto-char (car range))
12362 (while (re-search-forward
12363 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12364 (cdr range) t)
12365 (add-to-list 'rtn (org-match-string-no-properties 1)))
12366 (outline-next-heading))))
12368 (when include-specials
12369 (setq rtn (append org-special-properties rtn)))
12371 (when include-defaults
12372 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12373 (add-to-list 'rtn org-effort-property))
12375 (when include-columns
12376 (save-excursion
12377 (save-restriction
12378 (widen)
12379 (goto-char (point-min))
12380 (while (re-search-forward
12381 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12382 nil t)
12383 (setq cfmt (match-string 2) s 0)
12384 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12385 cfmt s)
12386 (setq s (match-end 0)
12387 p (match-string 1 cfmt))
12388 (unless (or (equal p "ITEM")
12389 (member p org-special-properties))
12390 (add-to-list 'rtn (match-string 1 cfmt))))))))
12392 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12394 (defun org-property-values (key)
12395 "Return a list of all values of property KEY."
12396 (save-excursion
12397 (save-restriction
12398 (widen)
12399 (goto-char (point-min))
12400 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12401 values)
12402 (while (re-search-forward re nil t)
12403 (add-to-list 'values (org-trim (match-string 1))))
12404 (delete "" values)))))
12406 (defun org-insert-property-drawer ()
12407 "Insert a property drawer into the current entry."
12408 (interactive)
12409 (org-back-to-heading t)
12410 (looking-at outline-regexp)
12411 (let ((indent (if org-adapt-indentation
12412 (- (match-end 0)(match-beginning 0))
12414 (beg (point))
12415 (re (concat "^[ \t]*" org-keyword-time-regexp))
12416 end hiddenp)
12417 (outline-next-heading)
12418 (setq end (point))
12419 (goto-char beg)
12420 (while (re-search-forward re end t))
12421 (setq hiddenp (org-invisible-p))
12422 (end-of-line 1)
12423 (and (equal (char-after) ?\n) (forward-char 1))
12424 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12425 (if (member (match-string 1) '("CLOCK:" ":END:"))
12426 ;; just skip this line
12427 (beginning-of-line 2)
12428 ;; Drawer start, find the end
12429 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12430 (beginning-of-line 1)))
12431 (org-skip-over-state-notes)
12432 (skip-chars-backward " \t\n\r")
12433 (if (eq (char-before) ?*) (forward-char 1))
12434 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12435 (beginning-of-line 0)
12436 (org-indent-to-column indent)
12437 (beginning-of-line 2)
12438 (org-indent-to-column indent)
12439 (beginning-of-line 0)
12440 (if hiddenp
12441 (save-excursion
12442 (org-back-to-heading t)
12443 (hide-entry))
12444 (org-flag-drawer t))))
12446 (defun org-set-property (property value)
12447 "In the current entry, set PROPERTY to VALUE.
12448 When called interactively, this will prompt for a property name, offering
12449 completion on existing and default properties. And then it will prompt
12450 for a value, offering completion either on allowed values (via an inherited
12451 xxx_ALL property) or on existing values in other instances of this property
12452 in the current file."
12453 (interactive
12454 (let* ((completion-ignore-case t)
12455 (keys (org-buffer-property-keys nil t t))
12456 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12457 (prop (if (member prop0 keys)
12458 prop0
12459 (or (cdr (assoc (downcase prop0)
12460 (mapcar (lambda (x) (cons (downcase x) x))
12461 keys)))
12462 prop0)))
12463 (cur (org-entry-get nil prop))
12464 (allowed (org-property-get-allowed-values nil prop 'table))
12465 (existing (mapcar 'list (org-property-values prop)))
12466 (val (if allowed
12467 (org-completing-read "Value: " allowed nil 'req-match)
12468 (let (org-completion-use-ido org-completion-use-iswitchb)
12469 (org-completing-read
12470 (concat "Value " (if (and cur (string-match "\\S-" cur))
12471 (concat "[" cur "]") "")
12472 ": ")
12473 existing nil nil "" nil cur)))))
12474 (list prop (if (equal val "") cur val))))
12475 (unless (equal (org-entry-get nil property) value)
12476 (org-entry-put nil property value)))
12478 (defun org-delete-property (property)
12479 "In the current entry, delete PROPERTY."
12480 (interactive
12481 (let* ((completion-ignore-case t)
12482 (prop (org-icompleting-read
12483 "Property: " (org-entry-properties nil 'standard))))
12484 (list prop)))
12485 (message "Property %s %s" property
12486 (if (org-entry-delete nil property)
12487 "deleted"
12488 "was not present in the entry")))
12490 (defun org-delete-property-globally (property)
12491 "Remove PROPERTY globally, from all entries."
12492 (interactive
12493 (let* ((completion-ignore-case t)
12494 (prop (org-icompleting-read
12495 "Globally remove property: "
12496 (mapcar 'list (org-buffer-property-keys)))))
12497 (list prop)))
12498 (save-excursion
12499 (save-restriction
12500 (widen)
12501 (goto-char (point-min))
12502 (let ((cnt 0))
12503 (while (re-search-forward
12504 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12505 nil t)
12506 (setq cnt (1+ cnt))
12507 (replace-match ""))
12508 (message "Property \"%s\" removed from %d entries" property cnt)))))
12510 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12512 (defun org-compute-property-at-point ()
12513 "Compute the property at point.
12514 This looks for an enclosing column format, extracts the operator and
12515 then applies it to the property in the column format's scope."
12516 (interactive)
12517 (unless (org-at-property-p)
12518 (error "Not at a property"))
12519 (let ((prop (org-match-string-no-properties 2)))
12520 (org-columns-get-format-and-top-level)
12521 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12522 (error "No operator defined for property %s" prop))
12523 (org-columns-compute prop)))
12525 (defun org-property-get-allowed-values (pom property &optional table)
12526 "Get allowed values for the property PROPERTY.
12527 When TABLE is non-nil, return an alist that can directly be used for
12528 completion."
12529 (let (vals)
12530 (cond
12531 ((equal property "TODO")
12532 (setq vals (org-with-point-at pom
12533 (append org-todo-keywords-1 '("")))))
12534 ((equal property "PRIORITY")
12535 (let ((n org-lowest-priority))
12536 (while (>= n org-highest-priority)
12537 (push (char-to-string n) vals)
12538 (setq n (1- n)))))
12539 ((member property org-special-properties))
12541 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12543 (when (and vals (string-match "\\S-" vals))
12544 (setq vals (car (read-from-string (concat "(" vals ")"))))
12545 (setq vals (mapcar (lambda (x)
12546 (cond ((stringp x) x)
12547 ((numberp x) (number-to-string x))
12548 ((symbolp x) (symbol-name x))
12549 (t "???")))
12550 vals)))))
12551 (if table (mapcar 'list vals) vals)))
12553 (defun org-property-previous-allowed-value (&optional previous)
12554 "Switch to the next allowed value for this property."
12555 (interactive)
12556 (org-property-next-allowed-value t))
12558 (defun org-property-next-allowed-value (&optional previous)
12559 "Switch to the next allowed value for this property."
12560 (interactive)
12561 (unless (org-at-property-p)
12562 (error "Not at a property"))
12563 (let* ((key (match-string 2))
12564 (value (match-string 3))
12565 (allowed (or (org-property-get-allowed-values (point) key)
12566 (and (member value '("[ ]" "[-]" "[X]"))
12567 '("[ ]" "[X]"))))
12568 nval)
12569 (unless allowed
12570 (error "Allowed values for this property have not been defined"))
12571 (if previous (setq allowed (reverse allowed)))
12572 (if (member value allowed)
12573 (setq nval (car (cdr (member value allowed)))))
12574 (setq nval (or nval (car allowed)))
12575 (if (equal nval value)
12576 (error "Only one allowed value for this property"))
12577 (org-at-property-p)
12578 (replace-match (concat " :" key ": " nval) t t)
12579 (org-indent-line-function)
12580 (beginning-of-line 1)
12581 (skip-chars-forward " \t")))
12583 (defun org-find-entry-with-id (ident)
12584 "Locate the entry that contains the ID property with exact value IDENT.
12585 IDENT can be a string, a symbol or a number, this function will search for
12586 the string representation of it.
12587 Return the position where this entry starts, or nil if there is no such entry."
12588 (interactive "sID: ")
12589 (let ((id (cond
12590 ((stringp ident) ident)
12591 ((symbol-name ident) (symbol-name ident))
12592 ((numberp ident) (number-to-string ident))
12593 (t (error "IDENT %s must be a string, symbol or number" ident))))
12594 (case-fold-search nil))
12595 (save-excursion
12596 (save-restriction
12597 (widen)
12598 (goto-char (point-min))
12599 (when (re-search-forward
12600 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12601 nil t)
12602 (org-back-to-heading t)
12603 (point))))))
12605 ;;;; Timestamps
12607 (defvar org-last-changed-timestamp nil)
12608 (defvar org-last-inserted-timestamp nil
12609 "The last time stamp inserted with `org-insert-time-stamp'.")
12610 (defvar org-time-was-given) ; dynamically scoped parameter
12611 (defvar org-end-time-was-given) ; dynamically scoped parameter
12612 (defvar org-ts-what) ; dynamically scoped parameter
12614 (defun org-time-stamp (arg &optional inactive)
12615 "Prompt for a date/time and insert a time stamp.
12616 If the user specifies a time like HH:MM, or if this command is called
12617 with a prefix argument, the time stamp will contain date and time.
12618 Otherwise, only the date will be included. All parts of a date not
12619 specified by the user will be filled in from the current date/time.
12620 So if you press just return without typing anything, the time stamp
12621 will represent the current date/time. If there is already a timestamp
12622 at the cursor, it will be modified."
12623 (interactive "P")
12624 (let* ((ts nil)
12625 (default-time
12626 ;; Default time is either today, or, when entering a range,
12627 ;; the range start.
12628 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12629 (save-excursion
12630 (re-search-backward
12631 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12632 (- (point) 20) t)))
12633 (apply 'encode-time (org-parse-time-string (match-string 1)))
12634 (current-time)))
12635 (default-input (and ts (org-get-compact-tod ts)))
12636 org-time-was-given org-end-time-was-given time)
12637 (cond
12638 ((and (org-at-timestamp-p t)
12639 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12640 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12641 (insert "--")
12642 (setq time (let ((this-command this-command))
12643 (org-read-date arg 'totime nil nil
12644 default-time default-input)))
12645 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12646 ((org-at-timestamp-p t)
12647 (setq time (let ((this-command this-command))
12648 (org-read-date arg 'totime nil nil default-time default-input)))
12649 (when (org-at-timestamp-p t) ; just to get the match data
12650 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12651 (replace-match "")
12652 (setq org-last-changed-timestamp
12653 (org-insert-time-stamp
12654 time (or org-time-was-given arg)
12655 inactive nil nil (list org-end-time-was-given))))
12656 (message "Timestamp updated"))
12658 (setq time (let ((this-command this-command))
12659 (org-read-date arg 'totime nil nil default-time default-input)))
12660 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12661 nil nil (list org-end-time-was-given))))))
12663 ;; FIXME: can we use this for something else, like computing time differences?
12664 (defun org-get-compact-tod (s)
12665 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12666 (let* ((t1 (match-string 1 s))
12667 (h1 (string-to-number (match-string 2 s)))
12668 (m1 (string-to-number (match-string 3 s)))
12669 (t2 (and (match-end 4) (match-string 5 s)))
12670 (h2 (and t2 (string-to-number (match-string 6 s))))
12671 (m2 (and t2 (string-to-number (match-string 7 s))))
12672 dh dm)
12673 (if (not t2)
12675 (setq dh (- h2 h1) dm (- m2 m1))
12676 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12677 (concat t1 "+" (number-to-string dh)
12678 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12680 (defun org-time-stamp-inactive (&optional arg)
12681 "Insert an inactive time stamp.
12682 An inactive time stamp is enclosed in square brackets instead of angle
12683 brackets. It is inactive in the sense that it does not trigger agenda entries,
12684 does not link to the calendar and cannot be changed with the S-cursor keys.
12685 So these are more for recording a certain time/date."
12686 (interactive "P")
12687 (org-time-stamp arg 'inactive))
12689 (defvar org-date-ovl (org-make-overlay 1 1))
12690 (org-overlay-put org-date-ovl 'face 'org-warning)
12691 (org-detach-overlay org-date-ovl)
12693 (defvar org-ans1) ; dynamically scoped parameter
12694 (defvar org-ans2) ; dynamically scoped parameter
12696 (defvar org-plain-time-of-day-regexp) ; defined below
12698 (defvar org-overriding-default-time nil) ; dynamically scoped
12699 (defvar org-read-date-overlay nil)
12700 (defvar org-dcst nil) ; dynamically scoped
12701 (defvar org-read-date-history nil)
12702 (defvar org-read-date-final-answer nil)
12704 (defun org-read-date (&optional with-time to-time from-string prompt
12705 default-time default-input)
12706 "Read a date, possibly a time, and make things smooth for the user.
12707 The prompt will suggest to enter an ISO date, but you can also enter anything
12708 which will at least partially be understood by `parse-time-string'.
12709 Unrecognized parts of the date will default to the current day, month, year,
12710 hour and minute. If this command is called to replace a timestamp at point,
12711 of to enter the second timestamp of a range, the default time is taken from the
12712 existing stamp. For example,
12713 3-2-5 --> 2003-02-05
12714 feb 15 --> currentyear-02-15
12715 sep 12 9 --> 2009-09-12
12716 12:45 --> today 12:45
12717 22 sept 0:34 --> currentyear-09-22 0:34
12718 12 --> currentyear-currentmonth-12
12719 Fri --> nearest Friday (today or later)
12720 etc.
12722 Furthermore you can specify a relative date by giving, as the *first* thing
12723 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12724 change in days weeks, months, years.
12725 With a single plus or minus, the date is relative to today. With a double
12726 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12727 +4d --> four days from today
12728 +4 --> same as above
12729 +2w --> two weeks from today
12730 ++5 --> five days from default date
12732 The function understands only English month and weekday abbreviations,
12733 but this can be configured with the variables `parse-time-months' and
12734 `parse-time-weekdays'.
12736 While prompting, a calendar is popped up - you can also select the
12737 date with the mouse (button 1). The calendar shows a period of three
12738 months. To scroll it to other months, use the keys `>' and `<'.
12739 If you don't like the calendar, turn it off with
12740 \(setq org-read-date-popup-calendar nil)
12742 With optional argument TO-TIME, the date will immediately be converted
12743 to an internal time.
12744 With an optional argument WITH-TIME, the prompt will suggest to also
12745 insert a time. Note that when WITH-TIME is not set, you can still
12746 enter a time, and this function will inform the calling routine about
12747 this change. The calling routine may then choose to change the format
12748 used to insert the time stamp into the buffer to include the time.
12749 With optional argument FROM-STRING, read from this string instead from
12750 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12751 the time/date that is used for everything that is not specified by the
12752 user."
12753 (require 'parse-time)
12754 (let* ((org-time-stamp-rounding-minutes
12755 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12756 (org-dcst org-display-custom-times)
12757 (ct (org-current-time))
12758 (def (or org-overriding-default-time default-time ct))
12759 (defdecode (decode-time def))
12760 (dummy (progn
12761 (when (< (nth 2 defdecode) org-extend-today-until)
12762 (setcar (nthcdr 2 defdecode) -1)
12763 (setcar (nthcdr 1 defdecode) 59)
12764 (setq def (apply 'encode-time defdecode)
12765 defdecode (decode-time def)))))
12766 (calendar-frame-setup nil)
12767 (calendar-move-hook nil)
12768 (calendar-view-diary-initially-flag nil)
12769 (view-diary-entries-initially nil)
12770 (calendar-view-holidays-initially-flag nil)
12771 (view-calendar-holidays-initially nil)
12772 (timestr (format-time-string
12773 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12774 (prompt (concat (if prompt (concat prompt " ") "")
12775 (format "Date+time [%s]: " timestr)))
12776 ans (org-ans0 "") org-ans1 org-ans2 final)
12778 (cond
12779 (from-string (setq ans from-string))
12780 (org-read-date-popup-calendar
12781 (save-excursion
12782 (save-window-excursion
12783 (calendar)
12784 (calendar-forward-day (- (time-to-days def)
12785 (calendar-absolute-from-gregorian
12786 (calendar-current-date))))
12787 (org-eval-in-calendar nil t)
12788 (let* ((old-map (current-local-map))
12789 (map (copy-keymap calendar-mode-map))
12790 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12791 (org-defkey map (kbd "RET") 'org-calendar-select)
12792 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12793 'org-calendar-select-mouse)
12794 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12795 'org-calendar-select-mouse)
12796 (org-defkey minibuffer-local-map [(meta shift left)]
12797 (lambda () (interactive)
12798 (org-eval-in-calendar '(calendar-backward-month 1))))
12799 (org-defkey minibuffer-local-map [(meta shift right)]
12800 (lambda () (interactive)
12801 (org-eval-in-calendar '(calendar-forward-month 1))))
12802 (org-defkey minibuffer-local-map [(meta shift up)]
12803 (lambda () (interactive)
12804 (org-eval-in-calendar '(calendar-backward-year 1))))
12805 (org-defkey minibuffer-local-map [(meta shift down)]
12806 (lambda () (interactive)
12807 (org-eval-in-calendar '(calendar-forward-year 1))))
12808 (org-defkey minibuffer-local-map [?\e (shift left)]
12809 (lambda () (interactive)
12810 (org-eval-in-calendar '(calendar-backward-month 1))))
12811 (org-defkey minibuffer-local-map [?\e (shift right)]
12812 (lambda () (interactive)
12813 (org-eval-in-calendar '(calendar-forward-month 1))))
12814 (org-defkey minibuffer-local-map [?\e (shift up)]
12815 (lambda () (interactive)
12816 (org-eval-in-calendar '(calendar-backward-year 1))))
12817 (org-defkey minibuffer-local-map [?\e (shift down)]
12818 (lambda () (interactive)
12819 (org-eval-in-calendar '(calendar-forward-year 1))))
12820 (org-defkey minibuffer-local-map [(shift up)]
12821 (lambda () (interactive)
12822 (org-eval-in-calendar '(calendar-backward-week 1))))
12823 (org-defkey minibuffer-local-map [(shift down)]
12824 (lambda () (interactive)
12825 (org-eval-in-calendar '(calendar-forward-week 1))))
12826 (org-defkey minibuffer-local-map [(shift left)]
12827 (lambda () (interactive)
12828 (org-eval-in-calendar '(calendar-backward-day 1))))
12829 (org-defkey minibuffer-local-map [(shift right)]
12830 (lambda () (interactive)
12831 (org-eval-in-calendar '(calendar-forward-day 1))))
12832 (org-defkey minibuffer-local-map ">"
12833 (lambda () (interactive)
12834 (org-eval-in-calendar '(scroll-calendar-left 1))))
12835 (org-defkey minibuffer-local-map "<"
12836 (lambda () (interactive)
12837 (org-eval-in-calendar '(scroll-calendar-right 1))))
12838 (run-hooks 'org-read-date-minibuffer-setup-hook)
12839 (unwind-protect
12840 (progn
12841 (use-local-map map)
12842 (add-hook 'post-command-hook 'org-read-date-display)
12843 (setq org-ans0 (read-string prompt default-input
12844 'org-read-date-history nil))
12845 ;; org-ans0: from prompt
12846 ;; org-ans1: from mouse click
12847 ;; org-ans2: from calendar motion
12848 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12849 (remove-hook 'post-command-hook 'org-read-date-display)
12850 (use-local-map old-map)
12851 (when org-read-date-overlay
12852 (org-delete-overlay org-read-date-overlay)
12853 (setq org-read-date-overlay nil)))))))
12855 (t ; Naked prompt only
12856 (unwind-protect
12857 (setq ans (read-string prompt default-input
12858 'org-read-date-history timestr))
12859 (when org-read-date-overlay
12860 (org-delete-overlay org-read-date-overlay)
12861 (setq org-read-date-overlay nil)))))
12863 (setq final (org-read-date-analyze ans def defdecode))
12864 (setq org-read-date-final-answer ans)
12866 (if to-time
12867 (apply 'encode-time final)
12868 (if (and (boundp 'org-time-was-given) org-time-was-given)
12869 (format "%04d-%02d-%02d %02d:%02d"
12870 (nth 5 final) (nth 4 final) (nth 3 final)
12871 (nth 2 final) (nth 1 final))
12872 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12874 (defvar def)
12875 (defvar defdecode)
12876 (defvar with-time)
12877 (defvar org-read-date-analyze-futurep nil)
12878 (defun org-read-date-display ()
12879 "Display the current date prompt interpretation in the minibuffer."
12880 (when org-read-date-display-live
12881 (when org-read-date-overlay
12882 (org-delete-overlay org-read-date-overlay))
12883 (let ((p (point)))
12884 (end-of-line 1)
12885 (while (not (equal (buffer-substring
12886 (max (point-min) (- (point) 4)) (point))
12887 " "))
12888 (insert " "))
12889 (goto-char p))
12890 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12891 " " (or org-ans1 org-ans2)))
12892 (org-end-time-was-given nil)
12893 (f (org-read-date-analyze ans def defdecode))
12894 (fmts (if org-dcst
12895 org-time-stamp-custom-formats
12896 org-time-stamp-formats))
12897 (fmt (if (or with-time
12898 (and (boundp 'org-time-was-given) org-time-was-given))
12899 (cdr fmts)
12900 (car fmts)))
12901 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12902 (when (and org-end-time-was-given
12903 (string-match org-plain-time-of-day-regexp txt))
12904 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12905 org-end-time-was-given
12906 (substring txt (match-end 0)))))
12907 (when org-read-date-analyze-futurep
12908 (setq txt (concat txt " (=>F)")))
12909 (setq org-read-date-overlay
12910 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12911 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12913 (defun org-read-date-analyze (ans def defdecode)
12914 "Analyse the combined answer of the date prompt."
12915 ;; FIXME: cleanup and comment
12916 (let (delta deltan deltaw deltadef year month day
12917 hour minute second wday pm h2 m2 tl wday1
12918 iso-year iso-weekday iso-week iso-year iso-date futurep)
12919 (setq org-read-date-analyze-futurep nil)
12920 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12921 (setq ans "+0"))
12923 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12924 (setq ans (replace-match "" t t ans)
12925 deltan (car delta)
12926 deltaw (nth 1 delta)
12927 deltadef (nth 2 delta)))
12929 ;; Check if there is an iso week date in there
12930 ;; If yes, sore the info and postpone interpreting it until the rest
12931 ;; of the parsing is done
12932 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12933 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12934 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12935 iso-week (string-to-number (match-string 2 ans)))
12936 (setq ans (replace-match "" t t ans)))
12938 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12939 (when (string-match
12940 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12941 (setq year (if (match-end 2)
12942 (string-to-number (match-string 2 ans))
12943 (string-to-number (format-time-string "%Y")))
12944 month (string-to-number (match-string 3 ans))
12945 day (string-to-number (match-string 4 ans)))
12946 (if (< year 100) (setq year (+ 2000 year)))
12947 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12948 t nil ans)))
12949 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12950 ;; If there is a time with am/pm, and *no* time without it, we convert
12951 ;; so that matching will be successful.
12952 (loop for i from 1 to 2 do ; twice, for end time as well
12953 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12954 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12955 (setq hour (string-to-number (match-string 1 ans))
12956 minute (if (match-end 3)
12957 (string-to-number (match-string 3 ans))
12959 pm (equal ?p
12960 (string-to-char (downcase (match-string 4 ans)))))
12961 (if (and (= hour 12) (not pm))
12962 (setq hour 0)
12963 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12964 (setq ans (replace-match (format "%02d:%02d" hour minute)
12965 t t ans))))
12967 ;; Check if a time range is given as a duration
12968 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12969 (setq hour (string-to-number (match-string 1 ans))
12970 h2 (+ hour (string-to-number (match-string 3 ans)))
12971 minute (string-to-number (match-string 2 ans))
12972 m2 (+ minute (if (match-end 5) (string-to-number
12973 (match-string 5 ans))0)))
12974 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12975 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12976 t t ans)))
12978 ;; Check if there is a time range
12979 (when (boundp 'org-end-time-was-given)
12980 (setq org-time-was-given nil)
12981 (when (and (string-match org-plain-time-of-day-regexp ans)
12982 (match-end 8))
12983 (setq org-end-time-was-given (match-string 8 ans))
12984 (setq ans (concat (substring ans 0 (match-beginning 7))
12985 (substring ans (match-end 7))))))
12987 (setq tl (parse-time-string ans)
12988 day (or (nth 3 tl) (nth 3 defdecode))
12989 month (or (nth 4 tl)
12990 (if (and org-read-date-prefer-future
12991 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12992 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
12993 (nth 4 defdecode)))
12994 year (or (nth 5 tl)
12995 (if (and org-read-date-prefer-future
12996 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12997 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
12998 (nth 5 defdecode)))
12999 hour (or (nth 2 tl) (nth 2 defdecode))
13000 minute (or (nth 1 tl) (nth 1 defdecode))
13001 second (or (nth 0 tl) 0)
13002 wday (nth 6 tl))
13004 (when (and (eq org-read-date-prefer-future 'time)
13005 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13006 (equal day (nth 3 defdecode))
13007 (equal month (nth 4 defdecode))
13008 (equal year (nth 5 defdecode))
13009 (nth 2 tl)
13010 (or (< (nth 2 tl) (nth 2 defdecode))
13011 (and (= (nth 2 tl) (nth 2 defdecode))
13012 (nth 1 tl)
13013 (< (nth 1 tl) (nth 1 defdecode)))))
13014 (setq day (1+ day)
13015 futurep t))
13017 ;; Special date definitions below
13018 (cond
13019 (iso-week
13020 ;; There was an iso week
13021 (setq futurep nil)
13022 (setq year (or iso-year year)
13023 day (or iso-weekday wday 1)
13024 wday nil ; to make sure that the trigger below does not match
13025 iso-date (calendar-gregorian-from-absolute
13026 (calendar-absolute-from-iso
13027 (list iso-week day year))))
13028 ; FIXME: Should we also push ISO weeks into the future?
13029 ; (when (and org-read-date-prefer-future
13030 ; (not iso-year)
13031 ; (< (calendar-absolute-from-gregorian iso-date)
13032 ; (time-to-days (current-time))))
13033 ; (setq year (1+ year)
13034 ; iso-date (calendar-gregorian-from-absolute
13035 ; (calendar-absolute-from-iso
13036 ; (list iso-week day year)))))
13037 (setq month (car iso-date)
13038 year (nth 2 iso-date)
13039 day (nth 1 iso-date)))
13040 (deltan
13041 (setq futurep nil)
13042 (unless deltadef
13043 (let ((now (decode-time (current-time))))
13044 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13045 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13046 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13047 ((equal deltaw "m") (setq month (+ month deltan)))
13048 ((equal deltaw "y") (setq year (+ year deltan)))))
13049 ((and wday (not (nth 3 tl)))
13050 (setq futurep nil)
13051 ;; Weekday was given, but no day, so pick that day in the week
13052 ;; on or after the derived date.
13053 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13054 (unless (equal wday wday1)
13055 (setq day (+ day (% (- wday wday1 -7) 7))))))
13056 (if (and (boundp 'org-time-was-given)
13057 (nth 2 tl))
13058 (setq org-time-was-given t))
13059 (if (< year 100) (setq year (+ 2000 year)))
13060 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13061 (setq org-read-date-analyze-futurep futurep)
13062 (list second minute hour day month year)))
13064 (defvar parse-time-weekdays)
13066 (defun org-read-date-get-relative (s today default)
13067 "Check string S for special relative date string.
13068 TODAY and DEFAULT are internal times, for today and for a default.
13069 Return shift list (N what def-flag)
13070 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13071 N is the number of WHATs to shift.
13072 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13073 the DEFAULT date rather than TODAY."
13074 (when (and
13075 (string-match
13076 (concat
13077 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13078 "\\([0-9]+\\)?"
13079 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13080 "\\([ \t]\\|$\\)") s)
13081 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13082 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13083 (string-to-char (substring (match-string 1 s) -1))
13084 ?+))
13085 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13086 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13087 (what (if (match-end 3) (match-string 3 s) "d"))
13088 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13089 (date (if rel default today))
13090 (wday (nth 6 (decode-time date)))
13091 delta)
13092 (if wday1
13093 (progn
13094 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13095 (if (= dir ?-) (setq delta (- delta 7)))
13096 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13097 (list delta "d" rel))
13098 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13100 (defun org-eval-in-calendar (form &optional keepdate)
13101 "Eval FORM in the calendar window and return to current window.
13102 Also, store the cursor date in variable org-ans2."
13103 (let ((sf (selected-frame))
13104 (sw (selected-window)))
13105 (select-window (get-buffer-window "*Calendar*" t))
13106 (eval form)
13107 (when (and (not keepdate) (calendar-cursor-to-date))
13108 (let* ((date (calendar-cursor-to-date))
13109 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13110 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13111 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13112 (select-window sw)
13113 (org-select-frame-set-input-focus sf)))
13115 (defun org-calendar-select ()
13116 "Return to `org-read-date' with the date currently selected.
13117 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13118 (interactive)
13119 (when (calendar-cursor-to-date)
13120 (let* ((date (calendar-cursor-to-date))
13121 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13122 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13123 (if (active-minibuffer-window) (exit-minibuffer))))
13125 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13126 "Insert a date stamp for the date given by the internal TIME.
13127 WITH-HM means, use the stamp format that includes the time of the day.
13128 INACTIVE means use square brackets instead of angular ones, so that the
13129 stamp will not contribute to the agenda.
13130 PRE and POST are optional strings to be inserted before and after the
13131 stamp.
13132 The command returns the inserted time stamp."
13133 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13134 stamp)
13135 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13136 (insert-before-markers (or pre ""))
13137 (insert-before-markers (setq stamp (format-time-string fmt time)))
13138 (when (listp extra)
13139 (setq extra (car extra))
13140 (if (and (stringp extra)
13141 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13142 (setq extra (format "-%02d:%02d"
13143 (string-to-number (match-string 1 extra))
13144 (string-to-number (match-string 2 extra))))
13145 (setq extra nil)))
13146 (when extra
13147 (backward-char 1)
13148 (insert-before-markers extra)
13149 (forward-char 1))
13150 (insert-before-markers (or post ""))
13151 (setq org-last-inserted-timestamp stamp)))
13153 (defun org-toggle-time-stamp-overlays ()
13154 "Toggle the use of custom time stamp formats."
13155 (interactive)
13156 (setq org-display-custom-times (not org-display-custom-times))
13157 (unless org-display-custom-times
13158 (let ((p (point-min)) (bmp (buffer-modified-p)))
13159 (while (setq p (next-single-property-change p 'display))
13160 (if (and (get-text-property p 'display)
13161 (eq (get-text-property p 'face) 'org-date))
13162 (remove-text-properties
13163 p (setq p (next-single-property-change p 'display))
13164 '(display t))))
13165 (set-buffer-modified-p bmp)))
13166 (if (featurep 'xemacs)
13167 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13168 (org-restart-font-lock)
13169 (setq org-table-may-need-update t)
13170 (if org-display-custom-times
13171 (message "Time stamps are overlayed with custom format")
13172 (message "Time stamp overlays removed")))
13174 (defun org-display-custom-time (beg end)
13175 "Overlay modified time stamp format over timestamp between BEG and END."
13176 (let* ((ts (buffer-substring beg end))
13177 t1 w1 with-hm tf time str w2 (off 0))
13178 (save-match-data
13179 (setq t1 (org-parse-time-string ts t))
13180 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13181 (setq off (- (match-end 0) (match-beginning 0)))))
13182 (setq end (- end off))
13183 (setq w1 (- end beg)
13184 with-hm (and (nth 1 t1) (nth 2 t1))
13185 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13186 time (org-fix-decoded-time t1)
13187 str (org-add-props
13188 (format-time-string
13189 (substring tf 1 -1) (apply 'encode-time time))
13190 nil 'mouse-face 'highlight)
13191 w2 (length str))
13192 (if (not (= w2 w1))
13193 (add-text-properties (1+ beg) (+ 2 beg)
13194 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13195 (if (featurep 'xemacs)
13196 (progn
13197 (put-text-property beg end 'invisible t)
13198 (put-text-property beg end 'end-glyph (make-glyph str)))
13199 (put-text-property beg end 'display str))))
13201 (defun org-translate-time (string)
13202 "Translate all timestamps in STRING to custom format.
13203 But do this only if the variable `org-display-custom-times' is set."
13204 (when org-display-custom-times
13205 (save-match-data
13206 (let* ((start 0)
13207 (re org-ts-regexp-both)
13208 t1 with-hm inactive tf time str beg end)
13209 (while (setq start (string-match re string start))
13210 (setq beg (match-beginning 0)
13211 end (match-end 0)
13212 t1 (save-match-data
13213 (org-parse-time-string (substring string beg end) t))
13214 with-hm (and (nth 1 t1) (nth 2 t1))
13215 inactive (equal (substring string beg (1+ beg)) "[")
13216 tf (funcall (if with-hm 'cdr 'car)
13217 org-time-stamp-custom-formats)
13218 time (org-fix-decoded-time t1)
13219 str (format-time-string
13220 (concat
13221 (if inactive "[" "<") (substring tf 1 -1)
13222 (if inactive "]" ">"))
13223 (apply 'encode-time time))
13224 string (replace-match str t t string)
13225 start (+ start (length str)))))))
13226 string)
13228 (defun org-fix-decoded-time (time)
13229 "Set 0 instead of nil for the first 6 elements of time.
13230 Don't touch the rest."
13231 (let ((n 0))
13232 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13234 (defun org-days-to-time (timestamp-string)
13235 "Difference between TIMESTAMP-STRING and now in days."
13236 (- (time-to-days (org-time-string-to-time timestamp-string))
13237 (time-to-days (current-time))))
13239 (defun org-deadline-close (timestamp-string &optional ndays)
13240 "Is the time in TIMESTAMP-STRING close to the current date?"
13241 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13242 (and (< (org-days-to-time timestamp-string) ndays)
13243 (not (org-entry-is-done-p))))
13245 (defun org-get-wdays (ts)
13246 "Get the deadline lead time appropriate for timestring TS."
13247 (cond
13248 ((<= org-deadline-warning-days 0)
13249 ;; 0 or negative, enforce this value no matter what
13250 (- org-deadline-warning-days))
13251 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13252 ;; lead time is specified.
13253 (floor (* (string-to-number (match-string 1 ts))
13254 (cdr (assoc (match-string 2 ts)
13255 '(("d" . 1) ("w" . 7)
13256 ("m" . 30.4) ("y" . 365.25)))))))
13257 ;; go for the default.
13258 (t org-deadline-warning-days)))
13260 (defun org-calendar-select-mouse (ev)
13261 "Return to `org-read-date' with the date currently selected.
13262 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13263 (interactive "e")
13264 (mouse-set-point ev)
13265 (when (calendar-cursor-to-date)
13266 (let* ((date (calendar-cursor-to-date))
13267 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13268 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13269 (if (active-minibuffer-window) (exit-minibuffer))))
13271 (defun org-check-deadlines (ndays)
13272 "Check if there are any deadlines due or past due.
13273 A deadline is considered due if it happens within `org-deadline-warning-days'
13274 days from today's date. If the deadline appears in an entry marked DONE,
13275 it is not shown. The prefix arg NDAYS can be used to test that many
13276 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13277 (interactive "P")
13278 (let* ((org-warn-days
13279 (cond
13280 ((equal ndays '(4)) 100000)
13281 (ndays (prefix-numeric-value ndays))
13282 (t (abs org-deadline-warning-days))))
13283 (case-fold-search nil)
13284 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13285 (callback
13286 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13288 (message "%d deadlines past-due or due within %d days"
13289 (org-occur regexp nil callback)
13290 org-warn-days)))
13292 (defun org-check-before-date (date)
13293 "Check if there are deadlines or scheduled entries before DATE."
13294 (interactive (list (org-read-date)))
13295 (let ((case-fold-search nil)
13296 (regexp (concat "\\<\\(" org-deadline-string
13297 "\\|" org-scheduled-string
13298 "\\) *<\\([^>]+\\)>"))
13299 (callback
13300 (lambda () (time-less-p
13301 (org-time-string-to-time (match-string 2))
13302 (org-time-string-to-time date)))))
13303 (message "%d entries before %s"
13304 (org-occur regexp nil callback) date)))
13306 (defun org-check-after-date (date)
13307 "Check if there are deadlines or scheduled entries after DATE."
13308 (interactive (list (org-read-date)))
13309 (let ((case-fold-search nil)
13310 (regexp (concat "\\<\\(" org-deadline-string
13311 "\\|" org-scheduled-string
13312 "\\) *<\\([^>]+\\)>"))
13313 (callback
13314 (lambda () (not
13315 (time-less-p
13316 (org-time-string-to-time (match-string 2))
13317 (org-time-string-to-time date))))))
13318 (message "%d entries after %s"
13319 (org-occur regexp nil callback) date)))
13321 (defun org-evaluate-time-range (&optional to-buffer)
13322 "Evaluate a time range by computing the difference between start and end.
13323 Normally the result is just printed in the echo area, but with prefix arg
13324 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13325 If the time range is actually in a table, the result is inserted into the
13326 next column.
13327 For time difference computation, a year is assumed to be exactly 365
13328 days in order to avoid rounding problems."
13329 (interactive "P")
13331 (org-clock-update-time-maybe)
13332 (save-excursion
13333 (unless (org-at-date-range-p t)
13334 (goto-char (point-at-bol))
13335 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13336 (if (not (org-at-date-range-p t))
13337 (error "Not at a time-stamp range, and none found in current line")))
13338 (let* ((ts1 (match-string 1))
13339 (ts2 (match-string 2))
13340 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13341 (match-end (match-end 0))
13342 (time1 (org-time-string-to-time ts1))
13343 (time2 (org-time-string-to-time ts2))
13344 (t1 (org-float-time time1))
13345 (t2 (org-float-time time2))
13346 (diff (abs (- t2 t1)))
13347 (negative (< (- t2 t1) 0))
13348 ;; (ys (floor (* 365 24 60 60)))
13349 (ds (* 24 60 60))
13350 (hs (* 60 60))
13351 (fy "%dy %dd %02d:%02d")
13352 (fy1 "%dy %dd")
13353 (fd "%dd %02d:%02d")
13354 (fd1 "%dd")
13355 (fh "%02d:%02d")
13356 y d h m align)
13357 (if havetime
13358 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13360 d (floor (/ diff ds)) diff (mod diff ds)
13361 h (floor (/ diff hs)) diff (mod diff hs)
13362 m (floor (/ diff 60)))
13363 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13365 d (floor (+ (/ diff ds) 0.5))
13366 h 0 m 0))
13367 (if (not to-buffer)
13368 (message "%s" (org-make-tdiff-string y d h m))
13369 (if (org-at-table-p)
13370 (progn
13371 (goto-char match-end)
13372 (setq align t)
13373 (and (looking-at " *|") (goto-char (match-end 0))))
13374 (goto-char match-end))
13375 (if (looking-at
13376 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13377 (replace-match ""))
13378 (if negative (insert " -"))
13379 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13380 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13381 (insert " " (format fh h m))))
13382 (if align (org-table-align))
13383 (message "Time difference inserted")))))
13385 (defun org-make-tdiff-string (y d h m)
13386 (let ((fmt "")
13387 (l nil))
13388 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13389 l (push y l)))
13390 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13391 l (push d l)))
13392 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13393 l (push h l)))
13394 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13395 l (push m l)))
13396 (apply 'format fmt (nreverse l))))
13398 (defun org-time-string-to-time (s)
13399 (apply 'encode-time (org-parse-time-string s)))
13400 (defun org-time-string-to-seconds (s)
13401 (org-float-time (org-time-string-to-time s)))
13403 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13404 "Convert a time stamp to an absolute day number.
13405 If there is a specifyer for a cyclic time stamp, get the closest date to
13406 DAYNR.
13407 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13408 the variable date is bound by the calendar when this is called."
13409 (cond
13410 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13411 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13412 daynr
13413 (+ daynr 1000)))
13414 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13415 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13416 (time-to-days (current-time))) (match-string 0 s)
13417 prefer show-all))
13418 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13420 (defun org-days-to-iso-week (days)
13421 "Return the iso week number."
13422 (require 'cal-iso)
13423 (car (calendar-iso-from-absolute days)))
13425 (defun org-small-year-to-year (year)
13426 "Convert 2-digit years into 4-digit years.
13427 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13428 The year 2000 cannot be abbreviated. Any year larger than 99
13429 is returned unchanged."
13430 (if (< year 38)
13431 (setq year (+ 2000 year))
13432 (if (< year 100)
13433 (setq year (+ 1900 year))))
13434 year)
13436 (defun org-time-from-absolute (d)
13437 "Return the time corresponding to date D.
13438 D may be an absolute day number, or a calendar-type list (month day year)."
13439 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13440 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13442 (defun org-calendar-holiday ()
13443 "List of holidays, for Diary display in Org-mode."
13444 (require 'holidays)
13445 (let ((hl (funcall
13446 (if (fboundp 'calendar-check-holidays)
13447 'calendar-check-holidays 'check-calendar-holidays) date)))
13448 (if hl (mapconcat 'identity hl "; "))))
13450 (defun org-diary-sexp-entry (sexp entry date)
13451 "Process a SEXP diary ENTRY for DATE."
13452 (require 'diary-lib)
13453 (let ((result (if calendar-debug-sexp
13454 (let ((stack-trace-on-error t))
13455 (eval (car (read-from-string sexp))))
13456 (condition-case nil
13457 (eval (car (read-from-string sexp)))
13458 (error
13459 (beep)
13460 (message "Bad sexp at line %d in %s: %s"
13461 (org-current-line)
13462 (buffer-file-name) sexp)
13463 (sleep-for 2))))))
13464 (cond ((stringp result) result)
13465 ((and (consp result)
13466 (stringp (cdr result))) (cdr result))
13467 (result entry)
13468 (t nil))))
13470 (defun org-diary-to-ical-string (frombuf)
13471 "Get iCalendar entries from diary entries in buffer FROMBUF.
13472 This uses the icalendar.el library."
13473 (let* ((tmpdir (if (featurep 'xemacs)
13474 (temp-directory)
13475 temporary-file-directory))
13476 (tmpfile (make-temp-name
13477 (expand-file-name "orgics" tmpdir)))
13478 buf rtn b e)
13479 (save-excursion
13480 (set-buffer frombuf)
13481 (icalendar-export-region (point-min) (point-max) tmpfile)
13482 (setq buf (find-buffer-visiting tmpfile))
13483 (set-buffer buf)
13484 (goto-char (point-min))
13485 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13486 (setq b (match-beginning 0)))
13487 (goto-char (point-max))
13488 (if (re-search-backward "^END:VEVENT" nil t)
13489 (setq e (match-end 0)))
13490 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13491 (kill-buffer buf)
13492 (delete-file tmpfile)
13493 rtn))
13495 (defun org-closest-date (start current change prefer show-all)
13496 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13497 When PREFER is `past' return a date that is either CURRENT or past.
13498 When PREFER is `future', return a date that is either CURRENT or future.
13499 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13500 ;; Make the proper lists from the dates
13501 (catch 'exit
13502 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13503 dn dw sday cday n1 n2 n0
13504 d m y y1 y2 date1 date2 nmonths nm ny m2)
13506 (setq start (org-date-to-gregorian start)
13507 current (org-date-to-gregorian
13508 (if show-all
13509 current
13510 (time-to-days (current-time))))
13511 sday (calendar-absolute-from-gregorian start)
13512 cday (calendar-absolute-from-gregorian current))
13514 (if (<= cday sday) (throw 'exit sday))
13516 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13517 (setq dn (string-to-number (match-string 1 change))
13518 dw (cdr (assoc (match-string 2 change) a1)))
13519 (error "Invalid change specifyer: %s" change))
13520 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13521 (cond
13522 ((eq dw 'day)
13523 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13524 n2 (+ n1 dn)))
13525 ((eq dw 'year)
13526 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13527 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13528 (setq date1 (list m d y1)
13529 n1 (calendar-absolute-from-gregorian date1)
13530 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13531 n2 (calendar-absolute-from-gregorian date2)))
13532 ((eq dw 'month)
13533 ;; approx number of month between the two dates
13534 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13535 ;; How often does dn fit in there?
13536 (setq d (nth 1 start) m (car start) y (nth 2 start)
13537 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13538 m (+ m nm)
13539 ny (floor (/ m 12))
13540 y (+ y ny)
13541 m (- m (* ny 12)))
13542 (while (> m 12) (setq m (- m 12) y (1+ y)))
13543 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13544 (setq m2 (+ m dn) y2 y)
13545 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13546 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13547 (while (<= n2 cday)
13548 (setq n1 n2 m m2 y y2)
13549 (setq m2 (+ m dn) y2 y)
13550 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13551 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13552 ;; Make sure n1 is the earlier date
13553 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13554 (if show-all
13555 (cond
13556 ((eq prefer 'past) (if (= cday n2) n2 n1))
13557 ((eq prefer 'future) (if (= cday n1) n1 n2))
13558 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13559 (cond
13560 ((eq prefer 'past) (if (= cday n2) n2 n1))
13561 ((eq prefer 'future) (if (= cday n1) n1 n2))
13562 (t (if (= cday n1) n1 n2)))))))
13564 (defun org-date-to-gregorian (date)
13565 "Turn any specification of DATE into a gregorian date for the calendar."
13566 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13567 ((and (listp date) (= (length date) 3)) date)
13568 ((stringp date)
13569 (setq date (org-parse-time-string date))
13570 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13571 ((listp date)
13572 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13574 (defun org-parse-time-string (s &optional nodefault)
13575 "Parse the standard Org-mode time string.
13576 This should be a lot faster than the normal `parse-time-string'.
13577 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13578 hour and minute fields will be nil if not given."
13579 (if (string-match org-ts-regexp0 s)
13580 (list 0
13581 (if (or (match-beginning 8) (not nodefault))
13582 (string-to-number (or (match-string 8 s) "0")))
13583 (if (or (match-beginning 7) (not nodefault))
13584 (string-to-number (or (match-string 7 s) "0")))
13585 (string-to-number (match-string 4 s))
13586 (string-to-number (match-string 3 s))
13587 (string-to-number (match-string 2 s))
13588 nil nil nil)
13589 (error "Not a standard Org-mode time string: %s" s)))
13591 (defun org-timestamp-up (&optional arg)
13592 "Increase the date item at the cursor by one.
13593 If the cursor is on the year, change the year. If it is on the month or
13594 the day, change that.
13595 With prefix ARG, change by that many units."
13596 (interactive "p")
13597 (org-timestamp-change (prefix-numeric-value arg)))
13599 (defun org-timestamp-down (&optional arg)
13600 "Decrease the date item at the cursor by one.
13601 If the cursor is on the year, change the year. If it is on the month or
13602 the day, change that.
13603 With prefix ARG, change by that many units."
13604 (interactive "p")
13605 (org-timestamp-change (- (prefix-numeric-value arg))))
13607 (defun org-timestamp-up-day (&optional arg)
13608 "Increase the date in the time stamp by one day.
13609 With prefix ARG, change that many days."
13610 (interactive "p")
13611 (if (and (not (org-at-timestamp-p t))
13612 (org-on-heading-p))
13613 (org-todo 'up)
13614 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13616 (defun org-timestamp-down-day (&optional arg)
13617 "Decrease the date in the time stamp by one day.
13618 With prefix ARG, change that many days."
13619 (interactive "p")
13620 (if (and (not (org-at-timestamp-p t))
13621 (org-on-heading-p))
13622 (org-todo 'down)
13623 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13625 (defun org-at-timestamp-p (&optional inactive-ok)
13626 "Determine if the cursor is in or at a timestamp."
13627 (interactive)
13628 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13629 (pos (point))
13630 (ans (or (looking-at tsr)
13631 (save-excursion
13632 (skip-chars-backward "^[<\n\r\t")
13633 (if (> (point) (point-min)) (backward-char 1))
13634 (and (looking-at tsr)
13635 (> (- (match-end 0) pos) -1))))))
13636 (and ans
13637 (boundp 'org-ts-what)
13638 (setq org-ts-what
13639 (cond
13640 ((= pos (match-beginning 0)) 'bracket)
13641 ((= pos (1- (match-end 0))) 'bracket)
13642 ((org-pos-in-match-range pos 2) 'year)
13643 ((org-pos-in-match-range pos 3) 'month)
13644 ((org-pos-in-match-range pos 7) 'hour)
13645 ((org-pos-in-match-range pos 8) 'minute)
13646 ((or (org-pos-in-match-range pos 4)
13647 (org-pos-in-match-range pos 5)) 'day)
13648 ((and (> pos (or (match-end 8) (match-end 5)))
13649 (< pos (match-end 0)))
13650 (- pos (or (match-end 8) (match-end 5))))
13651 (t 'day))))
13652 ans))
13654 (defun org-toggle-timestamp-type ()
13655 "Toggle the type (<active> or [inactive]) of a time stamp."
13656 (interactive)
13657 (when (org-at-timestamp-p t)
13658 (let ((beg (match-beginning 0)) (end (match-end 0))
13659 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13660 (save-excursion
13661 (goto-char beg)
13662 (while (re-search-forward "[][<>]" end t)
13663 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13664 t t)))
13665 (message "Timestamp is now %sactive"
13666 (if (equal (char-after beg) ?<) "" "in")))))
13668 (defun org-timestamp-change (n &optional what)
13669 "Change the date in the time stamp at point.
13670 The date will be changed by N times WHAT. WHAT can be `day', `month',
13671 `year', `minute', `second'. If WHAT is not given, the cursor position
13672 in the timestamp determines what will be changed."
13673 (let ((pos (point))
13674 with-hm inactive
13675 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13676 org-ts-what
13677 extra rem
13678 ts time time0)
13679 (if (not (org-at-timestamp-p t))
13680 (error "Not at a timestamp"))
13681 (if (and (not what) (eq org-ts-what 'bracket))
13682 (org-toggle-timestamp-type)
13683 (if (and (not what) (not (eq org-ts-what 'day))
13684 org-display-custom-times
13685 (get-text-property (point) 'display)
13686 (not (get-text-property (1- (point)) 'display)))
13687 (setq org-ts-what 'day))
13688 (setq org-ts-what (or what org-ts-what)
13689 inactive (= (char-after (match-beginning 0)) ?\[)
13690 ts (match-string 0))
13691 (replace-match "")
13692 (if (string-match
13693 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13695 (setq extra (match-string 1 ts)))
13696 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13697 (setq with-hm t))
13698 (setq time0 (org-parse-time-string ts))
13699 (when (and (eq org-ts-what 'minute)
13700 (eq current-prefix-arg nil))
13701 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13702 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13703 (setcar (cdr time0) (+ (nth 1 time0)
13704 (if (> n 0) (- rem) (- dm rem))))))
13705 (setq time
13706 (encode-time (or (car time0) 0)
13707 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13708 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13709 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13710 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13711 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13712 (nthcdr 6 time0)))
13713 (when (and (member org-ts-what '(hour minute))
13714 extra
13715 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13716 (setq extra (org-modify-ts-extra
13717 extra
13718 (if (eq org-ts-what 'hour) 2 5)
13719 n dm)))
13720 (when (integerp org-ts-what)
13721 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13722 (if (eq what 'calendar)
13723 (let ((cal-date (org-get-date-from-calendar)))
13724 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13725 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13726 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13727 (setcar time0 (or (car time0) 0))
13728 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13729 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13730 (setq time (apply 'encode-time time0))))
13731 (setq org-last-changed-timestamp
13732 (org-insert-time-stamp time with-hm inactive nil nil extra))
13733 (org-clock-update-time-maybe)
13734 (goto-char pos)
13735 ;; Try to recenter the calendar window, if any
13736 (if (and org-calendar-follow-timestamp-change
13737 (get-buffer-window "*Calendar*" t)
13738 (memq org-ts-what '(day month year)))
13739 (org-recenter-calendar (time-to-days time))))))
13741 (defun org-modify-ts-extra (s pos n dm)
13742 "Change the different parts of the lead-time and repeat fields in timestamp."
13743 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13744 ng h m new rem)
13745 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13746 (cond
13747 ((or (org-pos-in-match-range pos 2)
13748 (org-pos-in-match-range pos 3))
13749 (setq m (string-to-number (match-string 3 s))
13750 h (string-to-number (match-string 2 s)))
13751 (if (org-pos-in-match-range pos 2)
13752 (setq h (+ h n))
13753 (setq n (* dm (org-no-warnings (signum n))))
13754 (when (not (= 0 (setq rem (% m dm))))
13755 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13756 (setq m (+ m n)))
13757 (if (< m 0) (setq m (+ m 60) h (1- h)))
13758 (if (> m 59) (setq m (- m 60) h (1+ h)))
13759 (setq h (min 24 (max 0 h)))
13760 (setq ng 1 new (format "-%02d:%02d" h m)))
13761 ((org-pos-in-match-range pos 6)
13762 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13763 ((org-pos-in-match-range pos 5)
13764 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13766 ((org-pos-in-match-range pos 9)
13767 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13768 ((org-pos-in-match-range pos 8)
13769 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13771 (when ng
13772 (setq s (concat
13773 (substring s 0 (match-beginning ng))
13775 (substring s (match-end ng))))))
13778 (defun org-recenter-calendar (date)
13779 "If the calendar is visible, recenter it to DATE."
13780 (let* ((win (selected-window))
13781 (cwin (get-buffer-window "*Calendar*" t))
13782 (calendar-move-hook nil))
13783 (when cwin
13784 (select-window cwin)
13785 (calendar-goto-date (if (listp date) date
13786 (calendar-gregorian-from-absolute date)))
13787 (select-window win))))
13789 (defun org-goto-calendar (&optional arg)
13790 "Go to the Emacs calendar at the current date.
13791 If there is a time stamp in the current line, go to that date.
13792 A prefix ARG can be used to force the current date."
13793 (interactive "P")
13794 (let ((tsr org-ts-regexp) diff
13795 (calendar-move-hook nil)
13796 (calendar-view-holidays-initially-flag nil)
13797 (view-calendar-holidays-initially nil)
13798 (calendar-view-diary-initially-flag nil)
13799 (view-diary-entries-initially nil))
13800 (if (or (org-at-timestamp-p)
13801 (save-excursion
13802 (beginning-of-line 1)
13803 (looking-at (concat ".*" tsr))))
13804 (let ((d1 (time-to-days (current-time)))
13805 (d2 (time-to-days
13806 (org-time-string-to-time (match-string 1)))))
13807 (setq diff (- d2 d1))))
13808 (calendar)
13809 (calendar-goto-today)
13810 (if (and diff (not arg)) (calendar-forward-day diff))))
13812 (defun org-get-date-from-calendar ()
13813 "Return a list (month day year) of date at point in calendar."
13814 (with-current-buffer "*Calendar*"
13815 (save-match-data
13816 (calendar-cursor-to-date))))
13818 (defun org-date-from-calendar ()
13819 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13820 If there is already a time stamp at the cursor position, update it."
13821 (interactive)
13822 (if (org-at-timestamp-p t)
13823 (org-timestamp-change 0 'calendar)
13824 (let ((cal-date (org-get-date-from-calendar)))
13825 (org-insert-time-stamp
13826 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13828 (defun org-minutes-to-hh:mm-string (m)
13829 "Compute H:MM from a number of minutes."
13830 (let ((h (/ m 60)))
13831 (setq m (- m (* 60 h)))
13832 (format org-time-clocksum-format h m)))
13834 (defun org-hh:mm-string-to-minutes (s)
13835 "Convert a string H:MM to a number of minutes.
13836 If the string is just a number, interprete it as minutes.
13837 In fact, the first hh:mm or number in the string will be taken,
13838 there can be extra stuff in the string.
13839 If no number is found, the return value is 0."
13840 (cond
13841 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13842 (+ (* (string-to-number (match-string 1 s)) 60)
13843 (string-to-number (match-string 2 s))))
13844 ((string-match "\\([0-9]+\\)" s)
13845 (string-to-number (match-string 1 s)))
13846 (t 0)))
13848 ;;;; Files
13850 (defun org-save-all-org-buffers ()
13851 "Save all Org-mode buffers without user confirmation."
13852 (interactive)
13853 (message "Saving all Org-mode buffers...")
13854 (save-some-buffers t 'org-mode-p)
13855 (when (featurep 'org-id) (org-id-locations-save))
13856 (message "Saving all Org-mode buffers... done"))
13858 (defun org-revert-all-org-buffers ()
13859 "Revert all Org-mode buffers.
13860 Prompt for confirmation when there are unsaved changes.
13861 Be sure you know what you are doing before letting this function
13862 overwrite your changes.
13864 This function is useful in a setup where one tracks org files
13865 with a version control system, to revert on one machine after pulling
13866 changes from another. I believe the procedure must be like this:
13868 1. M-x org-save-all-org-buffers
13869 2. Pull changes from the other machine, resolve conflicts
13870 3. M-x org-revert-all-org-buffers"
13871 (interactive)
13872 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13873 (error "Abort"))
13874 (save-excursion
13875 (save-window-excursion
13876 (mapc
13877 (lambda (b)
13878 (when (and (with-current-buffer b (org-mode-p))
13879 (with-current-buffer b buffer-file-name))
13880 (switch-to-buffer b)
13881 (revert-buffer t 'no-confirm)))
13882 (buffer-list))
13883 (when (and (featurep 'org-id) org-id-track-globally)
13884 (org-id-locations-load)))))
13886 ;;;; Agenda files
13888 ;;;###autoload
13889 (defun org-iswitchb (&optional arg)
13890 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13891 With a prefix argument, restrict available to files.
13892 With two prefix arguments, restrict available buffers to agenda files."
13893 (interactive "P")
13894 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13895 ((equal arg '(16)) (org-buffer-list 'agenda))
13896 (t (org-buffer-list)))))
13897 (switch-to-buffer
13898 (org-icompleting-read "Org buffer: "
13899 (mapcar 'list (mapcar 'buffer-name blist))
13900 nil t))))
13902 ;;;###autoload
13903 (defalias 'org-ido-switchb 'org-iswitchb)
13905 (defun org-buffer-list (&optional predicate exclude-tmp)
13906 "Return a list of Org buffers.
13907 PREDICATE can be `export', `files' or `agenda'.
13909 export restrict the list to Export buffers.
13910 files restrict the list to buffers visiting Org files.
13911 agenda restrict the list to buffers visiting agenda files.
13913 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13914 (let* ((bfn nil)
13915 (agenda-files (and (eq predicate 'agenda)
13916 (mapcar 'file-truename (org-agenda-files t))))
13917 (filter
13918 (cond
13919 ((eq predicate 'files)
13920 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13921 ((eq predicate 'export)
13922 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13923 ((eq predicate 'agenda)
13924 (lambda (b)
13925 (with-current-buffer b
13926 (and (eq major-mode 'org-mode)
13927 (setq bfn (buffer-file-name b))
13928 (member (file-truename bfn) agenda-files)))))
13929 (t (lambda (b) (with-current-buffer b
13930 (or (eq major-mode 'org-mode)
13931 (string-match "\*Org .*Export"
13932 (buffer-name b)))))))))
13933 (delq nil
13934 (mapcar
13935 (lambda(b)
13936 (if (and (funcall filter b)
13937 (or (not exclude-tmp)
13938 (not (string-match "tmp" (buffer-name b)))))
13940 nil))
13941 (buffer-list)))))
13943 (defun org-agenda-files (&optional unrestricted archives)
13944 "Get the list of agenda files.
13945 Optional UNRESTRICTED means return the full list even if a restriction
13946 is currently in place.
13947 When ARCHIVES is t, include all archive files hat are really being
13948 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13949 `org-agenda-archives-mode' is t."
13950 (let ((files
13951 (cond
13952 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13953 ((stringp org-agenda-files) (org-read-agenda-file-list))
13954 ((listp org-agenda-files) org-agenda-files)
13955 (t (error "Invalid value of `org-agenda-files'")))))
13956 (setq files (apply 'append
13957 (mapcar (lambda (f)
13958 (if (file-directory-p f)
13959 (directory-files
13960 f t org-agenda-file-regexp)
13961 (list f)))
13962 files)))
13963 (when org-agenda-skip-unavailable-files
13964 (setq files (delq nil
13965 (mapcar (function
13966 (lambda (file)
13967 (and (file-readable-p file) file)))
13968 files))))
13969 (when (or (eq archives t)
13970 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13971 (setq files (org-add-archive-files files)))
13972 files))
13974 (defun org-edit-agenda-file-list ()
13975 "Edit the list of agenda files.
13976 Depending on setup, this either uses customize to edit the variable
13977 `org-agenda-files', or it visits the file that is holding the list. In the
13978 latter case, the buffer is set up in a way that saving it automatically kills
13979 the buffer and restores the previous window configuration."
13980 (interactive)
13981 (if (stringp org-agenda-files)
13982 (let ((cw (current-window-configuration)))
13983 (find-file org-agenda-files)
13984 (org-set-local 'org-window-configuration cw)
13985 (org-add-hook 'after-save-hook
13986 (lambda ()
13987 (set-window-configuration
13988 (prog1 org-window-configuration
13989 (kill-buffer (current-buffer))))
13990 (org-install-agenda-files-menu)
13991 (message "New agenda file list installed"))
13992 nil 'local)
13993 (message "%s" (substitute-command-keys
13994 "Edit list and finish with \\[save-buffer]")))
13995 (customize-variable 'org-agenda-files)))
13997 (defun org-store-new-agenda-file-list (list)
13998 "Set new value for the agenda file list and save it correctly."
13999 (if (stringp org-agenda-files)
14000 (let ((f org-agenda-files) b)
14001 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14002 (with-temp-file f
14003 (insert (mapconcat 'identity list "\n") "\n")))
14004 (let ((org-mode-hook nil) (org-inhibit-startup t)
14005 (org-insert-mode-line-in-empty-file nil))
14006 (setq org-agenda-files list)
14007 (customize-save-variable 'org-agenda-files org-agenda-files))))
14009 (defun org-read-agenda-file-list ()
14010 "Read the list of agenda files from a file."
14011 (when (file-directory-p org-agenda-files)
14012 (error "`org-agenda-files' cannot be a single directory"))
14013 (when (stringp org-agenda-files)
14014 (with-temp-buffer
14015 (insert-file-contents org-agenda-files)
14016 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14019 ;;;###autoload
14020 (defun org-cycle-agenda-files ()
14021 "Cycle through the files in `org-agenda-files'.
14022 If the current buffer visits an agenda file, find the next one in the list.
14023 If the current buffer does not, find the first agenda file."
14024 (interactive)
14025 (let* ((fs (org-agenda-files t))
14026 (files (append fs (list (car fs))))
14027 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14028 file)
14029 (unless files (error "No agenda files"))
14030 (catch 'exit
14031 (while (setq file (pop files))
14032 (if (equal (file-truename file) tcf)
14033 (when (car files)
14034 (find-file (car files))
14035 (throw 'exit t))))
14036 (find-file (car fs)))
14037 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14039 (defun org-agenda-file-to-front (&optional to-end)
14040 "Move/add the current file to the top of the agenda file list.
14041 If the file is not present in the list, it is added to the front. If it is
14042 present, it is moved there. With optional argument TO-END, add/move to the
14043 end of the list."
14044 (interactive "P")
14045 (let ((org-agenda-skip-unavailable-files nil)
14046 (file-alist (mapcar (lambda (x)
14047 (cons (file-truename x) x))
14048 (org-agenda-files t)))
14049 (ctf (file-truename buffer-file-name))
14050 x had)
14051 (setq x (assoc ctf file-alist) had x)
14053 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14054 (if to-end
14055 (setq file-alist (append (delq x file-alist) (list x)))
14056 (setq file-alist (cons x (delq x file-alist))))
14057 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14058 (org-install-agenda-files-menu)
14059 (message "File %s to %s of agenda file list"
14060 (if had "moved" "added") (if to-end "end" "front"))))
14062 (defun org-remove-file (&optional file)
14063 "Remove current file from the list of files in variable `org-agenda-files'.
14064 These are the files which are being checked for agenda entries.
14065 Optional argument FILE means, use this file instead of the current."
14066 (interactive)
14067 (let* ((org-agenda-skip-unavailable-files nil)
14068 (file (or file buffer-file-name))
14069 (true-file (file-truename file))
14070 (afile (abbreviate-file-name file))
14071 (files (delq nil (mapcar
14072 (lambda (x)
14073 (if (equal true-file
14074 (file-truename x))
14075 nil x))
14076 (org-agenda-files t)))))
14077 (if (not (= (length files) (length (org-agenda-files t))))
14078 (progn
14079 (org-store-new-agenda-file-list files)
14080 (org-install-agenda-files-menu)
14081 (message "Removed file: %s" afile))
14082 (message "File was not in list: %s (not removed)" afile))))
14084 (defun org-file-menu-entry (file)
14085 (vector file (list 'find-file file) t))
14087 (defun org-check-agenda-file (file)
14088 "Make sure FILE exists. If not, ask user what to do."
14089 (when (not (file-exists-p file))
14090 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14091 (abbreviate-file-name file))
14092 (let ((r (downcase (read-char-exclusive))))
14093 (cond
14094 ((equal r ?r)
14095 (org-remove-file file)
14096 (throw 'nextfile t))
14097 (t (error "Abort"))))))
14099 (defun org-get-agenda-file-buffer (file)
14100 "Get a buffer visiting FILE. If the buffer needs to be created, add
14101 it to the list of buffers which might be released later."
14102 (let ((buf (org-find-base-buffer-visiting file)))
14103 (if buf
14104 buf ; just return it
14105 ;; Make a new buffer and remember it
14106 (setq buf (find-file-noselect file))
14107 (if buf (push buf org-agenda-new-buffers))
14108 buf)))
14110 (defun org-release-buffers (blist)
14111 "Release all buffers in list, asking the user for confirmation when needed.
14112 When a buffer is unmodified, it is just killed. When modified, it is saved
14113 \(if the user agrees) and then killed."
14114 (let (buf file)
14115 (while (setq buf (pop blist))
14116 (setq file (buffer-file-name buf))
14117 (when (and (buffer-modified-p buf)
14118 file
14119 (y-or-n-p (format "Save file %s? " file)))
14120 (with-current-buffer buf (save-buffer)))
14121 (kill-buffer buf))))
14123 (defun org-prepare-agenda-buffers (files)
14124 "Create buffers for all agenda files, protect archived trees and comments."
14125 (interactive)
14126 (let ((pa '(:org-archived t))
14127 (pc '(:org-comment t))
14128 (pall '(:org-archived t :org-comment t))
14129 (inhibit-read-only t)
14130 (rea (concat ":" org-archive-tag ":"))
14131 bmp file re)
14132 (save-excursion
14133 (save-restriction
14134 (while (setq file (pop files))
14135 (catch 'nextfile
14136 (if (bufferp file)
14137 (set-buffer file)
14138 (org-check-agenda-file file)
14139 (set-buffer (org-get-agenda-file-buffer file)))
14140 (widen)
14141 (setq bmp (buffer-modified-p))
14142 (org-refresh-category-properties)
14143 (setq org-todo-keywords-for-agenda
14144 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14145 (setq org-done-keywords-for-agenda
14146 (append org-done-keywords-for-agenda org-done-keywords))
14147 (setq org-todo-keyword-alist-for-agenda
14148 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14149 (setq org-drawers-for-agenda
14150 (append org-drawers-for-agenda org-drawers))
14151 (setq org-tag-alist-for-agenda
14152 (append org-tag-alist-for-agenda org-tag-alist))
14154 (save-excursion
14155 (remove-text-properties (point-min) (point-max) pall)
14156 (when org-agenda-skip-archived-trees
14157 (goto-char (point-min))
14158 (while (re-search-forward rea nil t)
14159 (if (org-on-heading-p t)
14160 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14161 (goto-char (point-min))
14162 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14163 (while (re-search-forward re nil t)
14164 (add-text-properties
14165 (match-beginning 0) (org-end-of-subtree t) pc)))
14166 (set-buffer-modified-p bmp)))))
14167 (setq org-todo-keyword-alist-for-agenda
14168 (org-uniquify org-todo-keyword-alist-for-agenda)
14169 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14171 ;;;; Embedded LaTeX
14173 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14174 "Keymap for the minor `org-cdlatex-mode'.")
14176 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14177 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14178 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14179 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14180 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14182 (defvar org-cdlatex-texmathp-advice-is-done nil
14183 "Flag remembering if we have applied the advice to texmathp already.")
14185 (define-minor-mode org-cdlatex-mode
14186 "Toggle the minor `org-cdlatex-mode'.
14187 This mode supports entering LaTeX environment and math in LaTeX fragments
14188 in Org-mode.
14189 \\{org-cdlatex-mode-map}"
14190 nil " OCDL" nil
14191 (when org-cdlatex-mode (require 'cdlatex))
14192 (unless org-cdlatex-texmathp-advice-is-done
14193 (setq org-cdlatex-texmathp-advice-is-done t)
14194 (defadvice texmathp (around org-math-always-on activate)
14195 "Always return t in org-mode buffers.
14196 This is because we want to insert math symbols without dollars even outside
14197 the LaTeX math segments. If Orgmode thinks that point is actually inside
14198 an embedded LaTeX fragment, let texmathp do its job.
14199 \\[org-cdlatex-mode-map]"
14200 (interactive)
14201 (let (p)
14202 (cond
14203 ((not (org-mode-p)) ad-do-it)
14204 ((eq this-command 'cdlatex-math-symbol)
14205 (setq ad-return-value t
14206 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14208 (let ((p (org-inside-LaTeX-fragment-p)))
14209 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14210 (setq ad-return-value t
14211 texmathp-why '("Org-mode embedded math" . 0))
14212 (if p ad-do-it)))))))))
14214 (defun turn-on-org-cdlatex ()
14215 "Unconditionally turn on `org-cdlatex-mode'."
14216 (org-cdlatex-mode 1))
14218 (defun org-inside-LaTeX-fragment-p ()
14219 "Test if point is inside a LaTeX fragment.
14220 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14221 sequence appearing also before point.
14222 Even though the matchers for math are configurable, this function assumes
14223 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14224 delimiters are skipped when they have been removed by customization.
14225 The return value is nil, or a cons cell with the delimiter and
14226 and the position of this delimiter.
14228 This function does a reasonably good job, but can locally be fooled by
14229 for example currency specifications. For example it will assume being in
14230 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14231 fragments that are properly closed, but during editing, we have to live
14232 with the uncertainty caused by missing closing delimiters. This function
14233 looks only before point, not after."
14234 (catch 'exit
14235 (let ((pos (point))
14236 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14237 (lim (progn
14238 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14239 (point)))
14240 dd-on str (start 0) m re)
14241 (goto-char pos)
14242 (when dodollar
14243 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14244 re (nth 1 (assoc "$" org-latex-regexps)))
14245 (while (string-match re str start)
14246 (cond
14247 ((= (match-end 0) (length str))
14248 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14249 ((= (match-end 0) (- (length str) 5))
14250 (throw 'exit nil))
14251 (t (setq start (match-end 0))))))
14252 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14253 (goto-char pos)
14254 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14255 (and (match-beginning 2) (throw 'exit nil))
14256 ;; count $$
14257 (while (re-search-backward "\\$\\$" lim t)
14258 (setq dd-on (not dd-on)))
14259 (goto-char pos)
14260 (if dd-on (cons "$$" m))))))
14263 (defun org-try-cdlatex-tab ()
14264 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14265 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14266 - inside a LaTeX fragment, or
14267 - after the first word in a line, where an abbreviation expansion could
14268 insert a LaTeX environment."
14269 (when org-cdlatex-mode
14270 (cond
14271 ((save-excursion
14272 (skip-chars-backward "a-zA-Z0-9*")
14273 (skip-chars-backward " \t")
14274 (bolp))
14275 (cdlatex-tab) t)
14276 ((org-inside-LaTeX-fragment-p)
14277 (cdlatex-tab) t)
14278 (t nil))))
14280 (defun org-cdlatex-underscore-caret (&optional arg)
14281 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14282 Revert to the normal definition outside of these fragments."
14283 (interactive "P")
14284 (if (org-inside-LaTeX-fragment-p)
14285 (call-interactively 'cdlatex-sub-superscript)
14286 (let (org-cdlatex-mode)
14287 (call-interactively (key-binding (vector last-input-event))))))
14289 (defun org-cdlatex-math-modify (&optional arg)
14290 "Execute `cdlatex-math-modify' in LaTeX fragments.
14291 Revert to the normal definition outside of these fragments."
14292 (interactive "P")
14293 (if (org-inside-LaTeX-fragment-p)
14294 (call-interactively 'cdlatex-math-modify)
14295 (let (org-cdlatex-mode)
14296 (call-interactively (key-binding (vector last-input-event))))))
14298 (defvar org-latex-fragment-image-overlays nil
14299 "List of overlays carrying the images of latex fragments.")
14300 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14302 (defun org-remove-latex-fragment-image-overlays ()
14303 "Remove all overlays with LaTeX fragment images in current buffer."
14304 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14305 (setq org-latex-fragment-image-overlays nil))
14307 (defun org-preview-latex-fragment (&optional subtree)
14308 "Preview the LaTeX fragment at point, or all locally or globally.
14309 If the cursor is in a LaTeX fragment, create the image and overlay
14310 it over the source code. If there is no fragment at point, display
14311 all fragments in the current text, from one headline to the next. With
14312 prefix SUBTREE, display all fragments in the current subtree. With a
14313 double prefix `C-u C-u', or when the cursor is before the first headline,
14314 display all fragments in the buffer.
14315 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14316 (interactive "P")
14317 (org-remove-latex-fragment-image-overlays)
14318 (save-excursion
14319 (save-restriction
14320 (let (beg end at msg)
14321 (cond
14322 ((or (equal subtree '(16))
14323 (not (save-excursion
14324 (re-search-backward (concat "^" outline-regexp) nil t))))
14325 (setq beg (point-min) end (point-max)
14326 msg "Creating images for buffer...%s"))
14327 ((equal subtree '(4))
14328 (org-back-to-heading)
14329 (setq beg (point) end (org-end-of-subtree t)
14330 msg "Creating images for subtree...%s"))
14332 (if (setq at (org-inside-LaTeX-fragment-p))
14333 (goto-char (max (point-min) (- (cdr at) 2)))
14334 (org-back-to-heading))
14335 (setq beg (point) end (progn (outline-next-heading) (point))
14336 msg (if at "Creating image...%s"
14337 "Creating images for entry...%s"))))
14338 (message msg "")
14339 (narrow-to-region beg end)
14340 (goto-char beg)
14341 (org-format-latex
14342 (concat "ltxpng/" (file-name-sans-extension
14343 (file-name-nondirectory
14344 buffer-file-name)))
14345 default-directory 'overlays msg at 'forbuffer)
14346 (message msg "done. Use `C-c C-c' to remove images.")))))
14348 (defvar org-latex-regexps
14349 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14350 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14351 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14352 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14353 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14354 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14355 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14356 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14357 "Regular expressions for matching embedded LaTeX.")
14359 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14360 "Replace LaTeX fragments with links to an image, and produce images.
14361 Some of the options can be changed using the variable
14362 `org-format-latex-options'."
14363 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14364 (let* ((prefixnodir (file-name-nondirectory prefix))
14365 (absprefix (expand-file-name prefix dir))
14366 (todir (file-name-directory absprefix))
14367 (opt org-format-latex-options)
14368 (matchers (plist-get opt :matchers))
14369 (re-list org-latex-regexps)
14370 (cnt 0) txt link beg end re e checkdir
14371 executables-checked
14372 m n block linkfile movefile ov)
14373 ;; Check if there are old images files with this prefix, and remove them
14374 (when (file-directory-p todir)
14375 (mapc 'delete-file
14376 (directory-files
14377 todir 'full
14378 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14379 ;; Check the different regular expressions
14380 (while (setq e (pop re-list))
14381 (setq m (car e) re (nth 1 e) n (nth 2 e)
14382 block (if (nth 3 e) "\n\n" ""))
14383 (when (member m matchers)
14384 (goto-char (point-min))
14385 (while (re-search-forward re nil t)
14386 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14387 (not (get-text-property (match-beginning n)
14388 'org-protected))
14389 (or (not overlays)
14390 (not (eq (get-char-property (match-beginning n)
14391 'org-overlay-type)
14392 'org-latex-overlay))))
14393 (setq txt (match-string n)
14394 beg (match-beginning n) end (match-end n)
14395 cnt (1+ cnt)
14396 linkfile (format "%s_%04d.png" prefix cnt)
14397 movefile (format "%s_%04d.png" absprefix cnt)
14398 link (concat block "[[file:" linkfile "]]" block))
14399 (if msg (message msg cnt))
14400 (goto-char beg)
14401 (unless checkdir ; make sure the directory exists
14402 (setq checkdir t)
14403 (or (file-directory-p todir) (make-directory todir)))
14405 (unless executables-checked
14406 (org-check-external-command
14407 "latex" "needed to convert LaTeX fragments to images")
14408 (org-check-external-command
14409 "dvipng" "needed to convert LaTeX fragments to images")
14410 (setq executables-checked t))
14412 (org-create-formula-image
14413 txt movefile opt forbuffer)
14414 (if overlays
14415 (progn
14416 (mapc (lambda (o)
14417 (if (eq (org-overlay-get o 'org-overlay-type)
14418 'org-latex-overlay)
14419 (org-delete-overlay o)))
14420 (org-overlays-in beg end))
14421 (setq ov (org-make-overlay beg end))
14422 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14423 (if (featurep 'xemacs)
14424 (progn
14425 (org-overlay-put ov 'invisible t)
14426 (org-overlay-put
14427 ov 'end-glyph
14428 (make-glyph (vector 'png :file movefile))))
14429 (org-overlay-put
14430 ov 'display
14431 (list 'image :type 'png :file movefile :ascent 'center)))
14432 (push ov org-latex-fragment-image-overlays)
14433 (goto-char end))
14434 (delete-region beg end)
14435 (insert link))))))))
14437 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14438 ;; This function borrows from Ganesh Swami's latex2png.el
14439 (defun org-create-formula-image (string tofile options buffer)
14440 "This calls dvipng."
14441 (require 'org-latex)
14442 (let* ((tmpdir (if (featurep 'xemacs)
14443 (temp-directory)
14444 temporary-file-directory))
14445 (texfilebase (make-temp-name
14446 (expand-file-name "orgtex" tmpdir)))
14447 (texfile (concat texfilebase ".tex"))
14448 (dvifile (concat texfilebase ".dvi"))
14449 (pngfile (concat texfilebase ".png"))
14450 (fnh (if (featurep 'xemacs)
14451 (font-height (get-face-font 'default))
14452 (face-attribute 'default :height nil)))
14453 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14454 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14455 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14456 "Black"))
14457 (bg (or (plist-get options (if buffer :background :html-background))
14458 "Transparent")))
14459 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14460 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14461 (with-temp-file texfile
14462 (insert org-format-latex-header
14463 (if org-export-latex-packages-alist
14464 (concat "\n"
14465 (mapconcat (lambda(p)
14466 (if (equal "" (car p))
14467 (format "\\usepackage{%s}" (cadr p))
14468 (format "\\usepackage[%s]{%s}"
14469 (car p) (cadr p))))
14470 org-export-latex-packages-alist "\n"))
14472 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14473 (let ((dir default-directory))
14474 (condition-case nil
14475 (progn
14476 (cd tmpdir)
14477 (call-process "latex" nil nil nil texfile))
14478 (error nil))
14479 (cd dir))
14480 (if (not (file-exists-p dvifile))
14481 (progn (message "Failed to create dvi file from %s" texfile) nil)
14482 (condition-case nil
14483 (call-process "dvipng" nil nil nil
14484 "-fg" fg "-bg" bg
14485 "-D" dpi
14486 ;;"-x" scale "-y" scale
14487 "-T" "tight"
14488 "-o" pngfile
14489 dvifile)
14490 (error nil))
14491 (if (not (file-exists-p pngfile))
14492 (progn (message "Failed to create png file from %s" texfile) nil)
14493 ;; Use the requested file name and clean up
14494 (copy-file pngfile tofile 'replace)
14495 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14496 (delete-file (concat texfilebase e)))
14497 pngfile))))
14499 (defun org-dvipng-color (attr)
14500 "Return an rgb color specification for dvipng."
14501 (apply 'format "rgb %s %s %s"
14502 (mapcar 'org-normalize-color
14503 (color-values (face-attribute 'default attr nil)))))
14505 (defun org-normalize-color (value)
14506 "Return string to be used as color value for an RGB component."
14507 (format "%g" (/ value 65535.0)))
14509 ;;;; Key bindings
14511 ;; Make `C-c C-x' a prefix key
14512 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14514 ;; TAB key with modifiers
14515 (org-defkey org-mode-map "\C-i" 'org-cycle)
14516 (org-defkey org-mode-map [(tab)] 'org-cycle)
14517 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14518 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14519 (org-defkey org-mode-map "\M-\t" 'org-complete)
14520 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14521 ;; The following line is necessary under Suse GNU/Linux
14522 (unless (featurep 'xemacs)
14523 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14524 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14525 (define-key org-mode-map [backtab] 'org-shifttab)
14527 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14528 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14529 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14531 ;; Cursor keys with modifiers
14532 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14533 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14534 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14535 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14537 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14538 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14539 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14540 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14542 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14543 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14544 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14545 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14547 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14548 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14550 ;;; Extra keys for tty access.
14551 ;; We only set them when really needed because otherwise the
14552 ;; menus don't show the simple keys
14554 (when (or org-use-extra-keys
14555 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14556 (not window-system))
14557 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14558 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14559 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14560 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14561 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14562 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14563 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14564 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14565 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14566 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14567 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14568 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14569 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14570 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14571 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14572 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14573 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14574 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14575 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14576 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14577 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14578 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14579 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14580 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14581 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14582 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14583 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14584 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14586 ;; All the other keys
14588 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14589 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14590 (if (boundp 'narrow-map)
14591 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14592 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14593 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14594 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14595 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14596 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14597 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14598 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14599 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14600 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14601 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14602 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14603 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14604 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14605 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14606 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14607 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14608 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14609 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14610 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14611 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14612 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14613 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14614 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14615 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14616 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14617 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14618 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14619 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14620 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14621 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14622 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14623 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14624 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14625 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14626 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14627 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14628 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14629 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14630 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14631 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14632 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14633 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14634 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14635 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14636 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14637 (org-defkey org-mode-map "\C-c^" 'org-sort)
14638 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14639 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14640 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14641 (org-defkey org-mode-map "\C-m" 'org-return)
14642 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14643 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14644 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14645 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14646 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14647 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14648 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14649 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14650 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14651 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14652 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14653 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14654 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14655 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14656 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14657 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14658 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14659 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14660 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14661 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14662 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14664 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14665 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14666 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14667 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14669 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14670 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14671 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14672 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14673 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14674 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14675 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14676 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14677 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14678 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14679 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14680 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14681 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14682 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14683 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14685 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14686 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14687 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14688 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14690 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14692 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14694 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14695 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14697 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14700 (when (featurep 'xemacs)
14701 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14704 (defconst org-speed-commands-default
14706 ("a" . org-agenda)
14707 ("/" . org-sparse-tree)
14708 (";" . org-set-tags-command)
14709 ("I" . org-clock-in)
14710 ("O" . org-clock-out)
14711 ("c" . org-cycle)
14712 ("C" . org-shifttab)
14713 ("n" . outline-next-visible-heading)
14714 ("p" . outline-previous-visible-heading)
14715 ("f" . org-forward-same-level)
14716 ("b" . org-backward-same-level)
14717 ("u" . outline-up-heading)
14718 ("U" . org-shiftmetaup)
14719 ("D" . org-shiftmetadown)
14720 ("r" . org-metaright)
14721 ("l" . org-metaleft)
14722 ("R" . org-shiftmetaright)
14723 ("L" . org-shiftmetaleft)
14724 ("i" . (progn (forward-char 1) (call-interactively
14725 'org-insert-heading-respect-content)))
14726 ("o" . org-open-at-point)
14727 ("t" . org-todo)
14728 ("j" . org-goto)
14729 ("g" . (org-refile t))
14730 ("e" . org-set-effort)
14731 ("0" . (org-priority ?\ ))
14732 ("1" . (org-priority ?A))
14733 ("2" . (org-priority ?B))
14734 ("3" . (org-priority ?C))
14735 ("." . outline-mark-subtree)
14736 ("^" . org-sort)
14737 ("w" . org-refile)
14738 ("a" . org-archive-subtree-default-with-confirmation)
14739 ("/" . org-sparse-tree)
14740 ("?" . org-speed-command-help)
14742 "The default speed commands.")
14744 (defun org-print-speed-command (e)
14745 (princ (car e))
14746 (princ " ")
14747 (if (symbolp (cdr e))
14748 (princ (symbol-name (cdr e)))
14749 (prin1 (cdr e)))
14750 (princ "\n"))
14752 (defun org-speed-command-help ()
14753 "Show the available speed commands."
14754 (interactive)
14755 (if (not org-use-speed-commands)
14756 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
14757 (with-output-to-temp-buffer "*Help*"
14758 (princ "Speed commands\n==============\n")
14759 (mapc 'org-print-speed-command org-speed-commands-user)
14760 (princ "\n")
14761 (mapc 'org-print-speed-command org-speed-commands-default))))
14763 (defvar org-self-insert-command-undo-counter 0)
14765 (defvar org-table-auto-blank-field) ; defined in org-table.el
14766 (defvar org-speed-command nil)
14767 (defun org-self-insert-command (N)
14768 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14769 If the cursor is in a table looking at whitespace, the whitespace is
14770 overwritten, and the table is not marked as requiring realignment."
14771 (interactive "p")
14772 (cond
14773 ((and org-use-speed-commands
14774 (bolp)
14775 (looking-at outline-regexp)
14776 (setq
14777 org-speed-command
14778 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
14779 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
14780 (cond
14781 ((commandp org-speed-command)
14782 (setq this-command org-speed-command)
14783 (call-interactively org-speed-command))
14784 ((functionp org-speed-command)
14785 (funcall org-speed-command))
14786 ((and org-speed-command (listp org-speed-command))
14787 (eval org-speed-command))
14788 (t (let (org-use-speed-commands)
14789 (call-interactively 'org-self-insert-command)))))
14790 ((and
14791 (org-table-p)
14792 (progn
14793 ;; check if we blank the field, and if that triggers align
14794 (and (featurep 'org-table) org-table-auto-blank-field
14795 (member last-command
14796 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14797 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14798 ;; got extra space, this field does not determine column width
14799 (let (org-table-may-need-update) (org-table-blank-field))
14800 ;; no extra space, this field may determine column width
14801 (org-table-blank-field)))
14803 (eq N 1)
14804 (looking-at "[^|\n]* |"))
14805 (let (org-table-may-need-update)
14806 (goto-char (1- (match-end 0)))
14807 (delete-backward-char 1)
14808 (goto-char (match-beginning 0))
14809 (self-insert-command N)))
14811 (setq org-table-may-need-update t)
14812 (self-insert-command N)
14813 (org-fix-tags-on-the-fly)
14814 (if org-self-insert-cluster-for-undo
14815 (if (not (eq last-command 'org-self-insert-command))
14816 (setq org-self-insert-command-undo-counter 1)
14817 (if (>= org-self-insert-command-undo-counter 20)
14818 (setq org-self-insert-command-undo-counter 1)
14819 (and (> org-self-insert-command-undo-counter 0)
14820 buffer-undo-list
14821 (not (cadr buffer-undo-list)) ; remove nil entry
14822 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14823 (setq org-self-insert-command-undo-counter
14824 (1+ org-self-insert-command-undo-counter))))))))
14826 (defun org-fix-tags-on-the-fly ()
14827 (when (and (equal (char-after (point-at-bol)) ?*)
14828 (org-on-heading-p))
14829 (org-align-tags-here org-tags-column)))
14831 (defun org-delete-backward-char (N)
14832 "Like `delete-backward-char', insert whitespace at field end in tables.
14833 When deleting backwards, in tables this function will insert whitespace in
14834 front of the next \"|\" separator, to keep the table aligned. The table will
14835 still be marked for re-alignment if the field did fill the entire column,
14836 because, in this case the deletion might narrow the column."
14837 (interactive "p")
14838 (if (and (org-table-p)
14839 (eq N 1)
14840 (string-match "|" (buffer-substring (point-at-bol) (point)))
14841 (looking-at ".*?|"))
14842 (let ((pos (point))
14843 (noalign (looking-at "[^|\n\r]* |"))
14844 (c org-table-may-need-update))
14845 (backward-delete-char N)
14846 (skip-chars-forward "^|")
14847 (insert " ")
14848 (goto-char (1- pos))
14849 ;; noalign: if there were two spaces at the end, this field
14850 ;; does not determine the width of the column.
14851 (if noalign (setq org-table-may-need-update c)))
14852 (backward-delete-char N)
14853 (org-fix-tags-on-the-fly)))
14855 (defun org-delete-char (N)
14856 "Like `delete-char', but insert whitespace at field end in tables.
14857 When deleting characters, in tables this function will insert whitespace in
14858 front of the next \"|\" separator, to keep the table aligned. The table will
14859 still be marked for re-alignment if the field did fill the entire column,
14860 because, in this case the deletion might narrow the column."
14861 (interactive "p")
14862 (if (and (org-table-p)
14863 (not (bolp))
14864 (not (= (char-after) ?|))
14865 (eq N 1))
14866 (if (looking-at ".*?|")
14867 (let ((pos (point))
14868 (noalign (looking-at "[^|\n\r]* |"))
14869 (c org-table-may-need-update))
14870 (replace-match (concat
14871 (substring (match-string 0) 1 -1)
14872 " |"))
14873 (goto-char pos)
14874 ;; noalign: if there were two spaces at the end, this field
14875 ;; does not determine the width of the column.
14876 (if noalign (setq org-table-may-need-update c)))
14877 (delete-char N))
14878 (delete-char N)
14879 (org-fix-tags-on-the-fly)))
14881 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14882 (put 'org-self-insert-command 'delete-selection t)
14883 (put 'orgtbl-self-insert-command 'delete-selection t)
14884 (put 'org-delete-char 'delete-selection 'supersede)
14885 (put 'org-delete-backward-char 'delete-selection 'supersede)
14886 (put 'org-yank 'delete-selection 'yank)
14888 ;; Make `flyspell-mode' delay after some commands
14889 (put 'org-self-insert-command 'flyspell-delayed t)
14890 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14891 (put 'org-delete-char 'flyspell-delayed t)
14892 (put 'org-delete-backward-char 'flyspell-delayed t)
14894 ;; Make pabbrev-mode expand after org-mode commands
14895 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14896 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14898 ;; How to do this: Measure non-white length of current string
14899 ;; If equal to column width, we should realign.
14901 (defun org-remap (map &rest commands)
14902 "In MAP, remap the functions given in COMMANDS.
14903 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14904 (let (new old)
14905 (while commands
14906 (setq old (pop commands) new (pop commands))
14907 (if (fboundp 'command-remapping)
14908 (org-defkey map (vector 'remap old) new)
14909 (substitute-key-definition old new map global-map)))))
14911 (when (eq org-enable-table-editor 'optimized)
14912 ;; If the user wants maximum table support, we need to hijack
14913 ;; some standard editing functions
14914 (org-remap org-mode-map
14915 'self-insert-command 'org-self-insert-command
14916 'delete-char 'org-delete-char
14917 'delete-backward-char 'org-delete-backward-char)
14918 (org-defkey org-mode-map "|" 'org-force-self-insert))
14920 (defvar org-ctrl-c-ctrl-c-hook nil
14921 "Hook for functions attaching themselves to `C-c C-c'.
14922 This can be used to add additional functionality to the C-c C-c key which
14923 executes context-dependent commands.
14924 Each function will be called with no arguments. The function must check
14925 if the context is appropriate for it to act. If yes, it should do its
14926 thing and then return a non-nil value. If the context is wrong,
14927 just do nothing and return nil.")
14929 (defvar org-tab-first-hook nil
14930 "Hook for functions to attach themselves to TAB.
14931 See `org-ctrl-c-ctrl-c-hook' for more information.
14932 This hook runs as the first action when TAB is pressed, even before
14933 `org-cycle' messes around with the `outline-regexp' to cater for
14934 inline tasks and plain list item folding.
14935 If any function in this hook returns t, not other actions like table
14936 field motion visibility cycling will be done.")
14938 (defvar org-tab-after-check-for-table-hook nil
14939 "Hook for functions to attach themselves to TAB.
14940 See `org-ctrl-c-ctrl-c-hook' for more information.
14941 This hook runs after it has been established that the cursor is not in a
14942 table, but before checking if the cursor is in a headline or if global cycling
14943 should be done.
14944 If any function in this hook returns t, not other actions like visibility
14945 cycling will be done.")
14947 (defvar org-tab-after-check-for-cycling-hook nil
14948 "Hook for functions to attach themselves to TAB.
14949 See `org-ctrl-c-ctrl-c-hook' for more information.
14950 This hook runs after it has been established that not table field motion and
14951 not visibility should be done because of current context. This is probably
14952 the place where a package like yasnippets can hook in.")
14954 (defvar org-tab-before-tab-emulation-hook nil
14955 "Hook for functions to attach themselves to TAB.
14956 See `org-ctrl-c-ctrl-c-hook' for more information.
14957 This hook runs after every other options for TAB have been exhausted, but
14958 before indentation and \t insertion takes place.")
14960 (defvar org-metaleft-hook nil
14961 "Hook for functions attaching themselves to `M-left'.
14962 See `org-ctrl-c-ctrl-c-hook' for more information.")
14963 (defvar org-metaright-hook nil
14964 "Hook for functions attaching themselves to `M-right'.
14965 See `org-ctrl-c-ctrl-c-hook' for more information.")
14966 (defvar org-metaup-hook nil
14967 "Hook for functions attaching themselves to `M-up'.
14968 See `org-ctrl-c-ctrl-c-hook' for more information.")
14969 (defvar org-metadown-hook nil
14970 "Hook for functions attaching themselves to `M-down'.
14971 See `org-ctrl-c-ctrl-c-hook' for more information.")
14972 (defvar org-shiftmetaleft-hook nil
14973 "Hook for functions attaching themselves to `M-S-left'.
14974 See `org-ctrl-c-ctrl-c-hook' for more information.")
14975 (defvar org-shiftmetaright-hook nil
14976 "Hook for functions attaching themselves to `M-S-right'.
14977 See `org-ctrl-c-ctrl-c-hook' for more information.")
14978 (defvar org-shiftmetaup-hook nil
14979 "Hook for functions attaching themselves to `M-S-up'.
14980 See `org-ctrl-c-ctrl-c-hook' for more information.")
14981 (defvar org-shiftmetadown-hook nil
14982 "Hook for functions attaching themselves to `M-S-down'.
14983 See `org-ctrl-c-ctrl-c-hook' for more information.")
14984 (defvar org-metareturn-hook nil
14985 "Hook for functions attaching themselves to `M-RET'.
14986 See `org-ctrl-c-ctrl-c-hook' for more information.")
14988 (defun org-modifier-cursor-error ()
14989 "Throw an error, a modified cursor command was applied in wrong context."
14990 (error "This command is active in special context like tables, headlines or items"))
14992 (defun org-shiftselect-error ()
14993 "Throw an error because Shift-Cursor command was applied in wrong context."
14994 (if (and (boundp 'shift-select-mode) shift-select-mode)
14995 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
14996 (error "This command works only in special context like headlines or timestamps")))
14998 (defun org-call-for-shift-select (cmd)
14999 (let ((this-command-keys-shift-translated t))
15000 (call-interactively cmd)))
15002 (defun org-shifttab (&optional arg)
15003 "Global visibility cycling or move to previous table field.
15004 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15005 on context.
15006 See the individual commands for more information."
15007 (interactive "P")
15008 (cond
15009 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15010 ((integerp arg)
15011 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15012 (message "Content view to level: %d" arg)
15013 (org-content (prefix-numeric-value arg2))
15014 (setq org-cycle-global-status 'overview)))
15015 (t (call-interactively 'org-global-cycle))))
15017 (defun org-shiftmetaleft ()
15018 "Promote subtree or delete table column.
15019 Calls `org-promote-subtree', `org-outdent-item',
15020 or `org-table-delete-column', depending on context.
15021 See the individual commands for more information."
15022 (interactive)
15023 (cond
15024 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15025 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15026 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15027 ((org-at-item-p) (call-interactively 'org-outdent-item))
15028 (t (org-modifier-cursor-error))))
15030 (defun org-shiftmetaright ()
15031 "Demote subtree or insert table column.
15032 Calls `org-demote-subtree', `org-indent-item',
15033 or `org-table-insert-column', depending on context.
15034 See the individual commands for more information."
15035 (interactive)
15036 (cond
15037 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15038 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15039 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15040 ((org-at-item-p) (call-interactively 'org-indent-item))
15041 (t (org-modifier-cursor-error))))
15043 (defun org-shiftmetaup (&optional arg)
15044 "Move subtree up or kill table row.
15045 Calls `org-move-subtree-up' or `org-table-kill-row' or
15046 `org-move-item-up' depending on context. See the individual commands
15047 for more information."
15048 (interactive "P")
15049 (cond
15050 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15051 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15052 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15053 ((org-at-item-p) (call-interactively 'org-move-item-up))
15054 (t (org-modifier-cursor-error))))
15056 (defun org-shiftmetadown (&optional arg)
15057 "Move subtree down or insert table row.
15058 Calls `org-move-subtree-down' or `org-table-insert-row' or
15059 `org-move-item-down', depending on context. See the individual
15060 commands for more information."
15061 (interactive "P")
15062 (cond
15063 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15064 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15065 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15066 ((org-at-item-p) (call-interactively 'org-move-item-down))
15067 (t (org-modifier-cursor-error))))
15069 (defun org-metaleft (&optional arg)
15070 "Promote heading or move table column to left.
15071 Calls `org-do-promote' or `org-table-move-column', depending on context.
15072 With no specific context, calls the Emacs default `backward-word'.
15073 See the individual commands for more information."
15074 (interactive "P")
15075 (cond
15076 ((run-hook-with-args-until-success 'org-metaleft-hook))
15077 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15078 ((or (org-on-heading-p)
15079 (and (org-region-active-p)
15080 (save-excursion
15081 (goto-char (region-beginning))
15082 (org-on-heading-p))))
15083 (call-interactively 'org-do-promote))
15084 ((or (org-at-item-p)
15085 (and (org-region-active-p)
15086 (save-excursion
15087 (goto-char (region-beginning))
15088 (org-at-item-p))))
15089 (call-interactively 'org-outdent-item))
15090 (t (call-interactively 'backward-word))))
15092 (defun org-metaright (&optional arg)
15093 "Demote subtree or move table column to right.
15094 Calls `org-do-demote' or `org-table-move-column', depending on context.
15095 With no specific context, calls the Emacs default `forward-word'.
15096 See the individual commands for more information."
15097 (interactive "P")
15098 (cond
15099 ((run-hook-with-args-until-success 'org-metaright-hook))
15100 ((org-at-table-p) (call-interactively 'org-table-move-column))
15101 ((or (org-on-heading-p)
15102 (and (org-region-active-p)
15103 (save-excursion
15104 (goto-char (region-beginning))
15105 (org-on-heading-p))))
15106 (call-interactively 'org-do-demote))
15107 ((or (org-at-item-p)
15108 (and (org-region-active-p)
15109 (save-excursion
15110 (goto-char (region-beginning))
15111 (org-at-item-p))))
15112 (call-interactively 'org-indent-item))
15113 (t (call-interactively 'forward-word))))
15115 (defun org-metaup (&optional arg)
15116 "Move subtree up or move table row up.
15117 Calls `org-move-subtree-up' or `org-table-move-row' or
15118 `org-move-item-up', depending on context. See the individual commands
15119 for more information."
15120 (interactive "P")
15121 (cond
15122 ((run-hook-with-args-until-success 'org-metaup-hook))
15123 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15124 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15125 ((org-at-item-p) (call-interactively 'org-move-item-up))
15126 (t (transpose-lines 1) (beginning-of-line -1))))
15128 (defun org-metadown (&optional arg)
15129 "Move subtree down or move table row down.
15130 Calls `org-move-subtree-down' or `org-table-move-row' or
15131 `org-move-item-down', depending on context. See the individual
15132 commands for more information."
15133 (interactive "P")
15134 (cond
15135 ((run-hook-with-args-until-success 'org-metadown-hook))
15136 ((org-at-table-p) (call-interactively 'org-table-move-row))
15137 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15138 ((org-at-item-p) (call-interactively 'org-move-item-down))
15139 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15141 (defun org-shiftup (&optional arg)
15142 "Increase item in timestamp or increase priority of current headline.
15143 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15144 depending on context. See the individual commands for more information."
15145 (interactive "P")
15146 (cond
15147 ((and org-support-shift-select (org-region-active-p))
15148 (org-call-for-shift-select 'previous-line))
15149 ((org-at-timestamp-p t)
15150 (call-interactively (if org-edit-timestamp-down-means-later
15151 'org-timestamp-down 'org-timestamp-up)))
15152 ((and (not (eq org-support-shift-select 'always))
15153 org-enable-priority-commands
15154 (org-on-heading-p))
15155 (call-interactively 'org-priority-up))
15156 ((and (not org-support-shift-select) (org-at-item-p))
15157 (call-interactively 'org-previous-item))
15158 ((org-clocktable-try-shift 'up arg))
15159 (org-support-shift-select
15160 (org-call-for-shift-select 'previous-line))
15161 (t (org-shiftselect-error))))
15163 (defun org-shiftdown (&optional arg)
15164 "Decrease item in timestamp or decrease priority of current headline.
15165 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15166 depending on context. See the individual commands for more information."
15167 (interactive "P")
15168 (cond
15169 ((and org-support-shift-select (org-region-active-p))
15170 (org-call-for-shift-select 'next-line))
15171 ((org-at-timestamp-p t)
15172 (call-interactively (if org-edit-timestamp-down-means-later
15173 'org-timestamp-up 'org-timestamp-down)))
15174 ((and (not (eq org-support-shift-select 'always))
15175 org-enable-priority-commands
15176 (org-on-heading-p))
15177 (call-interactively 'org-priority-down))
15178 ((and (not org-support-shift-select) (org-at-item-p))
15179 (call-interactively 'org-next-item))
15180 ((org-clocktable-try-shift 'down arg))
15181 (org-support-shift-select
15182 (org-call-for-shift-select 'next-line))
15183 (t (org-shiftselect-error))))
15185 (defun org-shiftright (&optional arg)
15186 "Cycle the thing at point or in the current line, depending on context.
15187 Depending on context, this does one of the following:
15189 - switch a timestamp at point one day into the future
15190 - on a headline, switch to the next TODO keyword.
15191 - on an item, switch entire list to the next bullet type
15192 - on a property line, switch to the next allowed value
15193 - on a clocktable definition line, move time block into the future"
15194 (interactive "P")
15195 (cond
15196 ((and org-support-shift-select (org-region-active-p))
15197 (org-call-for-shift-select 'forward-char))
15198 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15199 ((and (not (eq org-support-shift-select 'always))
15200 (org-on-heading-p))
15201 (let ((org-inhibit-logging
15202 (not org-treat-S-cursor-todo-selection-as-state-change))
15203 (org-inhibit-blocking
15204 (not org-treat-S-cursor-todo-selection-as-state-change)))
15205 (org-call-with-arg 'org-todo 'right)))
15206 ((or (and org-support-shift-select
15207 (not (eq org-support-shift-select 'always))
15208 (org-at-item-bullet-p))
15209 (and (not org-support-shift-select) (org-at-item-p)))
15210 (org-call-with-arg 'org-cycle-list-bullet nil))
15211 ((and (not (eq org-support-shift-select 'always))
15212 (org-at-property-p))
15213 (call-interactively 'org-property-next-allowed-value))
15214 ((org-clocktable-try-shift 'right arg))
15215 (org-support-shift-select
15216 (org-call-for-shift-select 'forward-char))
15217 (t (org-shiftselect-error))))
15219 (defun org-shiftleft (&optional arg)
15220 "Cycle the thing at point or in the current line, depending on context.
15221 Depending on context, this does one of the following:
15223 - switch a timestamp at point one day into the past
15224 - on a headline, switch to the previous TODO keyword.
15225 - on an item, switch entire list to the previous bullet type
15226 - on a property line, switch to the previous allowed value
15227 - on a clocktable definition line, move time block into the past"
15228 (interactive "P")
15229 (cond
15230 ((and org-support-shift-select (org-region-active-p))
15231 (org-call-for-shift-select 'backward-char))
15232 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15233 ((and (not (eq org-support-shift-select 'always))
15234 (org-on-heading-p))
15235 (let ((org-inhibit-logging
15236 (not org-treat-S-cursor-todo-selection-as-state-change))
15237 (org-inhibit-blocking
15238 (not org-treat-S-cursor-todo-selection-as-state-change)))
15239 (org-call-with-arg 'org-todo 'left)))
15240 ((or (and org-support-shift-select
15241 (not (eq org-support-shift-select 'always))
15242 (org-at-item-bullet-p))
15243 (and (not org-support-shift-select) (org-at-item-p)))
15244 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15245 ((and (not (eq org-support-shift-select 'always))
15246 (org-at-property-p))
15247 (call-interactively 'org-property-previous-allowed-value))
15248 ((org-clocktable-try-shift 'left arg))
15249 (org-support-shift-select
15250 (org-call-for-shift-select 'backward-char))
15251 (t (org-shiftselect-error))))
15253 (defun org-shiftcontrolright ()
15254 "Switch to next TODO set."
15255 (interactive)
15256 (cond
15257 ((and org-support-shift-select (org-region-active-p))
15258 (org-call-for-shift-select 'forward-word))
15259 ((and (not (eq org-support-shift-select 'always))
15260 (org-on-heading-p))
15261 (org-call-with-arg 'org-todo 'nextset))
15262 (org-support-shift-select
15263 (org-call-for-shift-select 'forward-word))
15264 (t (org-shiftselect-error))))
15266 (defun org-shiftcontrolleft ()
15267 "Switch to previous TODO set."
15268 (interactive)
15269 (cond
15270 ((and org-support-shift-select (org-region-active-p))
15271 (org-call-for-shift-select 'backward-word))
15272 ((and (not (eq org-support-shift-select 'always))
15273 (org-on-heading-p))
15274 (org-call-with-arg 'org-todo 'previousset))
15275 (org-support-shift-select
15276 (org-call-for-shift-select 'backward-word))
15277 (t (org-shiftselect-error))))
15279 (defun org-ctrl-c-ret ()
15280 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15281 (interactive)
15282 (cond
15283 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15284 (t (call-interactively 'org-insert-heading))))
15286 (defun org-copy-special ()
15287 "Copy region in table or copy current subtree.
15288 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15289 See the individual commands for more information."
15290 (interactive)
15291 (call-interactively
15292 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15294 (defun org-cut-special ()
15295 "Cut region in table or cut current subtree.
15296 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15297 See the individual commands for more information."
15298 (interactive)
15299 (call-interactively
15300 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15302 (defun org-paste-special (arg)
15303 "Paste rectangular region into table, or past subtree relative to level.
15304 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15305 See the individual commands for more information."
15306 (interactive "P")
15307 (if (org-at-table-p)
15308 (org-table-paste-rectangle)
15309 (org-paste-subtree arg)))
15311 (defun org-edit-special ()
15312 "Call a special editor for the stuff at point.
15313 When at a table, call the formula editor with `org-table-edit-formulas'.
15314 When at the first line of an src example, call `org-edit-src-code'.
15315 When in an #+include line, visit the include file. Otherwise call
15316 `ffap' to visit the file at point."
15317 (interactive)
15318 (cond
15319 ((org-at-table-p)
15320 (call-interactively 'org-table-edit-formulas))
15321 ((save-excursion
15322 (beginning-of-line 1)
15323 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15324 (find-file (org-trim (match-string 1))))
15325 ((org-edit-src-code))
15326 ((org-edit-fixed-width-region))
15327 (t (call-interactively 'ffap))))
15330 (defun org-ctrl-c-ctrl-c (&optional arg)
15331 "Set tags in headline, or update according to changed information at point.
15333 This command does many different things, depending on context:
15335 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15336 this is what we do.
15338 - If the cursor is on a statistics cookie, update it.
15340 - If the cursor is in a headline, prompt for tags and insert them
15341 into the current line, aligned to `org-tags-column'. When called
15342 with prefix arg, realign all tags in the current buffer.
15344 - If the cursor is in one of the special #+KEYWORD lines, this
15345 triggers scanning the buffer for these lines and updating the
15346 information.
15348 - If the cursor is inside a table, realign the table. This command
15349 works even if the automatic table editor has been turned off.
15351 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15352 the entire table.
15354 - If the cursor is at a footnote reference or definition, jump to
15355 the corresponding definition or references, respectively.
15357 - If the cursor is a the beginning of a dynamic block, update it.
15359 - If the cursor is inside a table created by the table.el package,
15360 activate that table.
15362 - If the current buffer is a remember buffer, close note and file
15363 it. A prefix argument of 1 files to the default location
15364 without further interaction. A prefix argument of 2 files to
15365 the currently clocking task.
15367 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15368 links in this buffer.
15370 - If the cursor is on a numbered item in a plain list, renumber the
15371 ordered list.
15373 - If the cursor is on a checkbox, toggle it."
15374 (interactive "P")
15375 (let ((org-enable-table-editor t))
15376 (cond
15377 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15378 org-occur-highlights
15379 org-latex-fragment-image-overlays)
15380 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15381 (org-remove-occur-highlights)
15382 (org-remove-latex-fragment-image-overlays)
15383 (message "Temporary highlights/overlays removed from current buffer"))
15384 ((and (local-variable-p 'org-finish-function (current-buffer))
15385 (fboundp org-finish-function))
15386 (funcall org-finish-function))
15387 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15388 ((org-at-property-p)
15389 (call-interactively 'org-property-action))
15390 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15391 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15392 (or (org-on-heading-p) (org-at-item-p)))
15393 (call-interactively 'org-update-statistics-cookies))
15394 ((org-on-heading-p) (call-interactively 'org-set-tags))
15395 ((org-at-table.el-p)
15396 (require 'table)
15397 (beginning-of-line 1)
15398 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15399 (call-interactively 'table-recognize-table))
15400 ((org-at-table-p)
15401 (org-table-maybe-eval-formula)
15402 (if arg
15403 (call-interactively 'org-table-recalculate)
15404 (org-table-maybe-recalculate-line))
15405 (call-interactively 'org-table-align))
15406 ((or (org-footnote-at-reference-p)
15407 (org-footnote-at-definition-p))
15408 (call-interactively 'org-footnote-action))
15409 ((org-at-item-checkbox-p)
15410 (call-interactively 'org-toggle-checkbox))
15411 ((org-at-item-p)
15412 (if arg
15413 (call-interactively 'org-toggle-checkbox)
15414 (call-interactively 'org-maybe-renumber-ordered-list)))
15415 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15416 ;; Dynamic block
15417 (beginning-of-line 1)
15418 (save-excursion (org-update-dblock)))
15419 ((save-excursion
15420 (beginning-of-line 1)
15421 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15422 (cond
15423 ((equal (match-string 1) "TBLFM")
15424 ;; Recalculate the table before this line
15425 (save-excursion
15426 (beginning-of-line 1)
15427 (skip-chars-backward " \r\n\t")
15428 (if (org-at-table-p)
15429 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15431 ; (org-set-regexps-and-options)
15432 ; (org-restart-font-lock)
15433 (let ((org-inhibit-startup t)) (org-mode-restart))
15434 (message "Local setup has been refreshed"))))
15435 ((org-clock-update-time-maybe))
15436 (t (error "C-c C-c can do nothing useful at this location")))))
15438 (defun org-mode-restart ()
15439 "Restart Org-mode, to scan again for special lines.
15440 Also updates the keyword regular expressions."
15441 (interactive)
15442 (org-mode)
15443 (message "Org-mode restarted"))
15445 (defun org-kill-note-or-show-branches ()
15446 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15447 (interactive)
15448 (if (not org-finish-function)
15449 (call-interactively 'show-branches)
15450 (let ((org-note-abort t))
15451 (funcall org-finish-function))))
15453 (defun org-return (&optional indent)
15454 "Goto next table row or insert a newline.
15455 Calls `org-table-next-row' or `newline', depending on context.
15456 See the individual commands for more information."
15457 (interactive)
15458 (cond
15459 ((bobp) (if indent (newline-and-indent) (newline)))
15460 ((org-at-table-p)
15461 (org-table-justify-field-maybe)
15462 (call-interactively 'org-table-next-row))
15463 ((and org-return-follows-link
15464 (eq (get-text-property (point) 'face) 'org-link))
15465 (call-interactively 'org-open-at-point))
15466 ((and (org-at-heading-p)
15467 (looking-at
15468 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15469 (org-show-entry)
15470 (end-of-line 1)
15471 (newline))
15472 (t (if indent (newline-and-indent) (newline)))))
15474 (defun org-return-indent ()
15475 "Goto next table row or insert a newline and indent.
15476 Calls `org-table-next-row' or `newline-and-indent', depending on
15477 context. See the individual commands for more information."
15478 (interactive)
15479 (org-return t))
15481 (defun org-ctrl-c-star ()
15482 "Compute table, or change heading status of lines.
15483 Calls `org-table-recalculate' or `org-toggle-heading',
15484 depending on context."
15485 (interactive)
15486 (cond
15487 ((org-at-table-p)
15488 (call-interactively 'org-table-recalculate))
15490 ;; Convert all lines in region to list items
15491 (call-interactively 'org-toggle-heading))))
15493 (defun org-ctrl-c-minus ()
15494 "Insert separator line in table or modify bullet status of line.
15495 Also turns a plain line or a region of lines into list items.
15496 Calls `org-table-insert-hline', `org-toggle-item', or
15497 `org-cycle-list-bullet', depending on context."
15498 (interactive)
15499 (cond
15500 ((org-at-table-p)
15501 (call-interactively 'org-table-insert-hline))
15502 ((org-region-active-p)
15503 (call-interactively 'org-toggle-item))
15504 ((org-in-item-p)
15505 (call-interactively 'org-cycle-list-bullet))
15507 (call-interactively 'org-toggle-item))))
15509 (defun org-toggle-item ()
15510 "Convert headings or normal lines to items, items to normal lines.
15511 If there is no active region, only the current line is considered.
15513 If the first line in the region is a headline, convert all headlines to items.
15515 If the first line in the region is an item, convert all items to normal lines.
15517 If the first line is normal text, add an item bullet to each line."
15518 (interactive)
15519 (let (l2 l beg end)
15520 (if (org-region-active-p)
15521 (setq beg (region-beginning) end (region-end))
15522 (setq beg (point-at-bol)
15523 end (min (1+ (point-at-eol)) (point-max))))
15524 (save-excursion
15525 (goto-char end)
15526 (setq l2 (org-current-line))
15527 (goto-char beg)
15528 (beginning-of-line 1)
15529 (setq l (1- (org-current-line)))
15530 (if (org-at-item-p)
15531 ;; We already have items, de-itemize
15532 (while (< (setq l (1+ l)) l2)
15533 (when (org-at-item-p)
15534 (goto-char (match-beginning 2))
15535 (delete-region (match-beginning 2) (match-end 2))
15536 (and (looking-at "[ \t]+") (replace-match "")))
15537 (beginning-of-line 2))
15538 (if (org-on-heading-p)
15539 ;; Headings, convert to items
15540 (while (< (setq l (1+ l)) l2)
15541 (if (looking-at org-outline-regexp)
15542 (replace-match "- " t t))
15543 (beginning-of-line 2))
15544 ;; normal lines, turn them into items
15545 (while (< (setq l (1+ l)) l2)
15546 (unless (org-at-item-p)
15547 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15548 (replace-match "\\1- \\2")))
15549 (beginning-of-line 2)))))))
15551 (defun org-toggle-heading (&optional nstars)
15552 "Convert headings to normal text, or items or text to headings.
15553 If there is no active region, only the current line is considered.
15555 If the first line is a heading, remove the stars from all headlines
15556 in the region.
15558 If the first line is a plain list item, turn all plain list items
15559 into headings.
15561 If the first line is a normal line, turn each and every line in the
15562 region into a heading.
15564 When converting a line into a heading, the number of stars is chosen
15565 such that the lines become children of the current entry. However,
15566 when a prefix argument is given, its value determines the number of
15567 stars to add."
15568 (interactive "P")
15569 (let (l2 l itemp beg end)
15570 (if (org-region-active-p)
15571 (setq beg (region-beginning) end (region-end))
15572 (setq beg (point-at-bol)
15573 end (min (1+ (point-at-eol)) (point-max))))
15574 (save-excursion
15575 (goto-char end)
15576 (setq l2 (org-current-line))
15577 (goto-char beg)
15578 (beginning-of-line 1)
15579 (setq l (1- (org-current-line)))
15580 (if (org-on-heading-p)
15581 ;; We already have headlines, de-star them
15582 (while (< (setq l (1+ l)) l2)
15583 (when (org-on-heading-p t)
15584 (and (looking-at outline-regexp) (replace-match "")))
15585 (beginning-of-line 2))
15586 (setq itemp (org-at-item-p))
15587 (let* ((stars
15588 (if nstars
15589 (make-string (prefix-numeric-value current-prefix-arg)
15591 (save-excursion
15592 (if (re-search-backward org-complex-heading-regexp nil t)
15593 (match-string 1) ""))))
15594 (add-stars (cond (nstars "")
15595 ((equal stars "") "*")
15596 (org-odd-levels-only "**")
15597 (t "*")))
15598 (rpl (concat stars add-stars " ")))
15599 (while (< (setq l (1+ l)) l2)
15600 (if itemp
15601 (and (org-at-item-p) (replace-match rpl t t))
15602 (unless (org-on-heading-p)
15603 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15604 (replace-match (concat rpl (match-string 2))))))
15605 (beginning-of-line 2)))))))
15607 (defun org-meta-return (&optional arg)
15608 "Insert a new heading or wrap a region in a table.
15609 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15610 See the individual commands for more information."
15611 (interactive "P")
15612 (cond
15613 ((run-hook-with-args-until-success 'org-metareturn-hook))
15614 ((org-at-table-p)
15615 (call-interactively 'org-table-wrap-region))
15616 (t (call-interactively 'org-insert-heading))))
15618 ;;; Menu entries
15620 ;; Define the Org-mode menus
15621 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15622 '("Tbl"
15623 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15624 ["Next Field" org-cycle (org-at-table-p)]
15625 ["Previous Field" org-shifttab (org-at-table-p)]
15626 ["Next Row" org-return (org-at-table-p)]
15627 "--"
15628 ["Blank Field" org-table-blank-field (org-at-table-p)]
15629 ["Edit Field" org-table-edit-field (org-at-table-p)]
15630 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15631 "--"
15632 ("Column"
15633 ["Move Column Left" org-metaleft (org-at-table-p)]
15634 ["Move Column Right" org-metaright (org-at-table-p)]
15635 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15636 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15637 ("Row"
15638 ["Move Row Up" org-metaup (org-at-table-p)]
15639 ["Move Row Down" org-metadown (org-at-table-p)]
15640 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15641 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15642 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15643 "--"
15644 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15645 ("Rectangle"
15646 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15647 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15648 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15649 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15650 "--"
15651 ("Calculate"
15652 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15653 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15654 ["Edit Formulas" org-edit-special (org-at-table-p)]
15655 "--"
15656 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15657 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15658 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15659 "--"
15660 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15661 "--"
15662 ["Sum Column/Rectangle" org-table-sum
15663 (or (org-at-table-p) (org-region-active-p))]
15664 ["Which Column?" org-table-current-column (org-at-table-p)])
15665 ["Debug Formulas"
15666 org-table-toggle-formula-debugger
15667 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15668 ["Show Col/Row Numbers"
15669 org-table-toggle-coordinate-overlays
15670 :style toggle
15671 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15672 "--"
15673 ["Create" org-table-create (and (not (org-at-table-p))
15674 org-enable-table-editor)]
15675 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15676 ["Import from File" org-table-import (not (org-at-table-p))]
15677 ["Export to File" org-table-export (org-at-table-p)]
15678 "--"
15679 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15681 (easy-menu-define org-org-menu org-mode-map "Org menu"
15682 '("Org"
15683 ("Show/Hide"
15684 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15685 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15686 ["Sparse Tree..." org-sparse-tree t]
15687 ["Reveal Context" org-reveal t]
15688 ["Show All" show-all t]
15689 "--"
15690 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15691 "--"
15692 ["New Heading" org-insert-heading t]
15693 ("Navigate Headings"
15694 ["Up" outline-up-heading t]
15695 ["Next" outline-next-visible-heading t]
15696 ["Previous" outline-previous-visible-heading t]
15697 ["Next Same Level" outline-forward-same-level t]
15698 ["Previous Same Level" outline-backward-same-level t]
15699 "--"
15700 ["Jump" org-goto t])
15701 ("Edit Structure"
15702 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15703 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15704 "--"
15705 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15706 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15707 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15708 "--"
15709 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15710 "--"
15711 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15712 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15713 ["Demote Heading" org-metaright (not (org-at-table-p))]
15714 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15715 "--"
15716 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15717 "--"
15718 ["Convert to odd levels" org-convert-to-odd-levels t]
15719 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15720 ("Editing"
15721 ["Emphasis..." org-emphasize t]
15722 ["Edit Source Example" org-edit-special t]
15723 "--"
15724 ["Footnote new/jump" org-footnote-action t]
15725 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15726 ("Archive"
15727 ["Archive (default method)" org-archive-subtree-default t]
15728 "--"
15729 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
15730 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15731 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
15733 "--"
15734 ("Hyperlinks"
15735 ["Store Link (Global)" org-store-link t]
15736 ["Find existing link to here" org-occur-link-in-agenda-files t]
15737 ["Insert Link" org-insert-link t]
15738 ["Follow Link" org-open-at-point t]
15739 "--"
15740 ["Next link" org-next-link t]
15741 ["Previous link" org-previous-link t]
15742 "--"
15743 ["Descriptive Links"
15744 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15745 :style radio
15746 :selected (member '(org-link) buffer-invisibility-spec)]
15747 ["Literal Links"
15748 (progn
15749 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15750 :style radio
15751 :selected (not (member '(org-link) buffer-invisibility-spec))])
15752 "--"
15753 ("TODO Lists"
15754 ["TODO/DONE/-" org-todo t]
15755 ("Select keyword"
15756 ["Next keyword" org-shiftright (org-on-heading-p)]
15757 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15758 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15759 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15760 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15761 ["Show TODO Tree" org-show-todo-tree t]
15762 ["Global TODO list" org-todo-list t]
15763 "--"
15764 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15765 :selected org-enforce-todo-dependencies :style toggle :active t]
15766 "Settings for tree at point"
15767 ["Do Children sequentially" org-toggle-ordered-property :style radio
15768 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15769 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15770 ["Do Children parallel" org-toggle-ordered-property :style radio
15771 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15772 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15773 "--"
15774 ["Set Priority" org-priority t]
15775 ["Priority Up" org-shiftup t]
15776 ["Priority Down" org-shiftdown t]
15777 "--"
15778 ["Get news from all feeds" org-feed-update-all t]
15779 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15780 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15781 ("TAGS and Properties"
15782 ["Set Tags" org-set-tags-command t]
15783 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15784 "--"
15785 ["Set property" org-set-property t]
15786 ["Column view of properties" org-columns t]
15787 ["Insert Column View DBlock" org-insert-columns-dblock t])
15788 ("Dates and Scheduling"
15789 ["Timestamp" org-time-stamp t]
15790 ["Timestamp (inactive)" org-time-stamp-inactive t]
15791 ("Change Date"
15792 ["1 Day Later" org-shiftright t]
15793 ["1 Day Earlier" org-shiftleft t]
15794 ["1 ... Later" org-shiftup t]
15795 ["1 ... Earlier" org-shiftdown t])
15796 ["Compute Time Range" org-evaluate-time-range t]
15797 ["Schedule Item" org-schedule t]
15798 ["Deadline" org-deadline t]
15799 "--"
15800 ["Custom time format" org-toggle-time-stamp-overlays
15801 :style radio :selected org-display-custom-times]
15802 "--"
15803 ["Goto Calendar" org-goto-calendar t]
15804 ["Date from Calendar" org-date-from-calendar t]
15805 "--"
15806 ["Start/Restart Timer" org-timer-start t]
15807 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15808 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15809 ["Insert Timer String" org-timer t]
15810 ["Insert Timer Item" org-timer-item t])
15811 ("Logging work"
15812 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15813 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15814 ["Clock out" org-clock-out t]
15815 ["Clock cancel" org-clock-cancel t]
15816 "--"
15817 ["Mark as default task" org-clock-mark-default-task t]
15818 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15819 ["Goto running clock" org-clock-goto t]
15820 "--"
15821 ["Display times" org-clock-display t]
15822 ["Create clock table" org-clock-report t]
15823 "--"
15824 ["Record DONE time"
15825 (progn (setq org-log-done (not org-log-done))
15826 (message "Switching to %s will %s record a timestamp"
15827 (car org-done-keywords)
15828 (if org-log-done "automatically" "not")))
15829 :style toggle :selected org-log-done])
15830 "--"
15831 ["Agenda Command..." org-agenda t]
15832 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15833 ("File List for Agenda")
15834 ("Special views current file"
15835 ["TODO Tree" org-show-todo-tree t]
15836 ["Check Deadlines" org-check-deadlines t]
15837 ["Timeline" org-timeline t]
15838 ["Tags/Property tree" org-match-sparse-tree t])
15839 "--"
15840 ["Export/Publish..." org-export t]
15841 ("LaTeX"
15842 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15843 :selected org-cdlatex-mode]
15844 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15845 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15846 ["Modify math symbol" org-cdlatex-math-modify
15847 (org-inside-LaTeX-fragment-p)]
15848 ["Insert citation" org-reftex-citation t]
15849 "--"
15850 ["Export LaTeX fragments as images"
15851 (if (featurep 'org-exp)
15852 (setq org-export-with-LaTeX-fragments
15853 (not org-export-with-LaTeX-fragments))
15854 (require 'org-exp))
15855 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15856 org-export-with-LaTeX-fragments)])
15857 "--"
15858 ("MobileOrg"
15859 ["Push Files and Views" org-mobile-push t]
15860 ["Get Captured and Flagged" org-mobile-pull t]
15861 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
15862 "--"
15863 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
15864 "--"
15865 ("Documentation"
15866 ["Show Version" org-version t]
15867 ["Info Documentation" org-info t])
15868 ("Customize"
15869 ["Browse Org Group" org-customize t]
15870 "--"
15871 ["Expand This Menu" org-create-customize-menu
15872 (fboundp 'customize-menu-create)])
15873 ["Send bug report" org-submit-bug-report t]
15874 "--"
15875 ("Refresh/Reload"
15876 ["Refresh setup current buffer" org-mode-restart t]
15877 ["Reload Org (after update)" org-reload t]
15878 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15881 (defun org-info (&optional node)
15882 "Read documentation for Org-mode in the info system.
15883 With optional NODE, go directly to that node."
15884 (interactive)
15885 (info (format "(org)%s" (or node ""))))
15887 ;;;###autoload
15888 (defun org-submit-bug-report ()
15889 "Submit a bug report on Org-mode via mail.
15891 Don't hesitate to report any problems or inaccurate documentation.
15893 If you don't have setup sending mail from (X)Emacs, please copy the
15894 output buffer into your mail program, as it gives us important
15895 information about your Org-mode version and configuration."
15896 (interactive)
15897 (require 'reporter)
15898 (org-load-modules-maybe)
15899 (org-require-autoloaded-modules)
15900 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
15901 (reporter-submit-bug-report
15902 "emacs-orgmode@gnu.org"
15903 (org-version)
15904 (let (list)
15905 (save-window-excursion
15906 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
15907 (delete-other-windows)
15908 (erase-buffer)
15909 (insert "You are about to submit a bug report to the Org-mode mailing list.
15911 We would like to add your full Org-mode and Outline configuration to the
15912 bug report. This greatly simplifies the work of the maintainer and
15913 other experts on the mailing list.
15915 HOWEVER, some variables you have customized may contain private
15916 information. The names of customers, colleagues, or friends, might
15917 appear in the form of file names, tags, todo states, or search strings.
15918 If you answer yes to the prompt, you might want to check and remove
15919 such private information before sending the email.")
15920 (add-text-properties (point-min) (point-max) '(face org-warning))
15921 (when (yes-or-no-p "Include your Org-mode configuration ")
15922 (mapatoms
15923 (lambda (v)
15924 (and (boundp v)
15925 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
15926 (or (and (symbol-value v)
15927 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
15928 (and
15929 (get v 'custom-type) (get v 'standard-value)
15930 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
15931 (push v list)))))
15932 (kill-buffer (get-buffer "*Warn about privacy*"))
15933 list))
15934 nil nil
15935 "Remember to cover the basics, that is, what you expected to happen and
15936 what in fact did happen. You don't know how to make a good report? See
15938 http://orgmode.org/manual/Feedback.html#Feedback
15940 Your bug report will be posted to the Org-mode mailing list.
15941 ------------------------------------------------------------------------")))
15943 (defun org-install-agenda-files-menu ()
15944 (let ((bl (buffer-list)))
15945 (save-excursion
15946 (while bl
15947 (set-buffer (pop bl))
15948 (if (org-mode-p) (setq bl nil)))
15949 (when (org-mode-p)
15950 (easy-menu-change
15951 '("Org") "File List for Agenda"
15952 (append
15953 (list
15954 ["Edit File List" (org-edit-agenda-file-list) t]
15955 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15956 ["Remove Current File from List" org-remove-file t]
15957 ["Cycle through agenda files" org-cycle-agenda-files t]
15958 ["Occur in all agenda files" org-occur-in-agenda-files t]
15959 "--")
15960 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15962 ;;;; Documentation
15964 ;;;###autoload
15965 (defun org-require-autoloaded-modules ()
15966 (interactive)
15967 (mapc 'require
15968 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15969 org-docbook org-exp org-html org-icalendar
15970 org-id org-latex
15971 org-publish org-remember org-table
15972 org-timer org-xoxo)))
15974 ;;;###autoload
15975 (defun org-reload (&optional uncompiled)
15976 "Reload all org lisp files.
15977 With prefix arg UNCOMPILED, load the uncompiled versions."
15978 (interactive "P")
15979 (require 'find-func)
15980 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15981 (dir-org (file-name-directory (org-find-library-name "org")))
15982 (dir-org-contrib (ignore-errors
15983 (file-name-directory
15984 (org-find-library-name "org-contribdir"))))
15985 (files
15986 (append (directory-files dir-org t file-re)
15987 (and dir-org-contrib
15988 (directory-files dir-org-contrib t file-re))))
15989 (remove-re (concat (if (featurep 'xemacs)
15990 "org-colview" "org-colview-xemacs")
15991 "\\'")))
15992 (setq files (mapcar 'file-name-sans-extension files))
15993 (setq files (mapcar
15994 (lambda (x) (if (string-match remove-re x) nil x))
15995 files))
15996 (setq files (delq nil files))
15997 (mapc
15998 (lambda (f)
15999 (when (featurep (intern (file-name-nondirectory f)))
16000 (if (and (not uncompiled)
16001 (file-exists-p (concat f ".elc")))
16002 (load (concat f ".elc") nil nil t)
16003 (load (concat f ".el") nil nil t))))
16004 files))
16005 (org-version))
16007 ;;;###autoload
16008 (defun org-customize ()
16009 "Call the customize function with org as argument."
16010 (interactive)
16011 (org-load-modules-maybe)
16012 (org-require-autoloaded-modules)
16013 (customize-browse 'org))
16015 (defun org-create-customize-menu ()
16016 "Create a full customization menu for Org-mode, insert it into the menu."
16017 (interactive)
16018 (org-load-modules-maybe)
16019 (org-require-autoloaded-modules)
16020 (if (fboundp 'customize-menu-create)
16021 (progn
16022 (easy-menu-change
16023 '("Org") "Customize"
16024 `(["Browse Org group" org-customize t]
16025 "--"
16026 ,(customize-menu-create 'org)
16027 ["Set" Custom-set t]
16028 ["Save" Custom-save t]
16029 ["Reset to Current" Custom-reset-current t]
16030 ["Reset to Saved" Custom-reset-saved t]
16031 ["Reset to Standard Settings" Custom-reset-standard t]))
16032 (message "\"Org\"-menu now contains full customization menu"))
16033 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16035 ;;;; Miscellaneous stuff
16037 ;;; Generally useful functions
16039 (defun org-get-at-bol (property)
16040 "Get text property PROPERTY at beginning of line."
16041 (get-text-property (point-at-bol) property))
16043 (defun org-find-text-property-in-string (prop s)
16044 "Return the first non-nil value of property PROP in string S."
16045 (or (get-text-property 0 prop s)
16046 (get-text-property (or (next-single-property-change 0 prop s) 0)
16047 prop s)))
16049 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16050 "Display the given MESSAGE as a warning."
16051 (if (fboundp 'display-warning)
16052 (display-warning 'org message
16053 (if (featurep 'xemacs)
16054 'warning
16055 :warning))
16056 (let ((buf (get-buffer-create "*Org warnings*")))
16057 (with-current-buffer buf
16058 (goto-char (point-max))
16059 (insert "Warning (Org): " message)
16060 (unless (bolp)
16061 (newline)))
16062 (display-buffer buf)
16063 (sit-for 0))))
16065 (defun org-in-commented-line ()
16066 "Is point in a line starting with `#'?"
16067 (equal (char-after (point-at-bol)) ?#))
16069 (defun org-in-verbatim-emphasis ()
16070 (save-match-data
16071 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16073 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16074 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16075 (if (and marker (marker-buffer marker)
16076 (buffer-live-p (marker-buffer marker)))
16077 (progn
16078 (switch-to-buffer (marker-buffer marker))
16079 (if (or (> marker (point-max)) (< marker (point-min)))
16080 (widen))
16081 (goto-char marker)
16082 (org-show-context 'org-goto))
16083 (if bookmark
16084 (bookmark-jump bookmark)
16085 (error "Cannot find location"))))
16087 (defun org-quote-csv-field (s)
16088 "Quote field for inclusion in CSV material."
16089 (if (string-match "[\",]" s)
16090 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16093 (defun org-plist-delete (plist property)
16094 "Delete PROPERTY from PLIST.
16095 This is in contrast to merely setting it to 0."
16096 (let (p)
16097 (while plist
16098 (if (not (eq property (car plist)))
16099 (setq p (plist-put p (car plist) (nth 1 plist))))
16100 (setq plist (cddr plist)))
16103 (defun org-force-self-insert (N)
16104 "Needed to enforce self-insert under remapping."
16105 (interactive "p")
16106 (self-insert-command N))
16108 (defun org-string-width (s)
16109 "Compute width of string, ignoring invisible characters.
16110 This ignores character with invisibility property `org-link', and also
16111 characters with property `org-cwidth', because these will become invisible
16112 upon the next fontification round."
16113 (let (b l)
16114 (when (or (eq t buffer-invisibility-spec)
16115 (assq 'org-link buffer-invisibility-spec))
16116 (while (setq b (text-property-any 0 (length s)
16117 'invisible 'org-link s))
16118 (setq s (concat (substring s 0 b)
16119 (substring s (or (next-single-property-change
16120 b 'invisible s) (length s)))))))
16121 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16122 (setq s (concat (substring s 0 b)
16123 (substring s (or (next-single-property-change
16124 b 'org-cwidth s) (length s))))))
16125 (setq l (string-width s) b -1)
16126 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16127 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16130 (defun org-get-indentation (&optional line)
16131 "Get the indentation of the current line, interpreting tabs.
16132 When LINE is given, assume it represents a line and compute its indentation."
16133 (if line
16134 (if (string-match "^ *" (org-remove-tabs line))
16135 (match-end 0))
16136 (save-excursion
16137 (beginning-of-line 1)
16138 (skip-chars-forward " \t")
16139 (current-column))))
16141 (defun org-remove-tabs (s &optional width)
16142 "Replace tabulators in S with spaces.
16143 Assumes that s is a single line, starting in column 0."
16144 (setq width (or width tab-width))
16145 (while (string-match "\t" s)
16146 (setq s (replace-match
16147 (make-string
16148 (- (* width (/ (+ (match-beginning 0) width) width))
16149 (match-beginning 0)) ?\ )
16150 t t s)))
16153 (defun org-fix-indentation (line ind)
16154 "Fix indentation in LINE.
16155 IND is a cons cell with target and minimum indentation.
16156 If the current indentation in LINE is smaller than the minimum,
16157 leave it alone. If it is larger than ind, set it to the target."
16158 (let* ((l (org-remove-tabs line))
16159 (i (org-get-indentation l))
16160 (i1 (car ind)) (i2 (cdr ind)))
16161 (if (>= i i2) (setq l (substring line i2)))
16162 (if (> i1 0)
16163 (concat (make-string i1 ?\ ) l)
16164 l)))
16166 (defun org-remove-indentation (code &optional n)
16167 "Remove the maximum common indentation from the lines in CODE.
16168 N may optionally be the number of spaces to remove."
16169 (with-temp-buffer
16170 (insert code)
16171 (org-do-remove-indentation n)
16172 (buffer-string)))
16174 (defun org-do-remove-indentation (&optional n)
16175 "Remove the maximum common indentation from the buffer."
16176 (untabify (point-min) (point-max))
16177 (let ((min 10000) re)
16178 (if n
16179 (setq min n)
16180 (goto-char (point-min))
16181 (while (re-search-forward "^ *[^ \n]" nil t)
16182 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16183 (unless (or (= min 0) (= min 10000))
16184 (setq re (format "^ \\{%d\\}" min))
16185 (goto-char (point-min))
16186 (while (re-search-forward re nil t)
16187 (replace-match "")
16188 (end-of-line 1))
16189 min)))
16191 (defun org-fill-template (template alist)
16192 "Find each %key of ALIST in TEMPLATE and replace it."
16193 (let (entry key value)
16194 (setq alist (sort (copy-sequence alist)
16195 (lambda (a b) (< (length (car a)) (length (car b))))))
16196 (while (setq entry (pop alist))
16197 (setq template
16198 (replace-regexp-in-string
16199 (concat "%" (regexp-quote (car entry)))
16200 (cdr entry) template t t)))
16201 template))
16203 (defun org-base-buffer (buffer)
16204 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16205 (if (not buffer)
16206 buffer
16207 (or (buffer-base-buffer buffer)
16208 buffer)))
16210 (defun org-trim (s)
16211 "Remove whitespace at beginning and end of string."
16212 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16213 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16216 (defun org-wrap (string &optional width lines)
16217 "Wrap string to either a number of lines, or a width in characters.
16218 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16219 that costs. If there is a word longer than WIDTH, the text is actually
16220 wrapped to the length of that word.
16221 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16222 many lines, whatever width that takes.
16223 The return value is a list of lines, without newlines at the end."
16224 (let* ((words (org-split-string string "[ \t\n]+"))
16225 (maxword (apply 'max (mapcar 'org-string-width words)))
16226 w ll)
16227 (cond (width
16228 (org-do-wrap words (max maxword width)))
16229 (lines
16230 (setq w maxword)
16231 (setq ll (org-do-wrap words maxword))
16232 (if (<= (length ll) lines)
16234 (setq ll words)
16235 (while (> (length ll) lines)
16236 (setq w (1+ w))
16237 (setq ll (org-do-wrap words w)))
16238 ll))
16239 (t (error "Cannot wrap this")))))
16241 (defun org-do-wrap (words width)
16242 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16243 (let (lines line)
16244 (while words
16245 (setq line (pop words))
16246 (while (and words (< (+ (length line) (length (car words))) width))
16247 (setq line (concat line " " (pop words))))
16248 (setq lines (push line lines)))
16249 (nreverse lines)))
16251 (defun org-split-string (string &optional separators)
16252 "Splits STRING into substrings at SEPARATORS.
16253 No empty strings are returned if there are matches at the beginning
16254 and end of string."
16255 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16256 (start 0)
16257 notfirst
16258 (list nil))
16259 (while (and (string-match rexp string
16260 (if (and notfirst
16261 (= start (match-beginning 0))
16262 (< start (length string)))
16263 (1+ start) start))
16264 (< (match-beginning 0) (length string)))
16265 (setq notfirst t)
16266 (or (eq (match-beginning 0) 0)
16267 (and (eq (match-beginning 0) (match-end 0))
16268 (eq (match-beginning 0) start))
16269 (setq list
16270 (cons (substring string start (match-beginning 0))
16271 list)))
16272 (setq start (match-end 0)))
16273 (or (eq start (length string))
16274 (setq list
16275 (cons (substring string start)
16276 list)))
16277 (nreverse list)))
16279 (defun org-quote-vert (s)
16280 "Replace \"|\" with \"\\vert\"."
16281 (while (string-match "|" s)
16282 (setq s (replace-match "\\vert" t t s)))
16285 (defun org-uuidgen-p (s)
16286 "Is S an ID created by UUIDGEN?"
16287 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16289 (defun org-context ()
16290 "Return a list of contexts of the current cursor position.
16291 If several contexts apply, all are returned.
16292 Each context entry is a list with a symbol naming the context, and
16293 two positions indicating start and end of the context. Possible
16294 contexts are:
16296 :headline anywhere in a headline
16297 :headline-stars on the leading stars in a headline
16298 :todo-keyword on a TODO keyword (including DONE) in a headline
16299 :tags on the TAGS in a headline
16300 :priority on the priority cookie in a headline
16301 :item on the first line of a plain list item
16302 :item-bullet on the bullet/number of a plain list item
16303 :checkbox on the checkbox in a plain list item
16304 :table in an org-mode table
16305 :table-special on a special filed in a table
16306 :table-table in a table.el table
16307 :link on a hyperlink
16308 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16309 :target on a <<target>>
16310 :radio-target on a <<<radio-target>>>
16311 :latex-fragment on a LaTeX fragment
16312 :latex-preview on a LaTeX fragment with overlayed preview image
16314 This function expects the position to be visible because it uses font-lock
16315 faces as a help to recognize the following contexts: :table-special, :link,
16316 and :keyword."
16317 (let* ((f (get-text-property (point) 'face))
16318 (faces (if (listp f) f (list f)))
16319 (p (point)) clist o)
16320 ;; First the large context
16321 (cond
16322 ((org-on-heading-p t)
16323 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16324 (when (progn
16325 (beginning-of-line 1)
16326 (looking-at org-todo-line-tags-regexp))
16327 (push (org-point-in-group p 1 :headline-stars) clist)
16328 (push (org-point-in-group p 2 :todo-keyword) clist)
16329 (push (org-point-in-group p 4 :tags) clist))
16330 (goto-char p)
16331 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16332 (if (looking-at "\\[#[A-Z0-9]\\]")
16333 (push (org-point-in-group p 0 :priority) clist)))
16335 ((org-at-item-p)
16336 (push (org-point-in-group p 2 :item-bullet) clist)
16337 (push (list :item (point-at-bol)
16338 (save-excursion (org-end-of-item) (point)))
16339 clist)
16340 (and (org-at-item-checkbox-p)
16341 (push (org-point-in-group p 0 :checkbox) clist)))
16343 ((org-at-table-p)
16344 (push (list :table (org-table-begin) (org-table-end)) clist)
16345 (if (memq 'org-formula faces)
16346 (push (list :table-special
16347 (previous-single-property-change p 'face)
16348 (next-single-property-change p 'face)) clist)))
16349 ((org-at-table-p 'any)
16350 (push (list :table-table) clist)))
16351 (goto-char p)
16353 ;; Now the small context
16354 (cond
16355 ((org-at-timestamp-p)
16356 (push (org-point-in-group p 0 :timestamp) clist))
16357 ((memq 'org-link faces)
16358 (push (list :link
16359 (previous-single-property-change p 'face)
16360 (next-single-property-change p 'face)) clist))
16361 ((memq 'org-special-keyword faces)
16362 (push (list :keyword
16363 (previous-single-property-change p 'face)
16364 (next-single-property-change p 'face)) clist))
16365 ((org-on-target-p)
16366 (push (org-point-in-group p 0 :target) clist)
16367 (goto-char (1- (match-beginning 0)))
16368 (if (looking-at org-radio-target-regexp)
16369 (push (org-point-in-group p 0 :radio-target) clist))
16370 (goto-char p))
16371 ((setq o (car (delq nil
16372 (mapcar
16373 (lambda (x)
16374 (if (memq x org-latex-fragment-image-overlays) x))
16375 (org-overlays-at (point))))))
16376 (push (list :latex-fragment
16377 (org-overlay-start o) (org-overlay-end o)) clist)
16378 (push (list :latex-preview
16379 (org-overlay-start o) (org-overlay-end o)) clist))
16380 ((org-inside-LaTeX-fragment-p)
16381 ;; FIXME: positions wrong.
16382 (push (list :latex-fragment (point) (point)) clist)))
16384 (setq clist (nreverse (delq nil clist)))
16385 clist))
16387 ;; FIXME: Compare with at-regexp-p Do we need both?
16388 (defun org-in-regexp (re &optional nlines visually)
16389 "Check if point is inside a match of regexp.
16390 Normally only the current line is checked, but you can include NLINES extra
16391 lines both before and after point into the search.
16392 If VISUALLY is set, require that the cursor is not after the match but
16393 really on, so that the block visually is on the match."
16394 (catch 'exit
16395 (let ((pos (point))
16396 (eol (point-at-eol (+ 1 (or nlines 0))))
16397 (inc (if visually 1 0)))
16398 (save-excursion
16399 (beginning-of-line (- 1 (or nlines 0)))
16400 (while (re-search-forward re eol t)
16401 (if (and (<= (match-beginning 0) pos)
16402 (>= (+ inc (match-end 0)) pos))
16403 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16405 (defun org-at-regexp-p (regexp)
16406 "Is point inside a match of REGEXP in the current line?"
16407 (catch 'exit
16408 (save-excursion
16409 (let ((pos (point)) (end (point-at-eol)))
16410 (beginning-of-line 1)
16411 (while (re-search-forward regexp end t)
16412 (if (and (<= (match-beginning 0) pos)
16413 (>= (match-end 0) pos))
16414 (throw 'exit t)))
16415 nil))))
16417 (defun org-occur-in-agenda-files (regexp &optional nlines)
16418 "Call `multi-occur' with buffers for all agenda files."
16419 (interactive "sOrg-files matching: \np")
16420 (let* ((files (org-agenda-files))
16421 (tnames (mapcar 'file-truename files))
16422 (extra org-agenda-text-search-extra-files)
16424 (when (eq (car extra) 'agenda-archives)
16425 (setq extra (cdr extra))
16426 (setq files (org-add-archive-files files)))
16427 (while (setq f (pop extra))
16428 (unless (member (file-truename f) tnames)
16429 (add-to-list 'files f 'append)
16430 (add-to-list 'tnames (file-truename f) 'append)))
16431 (multi-occur
16432 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16433 regexp)))
16435 (if (boundp 'occur-mode-find-occurrence-hook)
16436 ;; Emacs 23
16437 (add-hook 'occur-mode-find-occurrence-hook
16438 (lambda ()
16439 (when (org-mode-p)
16440 (org-reveal))))
16441 ;; Emacs 22
16442 (defadvice occur-mode-goto-occurrence
16443 (after org-occur-reveal activate)
16444 (and (org-mode-p) (org-reveal)))
16445 (defadvice occur-mode-goto-occurrence-other-window
16446 (after org-occur-reveal activate)
16447 (and (org-mode-p) (org-reveal)))
16448 (defadvice occur-mode-display-occurrence
16449 (after org-occur-reveal activate)
16450 (when (org-mode-p)
16451 (let ((pos (occur-mode-find-occurrence)))
16452 (with-current-buffer (marker-buffer pos)
16453 (save-excursion
16454 (goto-char pos)
16455 (org-reveal)))))))
16457 (defun org-occur-link-in-agenda-files ()
16458 "Create a link and search for it in the agendas.
16459 The link is not stored in `org-stored-links', it is just created
16460 for the search purpose."
16461 (interactive)
16462 (let ((link (condition-case nil
16463 (org-store-link nil)
16464 (error "Unable to create a link to here"))))
16465 (org-occur-in-agenda-files (regexp-quote link))))
16467 (defun org-uniquify (list)
16468 "Remove duplicate elements from LIST."
16469 (let (res)
16470 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16471 res))
16473 (defun org-delete-all (elts list)
16474 "Remove all elements in ELTS from LIST."
16475 (while elts
16476 (setq list (delete (pop elts) list)))
16477 list)
16479 (defun org-back-over-empty-lines ()
16480 "Move backwards over whitespace, to the beginning of the first empty line.
16481 Returns the number of empty lines passed."
16482 (let ((pos (point)))
16483 (skip-chars-backward " \t\n\r")
16484 (beginning-of-line 2)
16485 (goto-char (min (point) pos))
16486 (count-lines (point) pos)))
16488 (defun org-skip-whitespace ()
16489 (skip-chars-forward " \t\n\r"))
16491 (defun org-point-in-group (point group &optional context)
16492 "Check if POINT is in match-group GROUP.
16493 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16494 match. If the match group does ot exist or point is not inside it,
16495 return nil."
16496 (and (match-beginning group)
16497 (>= point (match-beginning group))
16498 (<= point (match-end group))
16499 (if context
16500 (list context (match-beginning group) (match-end group))
16501 t)))
16503 (defun org-switch-to-buffer-other-window (&rest args)
16504 "Switch to buffer in a second window on the current frame.
16505 In particular, do not allow pop-up frames."
16506 (let (pop-up-frames special-display-buffer-names special-display-regexps
16507 special-display-function)
16508 (apply 'switch-to-buffer-other-window args)))
16510 (defun org-combine-plists (&rest plists)
16511 "Create a single property list from all plists in PLISTS.
16512 The process starts by copying the first list, and then setting properties
16513 from the other lists. Settings in the last list are the most significant
16514 ones and overrule settings in the other lists."
16515 (let ((rtn (copy-sequence (pop plists)))
16516 p v ls)
16517 (while plists
16518 (setq ls (pop plists))
16519 (while ls
16520 (setq p (pop ls) v (pop ls))
16521 (setq rtn (plist-put rtn p v))))
16522 rtn))
16524 (defun org-move-line-down (arg)
16525 "Move the current line down. With prefix argument, move it past ARG lines."
16526 (interactive "p")
16527 (let ((col (current-column))
16528 beg end pos)
16529 (beginning-of-line 1) (setq beg (point))
16530 (beginning-of-line 2) (setq end (point))
16531 (beginning-of-line (+ 1 arg))
16532 (setq pos (move-marker (make-marker) (point)))
16533 (insert (delete-and-extract-region beg end))
16534 (goto-char pos)
16535 (org-move-to-column col)))
16537 (defun org-move-line-up (arg)
16538 "Move the current line up. With prefix argument, move it past ARG lines."
16539 (interactive "p")
16540 (let ((col (current-column))
16541 beg end pos)
16542 (beginning-of-line 1) (setq beg (point))
16543 (beginning-of-line 2) (setq end (point))
16544 (beginning-of-line (- arg))
16545 (setq pos (move-marker (make-marker) (point)))
16546 (insert (delete-and-extract-region beg end))
16547 (goto-char pos)
16548 (org-move-to-column col)))
16550 (defun org-replace-escapes (string table)
16551 "Replace %-escapes in STRING with values in TABLE.
16552 TABLE is an association list with keys like \"%a\" and string values.
16553 The sequences in STRING may contain normal field width and padding information,
16554 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16555 so values can contain further %-escapes if they are define later in TABLE."
16556 (let ((case-fold-search nil)
16557 e re rpl)
16558 (while (setq e (pop table))
16559 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16560 (while (string-match re string)
16561 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16562 (cdr e)))
16563 (setq string (replace-match rpl t t string))))
16564 string))
16567 (defun org-sublist (list start end)
16568 "Return a section of LIST, from START to END.
16569 Counting starts at 1."
16570 (let (rtn (c start))
16571 (setq list (nthcdr (1- start) list))
16572 (while (and list (<= c end))
16573 (push (pop list) rtn)
16574 (setq c (1+ c)))
16575 (nreverse rtn)))
16577 (defun org-find-base-buffer-visiting (file)
16578 "Like `find-buffer-visiting' but always return the base buffer and
16579 not an indirect buffer."
16580 (let ((buf (or (get-file-buffer file)
16581 (find-buffer-visiting file))))
16582 (if buf
16583 (or (buffer-base-buffer buf) buf)
16584 nil)))
16586 (defun org-image-file-name-regexp (&optional extensions)
16587 "Return regexp matching the file names of images.
16588 If EXTENSIONS is given, only match these."
16589 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16590 (image-file-name-regexp)
16591 (let ((image-file-name-extensions
16592 (or extensions
16593 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16594 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16595 (concat "\\."
16596 (regexp-opt (nconc (mapcar 'upcase
16597 image-file-name-extensions)
16598 image-file-name-extensions)
16600 "\\'"))))
16602 (defun org-file-image-p (file &optional extensions)
16603 "Return non-nil if FILE is an image."
16604 (save-match-data
16605 (string-match (org-image-file-name-regexp extensions) file)))
16607 (defun org-get-cursor-date ()
16608 "Return the date at cursor in as a time.
16609 This works in the calendar and in the agenda, anywhere else it just
16610 returns the current time."
16611 (let (date day defd)
16612 (cond
16613 ((eq major-mode 'calendar-mode)
16614 (setq date (calendar-cursor-to-date)
16615 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16616 ((eq major-mode 'org-agenda-mode)
16617 (setq day (get-text-property (point) 'day))
16618 (if day
16619 (setq date (calendar-gregorian-from-absolute day)
16620 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16621 (nth 2 date))))))
16622 (or defd (current-time))))
16624 (defvar org-agenda-action-marker (make-marker)
16625 "Marker pointing to the entry for the next agenda action.")
16627 (defun org-mark-entry-for-agenda-action ()
16628 "Mark the current entry as target of an agenda action.
16629 Agenda actions are actions executed from the agenda with the key `k',
16630 which make use of the date at the cursor."
16631 (interactive)
16632 (move-marker org-agenda-action-marker
16633 (save-excursion (org-back-to-heading t) (point))
16634 (current-buffer))
16635 (message
16636 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16638 ;;; Paragraph filling stuff.
16639 ;; We want this to be just right, so use the full arsenal.
16641 (defun org-indent-line-function ()
16642 "Indent line like previous, but further if previous was headline or item."
16643 (interactive)
16644 (let* ((pos (point))
16645 (itemp (org-at-item-p))
16646 (case-fold-search t)
16647 (org-drawer-regexp (or org-drawer-regexp "\000"))
16648 column bpos bcol tpos tcol bullet btype bullet-type)
16649 ;; Find the previous relevant line
16650 (beginning-of-line 1)
16651 (cond
16652 ((looking-at "#") (setq column 0))
16653 ((looking-at "\\*+ ") (setq column 0))
16654 ((and (looking-at "[ \t]*:END:")
16655 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16656 (save-excursion
16657 (goto-char (1- (match-beginning 1)))
16658 (setq column (current-column))))
16659 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16660 (save-excursion
16661 (re-search-backward
16662 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16663 (setq column (org-get-indentation (match-string 0))))
16665 (beginning-of-line 0)
16666 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16667 (not (looking-at "[ \t]*:END:"))
16668 (not (looking-at org-drawer-regexp)))
16669 (beginning-of-line 0))
16670 (cond
16671 ((looking-at "\\*+[ \t]+")
16672 (if (not org-adapt-indentation)
16673 (setq column 0)
16674 (goto-char (match-end 0))
16675 (setq column (current-column))))
16676 ((looking-at org-drawer-regexp)
16677 (goto-char (1- (match-beginning 1)))
16678 (setq column (current-column)))
16679 ((looking-at "\\([ \t]*\\):END:")
16680 (goto-char (match-end 1))
16681 (setq column (current-column)))
16682 ((org-in-item-p)
16683 (org-beginning-of-item)
16684 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16685 (setq bpos (match-beginning 1) tpos (match-end 0)
16686 bcol (progn (goto-char bpos) (current-column))
16687 tcol (progn (goto-char tpos) (current-column))
16688 bullet (match-string 1)
16689 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16690 (if (> tcol (+ bcol org-description-max-indent))
16691 (setq tcol (+ bcol 5)))
16692 (if (not itemp)
16693 (setq column tcol)
16694 (goto-char pos)
16695 (beginning-of-line 1)
16696 (if (looking-at "\\S-")
16697 (progn
16698 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16699 (setq bullet (match-string 1)
16700 btype (if (string-match "[0-9]" bullet) "n" bullet))
16701 (setq column (if (equal btype bullet-type) bcol tcol)))
16702 (setq column (org-get-indentation)))))
16703 (t (setq column (org-get-indentation))))))
16704 (goto-char pos)
16705 (if (<= (current-column) (current-indentation))
16706 (org-indent-line-to column)
16707 (save-excursion (org-indent-line-to column)))
16708 (setq column (current-column))
16709 (beginning-of-line 1)
16710 (if (looking-at
16711 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16712 (replace-match (concat (match-string 1)
16713 (format org-property-format
16714 (match-string 2) (match-string 3)))
16715 t t))
16716 (org-move-to-column column)))
16718 (defun org-set-autofill-regexps ()
16719 (interactive)
16720 ;; In the paragraph separator we include headlines, because filling
16721 ;; text in a line directly attached to a headline would otherwise
16722 ;; fill the headline as well.
16723 (org-set-local 'comment-start-skip "^#+[ \t]*")
16724 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16725 ;; The paragraph starter includes hand-formatted lists.
16726 (org-set-local
16727 'paragraph-start
16728 (concat
16729 "\f" "\\|"
16730 "[ ]*$" "\\|"
16731 "\\*+ " "\\|"
16732 "[ \t]*#" "\\|"
16733 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16734 "[ \t]*[:|]" "\\|"
16735 "\\$\\$" "\\|"
16736 "\\\\\\(begin\\|end\\|[][]\\)"))
16737 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16738 ;; But only if the user has not turned off tables or fixed-width regions
16739 (org-set-local
16740 'auto-fill-inhibit-regexp
16741 (concat "\\*+ \\|#\\+"
16742 "\\|[ \t]*" org-keyword-time-regexp
16743 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16744 (concat
16745 "\\|[ \t]*["
16746 (if org-enable-table-editor "|" "")
16747 (if org-enable-fixed-width-editor ":" "")
16748 "]"))))
16749 ;; We use our own fill-paragraph function, to make sure that tables
16750 ;; and fixed-width regions are not wrapped. That function will pass
16751 ;; through to `fill-paragraph' when appropriate.
16752 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16753 ; Adaptive filling: To get full control, first make sure that
16754 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16755 (org-set-local 'adaptive-fill-regexp "\000")
16756 (org-set-local 'adaptive-fill-function
16757 'org-adaptive-fill-function)
16758 (org-set-local
16759 'align-mode-rules-list
16760 '((org-in-buffer-settings
16761 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16762 (modes . '(org-mode))))))
16764 (defun org-fill-paragraph (&optional justify)
16765 "Re-align a table, pass through to fill-paragraph if no table."
16766 (let ((table-p (org-at-table-p))
16767 (table.el-p (org-at-table.el-p)))
16768 (cond ((and (equal (char-after (point-at-bol)) ?*)
16769 (save-excursion (goto-char (point-at-bol))
16770 (looking-at outline-regexp)))
16771 t) ; skip headlines
16772 (table.el-p t) ; skip table.el tables
16773 (table-p (org-table-align) t) ; align org-mode tables
16774 (t nil)))) ; call paragraph-fill
16776 ;; For reference, this is the default value of adaptive-fill-regexp
16777 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16779 (defun org-adaptive-fill-function ()
16780 "Return a fill prefix for org-mode files.
16781 In particular, this makes sure hanging paragraphs for hand-formatted lists
16782 work correctly."
16783 (cond ((looking-at "#[ \t]+")
16784 (match-string 0))
16785 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16786 (save-excursion
16787 (if (> (match-end 1) (+ (match-beginning 1)
16788 org-description-max-indent))
16789 (goto-char (+ (match-beginning 1) 5))
16790 (goto-char (match-end 0)))
16791 (make-string (current-column) ?\ )))
16792 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16793 (save-excursion
16794 (goto-char (match-end 0))
16795 (make-string (current-column) ?\ )))
16796 (t nil)))
16798 ;;; Other stuff.
16800 (defun org-toggle-fixed-width-section (arg)
16801 "Toggle the fixed-width export.
16802 If there is no active region, the QUOTE keyword at the current headline is
16803 inserted or removed. When present, it causes the text between this headline
16804 and the next to be exported as fixed-width text, and unmodified.
16805 If there is an active region, this command adds or removes a colon as the
16806 first character of this line. If the first character of a line is a colon,
16807 this line is also exported in fixed-width font."
16808 (interactive "P")
16809 (let* ((cc 0)
16810 (regionp (org-region-active-p))
16811 (beg (if regionp (region-beginning) (point)))
16812 (end (if regionp (region-end)))
16813 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16814 (case-fold-search nil)
16815 (re "[ \t]*\\(: \\)")
16816 off)
16817 (if regionp
16818 (save-excursion
16819 (goto-char beg)
16820 (setq cc (current-column))
16821 (beginning-of-line 1)
16822 (setq off (looking-at re))
16823 (while (> nlines 0)
16824 (setq nlines (1- nlines))
16825 (beginning-of-line 1)
16826 (cond
16827 (arg
16828 (org-move-to-column cc t)
16829 (insert ": \n")
16830 (forward-line -1))
16831 ((and off (looking-at re))
16832 (replace-match "" t t nil 1))
16833 ((not off) (org-move-to-column cc t) (insert ": ")))
16834 (forward-line 1)))
16835 (save-excursion
16836 (org-back-to-heading)
16837 (if (looking-at (concat outline-regexp
16838 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16839 (replace-match "" t t nil 1)
16840 (if (looking-at outline-regexp)
16841 (progn
16842 (goto-char (match-end 0))
16843 (insert org-quote-string " "))))))))
16845 (defun org-reftex-citation ()
16846 "Use reftex-citation to insert a citation into the buffer.
16847 This looks for a line like
16849 #+BIBLIOGRAPHY: foo plain option:-d
16851 and derives from it that foo.bib is the bbliography file relevant
16852 for this document. It then installs the necessary environment for RefTeX
16853 to work in this buffer and calls `reftex-citation' to insert a citation
16854 into the buffer.
16856 Export of such citations to both LaTeX and HTML is handled by the contributed
16857 package org-exp-bibtex by Taru Karttunen."
16858 (interactive)
16859 (let ((reftex-docstruct-symbol 'rds)
16860 (reftex-cite-format "\\cite{%l}")
16861 rds bib)
16862 (save-excursion
16863 (save-restriction
16864 (widen)
16865 (let ((case-fold-search t)
16866 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16867 (if (not (save-excursion
16868 (or (re-search-forward re nil t)
16869 (re-search-backward re nil t))))
16870 (error "No bibliography defined in file")
16871 (setq bib (concat (match-string 1) ".bib")
16872 rds (list (list 'bib bib)))))))
16873 (call-interactively 'reftex-citation)))
16875 ;;;; Functions extending outline functionality
16877 (defun org-beginning-of-line (&optional arg)
16878 "Go to the beginning of the current line. If that is invisible, continue
16879 to a visible line beginning. This makes the function of C-a more intuitive.
16880 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16881 first attempt, and only move to after the tags when the cursor is already
16882 beyond the end of the headline."
16883 (interactive "P")
16884 (let ((pos (point))
16885 (special (if (consp org-special-ctrl-a/e)
16886 (car org-special-ctrl-a/e)
16887 org-special-ctrl-a/e))
16888 refpos)
16889 (if (org-bound-and-true-p line-move-visual)
16890 (beginning-of-visual-line 1)
16891 (beginning-of-line 1))
16892 (if (and arg (fboundp 'move-beginning-of-line))
16893 (call-interactively 'move-beginning-of-line)
16894 (if (bobp)
16896 (backward-char 1)
16897 (if (org-invisible-p)
16898 (while (and (not (bobp)) (org-invisible-p))
16899 (backward-char 1)
16900 (beginning-of-line 1))
16901 (forward-char 1))))
16902 (when special
16903 (cond
16904 ((and (looking-at org-complex-heading-regexp)
16905 (= (char-after (match-end 1)) ?\ ))
16906 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16907 (point-at-eol)))
16908 (goto-char
16909 (if (eq special t)
16910 (cond ((> pos refpos) refpos)
16911 ((= pos (point)) refpos)
16912 (t (point)))
16913 (cond ((> pos (point)) (point))
16914 ((not (eq last-command this-command)) (point))
16915 (t refpos)))))
16916 ((org-at-item-p)
16917 (goto-char
16918 (if (eq special t)
16919 (cond ((> pos (match-end 4)) (match-end 4))
16920 ((= pos (point)) (match-end 4))
16921 (t (point)))
16922 (cond ((> pos (point)) (point))
16923 ((not (eq last-command this-command)) (point))
16924 (t (match-end 4))))))))
16925 (org-no-warnings
16926 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16928 (defun org-end-of-line (&optional arg)
16929 "Go to the end of the line.
16930 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16931 first attempt, and only move to after the tags when the cursor is already
16932 beyond the end of the headline."
16933 (interactive "P")
16934 (let ((special (if (consp org-special-ctrl-a/e)
16935 (cdr org-special-ctrl-a/e)
16936 org-special-ctrl-a/e)))
16937 (if (or (not special)
16938 (not (org-on-heading-p))
16939 arg)
16940 (call-interactively
16941 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16942 ((fboundp 'move-end-of-line) 'move-end-of-line)
16943 (t 'end-of-line)))
16944 (let ((pos (point)))
16945 (beginning-of-line 1)
16946 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
16947 (if (eq special t)
16948 (if (or (< pos (match-beginning 1))
16949 (= pos (match-end 0)))
16950 (goto-char (match-beginning 1))
16951 (goto-char (match-end 0)))
16952 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16953 (goto-char (match-end 0))
16954 (goto-char (match-beginning 1))))
16955 (call-interactively (if (fboundp 'move-end-of-line)
16956 'move-end-of-line
16957 'end-of-line)))))
16958 (org-no-warnings
16959 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16961 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16962 (define-key org-mode-map "\C-e" 'org-end-of-line)
16963 (define-key org-mode-map [home] 'org-beginning-of-line)
16964 (define-key org-mode-map [end] 'org-end-of-line)
16966 (defun org-backward-sentence (&optional arg)
16967 "Go to beginning of sentence, or beginning of table field.
16968 This will call `backward-sentence' or `org-table-beginning-of-field',
16969 depending on context."
16970 (interactive "P")
16971 (cond
16972 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16973 (t (call-interactively 'backward-sentence))))
16975 (defun org-forward-sentence (&optional arg)
16976 "Go to end of sentence, or end of table field.
16977 This will call `forward-sentence' or `org-table-end-of-field',
16978 depending on context."
16979 (interactive "P")
16980 (cond
16981 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16982 (t (call-interactively 'forward-sentence))))
16984 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16985 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16987 (defun org-kill-line (&optional arg)
16988 "Kill line, to tags or end of line."
16989 (interactive "P")
16990 (cond
16991 ((or (not org-special-ctrl-k)
16992 (bolp)
16993 (not (org-on-heading-p)))
16994 (call-interactively 'kill-line))
16995 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16996 (kill-region (point) (match-beginning 1))
16997 (org-set-tags nil t))
16998 (t (kill-region (point) (point-at-eol)))))
17000 (define-key org-mode-map "\C-k" 'org-kill-line)
17002 (defun org-yank (&optional arg)
17003 "Yank. If the kill is a subtree, treat it specially.
17004 This command will look at the current kill and check if is a single
17005 subtree, or a series of subtrees[1]. If it passes the test, and if the
17006 cursor is at the beginning of a line or after the stars of a currently
17007 empty headline, then the yank is handled specially. How exactly depends
17008 on the value of the following variables, both set by default.
17010 org-yank-folded-subtrees
17011 When set, the subtree(s) will be folded after insertion, but only
17012 if doing so would now swallow text after the yanked text.
17014 org-yank-adjusted-subtrees
17015 When set, the subtree will be promoted or demoted in order to
17016 fit into the local outline tree structure, which means that the level
17017 will be adjusted so that it becomes the smaller one of the two
17018 *visible* surrounding headings.
17020 Any prefix to this command will cause `yank' to be called directly with
17021 no special treatment. In particular, a simple `C-u' prefix will just
17022 plainly yank the text as it is.
17024 \[1] The test checks if the first non-white line is a heading
17025 and if there are no other headings with fewer stars."
17026 (interactive "P")
17027 (org-yank-generic 'yank arg))
17029 (defun org-yank-generic (command arg)
17030 "Perform some yank-like command.
17032 This function implements the behavior described in the `org-yank'
17033 documentation. However, it has been generalized to work for any
17034 interactive command with similar behavior."
17036 ;; pretend to be command COMMAND
17037 (setq this-command command)
17039 (if arg
17040 (call-interactively command)
17042 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17043 (and (org-kill-is-subtree-p)
17044 (or (bolp)
17045 (and (looking-at "[ \t]*$")
17046 (string-match
17047 "\\`\\*+\\'"
17048 (buffer-substring (point-at-bol) (point)))))))
17049 swallowp)
17050 (cond
17051 ((and subtreep org-yank-folded-subtrees)
17052 (let ((beg (point))
17053 end)
17054 (if (and subtreep org-yank-adjusted-subtrees)
17055 (org-paste-subtree nil nil 'for-yank)
17056 (call-interactively command))
17058 (setq end (point))
17059 (goto-char beg)
17060 (when (and (bolp) subtreep
17061 (not (setq swallowp
17062 (org-yank-folding-would-swallow-text beg end))))
17063 (or (looking-at outline-regexp)
17064 (re-search-forward (concat "^" outline-regexp) end t))
17065 (while (and (< (point) end) (looking-at outline-regexp))
17066 (hide-subtree)
17067 (org-cycle-show-empty-lines 'folded)
17068 (condition-case nil
17069 (outline-forward-same-level 1)
17070 (error (goto-char end)))))
17071 (when swallowp
17072 (message
17073 "Inserted text not folded because that would swallow text"))
17075 (goto-char end)
17076 (skip-chars-forward " \t\n\r")
17077 (beginning-of-line 1)
17078 (push-mark beg 'nomsg)))
17079 ((and subtreep org-yank-adjusted-subtrees)
17080 (let ((beg (point-at-bol)))
17081 (org-paste-subtree nil nil 'for-yank)
17082 (push-mark beg 'nomsg)))
17084 (call-interactively command))))))
17086 (defun org-yank-folding-would-swallow-text (beg end)
17087 "Would hide-subtree at BEG swallow any text after END?"
17088 (let (level)
17089 (save-excursion
17090 (goto-char beg)
17091 (when (or (looking-at outline-regexp)
17092 (re-search-forward (concat "^" outline-regexp) end t))
17093 (setq level (org-outline-level)))
17094 (goto-char end)
17095 (skip-chars-forward " \t\r\n\v\f")
17096 (if (or (eobp)
17097 (and (bolp) (looking-at org-outline-regexp)
17098 (<= (org-outline-level) level)))
17099 nil ; Nothing would be swallowed
17100 t)))) ; something would swallow
17102 (define-key org-mode-map "\C-y" 'org-yank)
17104 (defun org-invisible-p ()
17105 "Check if point is at a character currently not visible."
17106 ;; Early versions of noutline don't have `outline-invisible-p'.
17107 (if (fboundp 'outline-invisible-p)
17108 (outline-invisible-p)
17109 (get-char-property (point) 'invisible)))
17111 (defun org-invisible-p2 ()
17112 "Check if point is at a character currently not visible."
17113 (save-excursion
17114 (if (and (eolp) (not (bobp))) (backward-char 1))
17115 ;; Early versions of noutline don't have `outline-invisible-p'.
17116 (if (fboundp 'outline-invisible-p)
17117 (outline-invisible-p)
17118 (get-char-property (point) 'invisible))))
17120 (defun org-back-to-heading (&optional invisible-ok)
17121 "Call `outline-back-to-heading', but provide a better error message."
17122 (condition-case nil
17123 (outline-back-to-heading invisible-ok)
17124 (error (error "Before first headline at position %d in buffer %s"
17125 (point) (current-buffer)))))
17127 (defun org-before-first-heading-p ()
17128 "Before first heading?"
17129 (save-excursion
17130 (null (re-search-backward "^\\*+ " nil t))))
17132 (defun org-on-heading-p (&optional ignored)
17133 (outline-on-heading-p t))
17134 (defun org-at-heading-p (&optional ignored)
17135 (outline-on-heading-p t))
17137 (defun org-at-heading-or-item-p ()
17138 (or (org-on-heading-p) (org-at-item-p)))
17140 (defun org-on-target-p ()
17141 (or (org-in-regexp org-radio-target-regexp)
17142 (org-in-regexp org-target-regexp)))
17144 (defun org-up-heading-all (arg)
17145 "Move to the heading line of which the present line is a subheading.
17146 This function considers both visible and invisible heading lines.
17147 With argument, move up ARG levels."
17148 (if (fboundp 'outline-up-heading-all)
17149 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17150 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17152 (defun org-up-heading-safe ()
17153 "Move to the heading line of which the present line is a subheading.
17154 This version will not throw an error. It will return the level of the
17155 headline found, or nil if no higher level is found.
17157 Also, this function will be a lot faster than `outline-up-heading',
17158 because it relies on stars being the outline starters. This can really
17159 make a significant difference in outlines with very many siblings."
17160 (let (start-level re)
17161 (org-back-to-heading t)
17162 (setq start-level (funcall outline-level))
17163 (if (equal start-level 1)
17165 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17166 (if (re-search-backward re nil t)
17167 (funcall outline-level)))))
17169 (defun org-first-sibling-p ()
17170 "Is this heading the first child of its parents?"
17171 (interactive)
17172 (let ((re (concat "^" outline-regexp))
17173 level l)
17174 (unless (org-at-heading-p t)
17175 (error "Not at a heading"))
17176 (setq level (funcall outline-level))
17177 (save-excursion
17178 (if (not (re-search-backward re nil t))
17180 (setq l (funcall outline-level))
17181 (< l level)))))
17183 (defun org-goto-sibling (&optional previous)
17184 "Goto the next sibling, even if it is invisible.
17185 When PREVIOUS is set, go to the previous sibling instead. Returns t
17186 when a sibling was found. When none is found, return nil and don't
17187 move point."
17188 (let ((fun (if previous 're-search-backward 're-search-forward))
17189 (pos (point))
17190 (re (concat "^" outline-regexp))
17191 level l)
17192 (when (condition-case nil (org-back-to-heading t) (error nil))
17193 (setq level (funcall outline-level))
17194 (catch 'exit
17195 (or previous (forward-char 1))
17196 (while (funcall fun re nil t)
17197 (setq l (funcall outline-level))
17198 (when (< l level) (goto-char pos) (throw 'exit nil))
17199 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17200 (goto-char pos)
17201 nil))))
17203 (defun org-show-siblings ()
17204 "Show all siblings of the current headline."
17205 (save-excursion
17206 (while (org-goto-sibling) (org-flag-heading nil)))
17207 (save-excursion
17208 (while (org-goto-sibling 'previous)
17209 (org-flag-heading nil))))
17211 (defun org-show-hidden-entry ()
17212 "Show an entry where even the heading is hidden."
17213 (save-excursion
17214 (org-show-entry)))
17216 (defun org-flag-heading (flag &optional entry)
17217 "Flag the current heading. FLAG non-nil means make invisible.
17218 When ENTRY is non-nil, show the entire entry."
17219 (save-excursion
17220 (org-back-to-heading t)
17221 ;; Check if we should show the entire entry
17222 (if entry
17223 (progn
17224 (org-show-entry)
17225 (save-excursion
17226 (and (outline-next-heading)
17227 (org-flag-heading nil))))
17228 (outline-flag-region (max (point-min) (1- (point)))
17229 (save-excursion (outline-end-of-heading) (point))
17230 flag))))
17232 (defun org-get-next-sibling ()
17233 "Move to next heading of the same level, and return point.
17234 If there is no such heading, return nil.
17235 This is like outline-next-sibling, but invisible headings are ok."
17236 (let ((level (funcall outline-level)))
17237 (outline-next-heading)
17238 (while (and (not (eobp)) (> (funcall outline-level) level))
17239 (outline-next-heading))
17240 (if (or (eobp) (< (funcall outline-level) level))
17242 (point))))
17244 (defun org-get-last-sibling ()
17245 "Move to previous heading of the same level, and return point.
17246 If there is no such heading, return nil."
17247 (let ((opoint (point))
17248 (level (funcall outline-level)))
17249 (outline-previous-heading)
17250 (when (and (/= (point) opoint) (outline-on-heading-p t))
17251 (while (and (> (funcall outline-level) level)
17252 (not (bobp)))
17253 (outline-previous-heading))
17254 (if (< (funcall outline-level) level)
17256 (point)))))
17258 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17259 ;; This contains an exact copy of the original function, but it uses
17260 ;; `org-back-to-heading', to make it work also in invisible
17261 ;; trees. And is uses an invisible-OK argument.
17262 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17263 ;; Furthermore, when used inside Org, finding the end of a large subtree
17264 ;; with many children and grandchildren etc, this can be much faster
17265 ;; than the outline version.
17266 (org-back-to-heading invisible-OK)
17267 (let ((first t)
17268 (level (funcall outline-level)))
17269 (if (and (org-mode-p) (< level 1000))
17270 ;; A true heading (not a plain list item), in Org-mode
17271 ;; This means we can easily find the end by looking
17272 ;; only for the right number of stars. Using a regexp to do
17273 ;; this is so much faster than using a Lisp loop.
17274 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17275 (forward-char 1)
17276 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17277 ;; something else, do it the slow way
17278 (while (and (not (eobp))
17279 (or first (> (funcall outline-level) level)))
17280 (setq first nil)
17281 (outline-next-heading)))
17282 (unless to-heading
17283 (if (memq (preceding-char) '(?\n ?\^M))
17284 (progn
17285 ;; Go to end of line before heading
17286 (forward-char -1)
17287 (if (memq (preceding-char) '(?\n ?\^M))
17288 ;; leave blank line before heading
17289 (forward-char -1))))))
17290 (point))
17292 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17293 "Use Org version in org-mode, for dramatic speed-up."
17294 (if (eq major-mode 'org-mode)
17295 (progn
17296 (org-end-of-subtree nil t)
17297 (unless (eobp) (backward-char 1)))
17298 ad-do-it))
17300 (defun org-forward-same-level (arg &optional invisible-ok)
17301 "Move forward to the arg'th subheading at same level as this one.
17302 Stop at the first and last subheadings of a superior heading."
17303 (interactive "p")
17304 (org-back-to-heading invisible-ok)
17305 (org-on-heading-p)
17306 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17307 (re (format "^\\*\\{1,%d\\} " level))
17309 (forward-char 1)
17310 (while (> arg 0)
17311 (while (and (re-search-forward re nil 'move)
17312 (setq l (- (match-end 0) (match-beginning 0) 1))
17313 (= l level)
17314 (not invisible-ok)
17315 (org-invisible-p))
17316 (if (< l level) (setq arg 1)))
17317 (setq arg (1- arg)))
17318 (beginning-of-line 1)))
17320 (defun org-backward-same-level (arg &optional invisible-ok)
17321 "Move backward to the arg'th subheading at same level as this one.
17322 Stop at the first and last subheadings of a superior heading."
17323 (interactive "p")
17324 (org-back-to-heading)
17325 (org-on-heading-p)
17326 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17327 (re (format "^\\*\\{1,%d\\} " level))
17329 (while (> arg 0)
17330 (while (and (re-search-backward re nil 'move)
17331 (setq l (- (match-end 0) (match-beginning 0) 1))
17332 (= l level)
17333 (not invisible-ok)
17334 (org-invisible-p))
17335 (if (< l level) (setq arg 1)))
17336 (setq arg (1- arg)))))
17338 (defun org-show-subtree ()
17339 "Show everything after this heading at deeper levels."
17340 (outline-flag-region
17341 (point)
17342 (save-excursion
17343 (org-end-of-subtree t t))
17344 nil))
17346 (defun org-show-entry ()
17347 "Show the body directly following this heading.
17348 Show the heading too, if it is currently invisible."
17349 (interactive)
17350 (save-excursion
17351 (condition-case nil
17352 (progn
17353 (org-back-to-heading t)
17354 (outline-flag-region
17355 (max (point-min) (1- (point)))
17356 (save-excursion
17357 (if (re-search-forward
17358 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17359 (match-beginning 1)
17360 (point-max)))
17361 nil)
17362 (org-cycle-hide-drawers 'children))
17363 (error nil))))
17365 (defun org-make-options-regexp (kwds &optional extra)
17366 "Make a regular expression for keyword lines."
17367 (concat
17369 "#?[ \t]*\\+\\("
17370 (mapconcat 'regexp-quote kwds "\\|")
17371 (if extra (concat "\\|" extra))
17372 "\\):[ \t]*"
17373 "\\(.*\\)"))
17375 ;; Make isearch reveal the necessary context
17376 (defun org-isearch-end ()
17377 "Reveal context after isearch exits."
17378 (when isearch-success ; only if search was successful
17379 (if (featurep 'xemacs)
17380 ;; Under XEmacs, the hook is run in the correct place,
17381 ;; we directly show the context.
17382 (org-show-context 'isearch)
17383 ;; In Emacs the hook runs *before* restoring the overlays.
17384 ;; So we have to use a one-time post-command-hook to do this.
17385 ;; (Emacs 22 has a special variable, see function `org-mode')
17386 (unless (and (boundp 'isearch-mode-end-hook-quit)
17387 isearch-mode-end-hook-quit)
17388 ;; Only when the isearch was not quitted.
17389 (org-add-hook 'post-command-hook 'org-isearch-post-command
17390 'append 'local)))))
17392 (defun org-isearch-post-command ()
17393 "Remove self from hook, and show context."
17394 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17395 (org-show-context 'isearch))
17398 ;;;; Integration with and fixes for other packages
17400 ;;; Imenu support
17402 (defvar org-imenu-markers nil
17403 "All markers currently used by Imenu.")
17404 (make-variable-buffer-local 'org-imenu-markers)
17406 (defun org-imenu-new-marker (&optional pos)
17407 "Return a new marker for use by Imenu, and remember the marker."
17408 (let ((m (make-marker)))
17409 (move-marker m (or pos (point)))
17410 (push m org-imenu-markers)
17413 (defun org-imenu-get-tree ()
17414 "Produce the index for Imenu."
17415 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17416 (setq org-imenu-markers nil)
17417 (let* ((n org-imenu-depth)
17418 (re (concat "^" outline-regexp))
17419 (subs (make-vector (1+ n) nil))
17420 (last-level 0)
17421 m level head)
17422 (save-excursion
17423 (save-restriction
17424 (widen)
17425 (goto-char (point-max))
17426 (while (re-search-backward re nil t)
17427 (setq level (org-reduced-level (funcall outline-level)))
17428 (when (<= level n)
17429 (looking-at org-complex-heading-regexp)
17430 (setq head (org-link-display-format
17431 (org-match-string-no-properties 4))
17432 m (org-imenu-new-marker))
17433 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17434 (if (>= level last-level)
17435 (push (cons head m) (aref subs level))
17436 (push (cons head (aref subs (1+ level))) (aref subs level))
17437 (loop for i from (1+ level) to n do (aset subs i nil)))
17438 (setq last-level level)))))
17439 (aref subs 1)))
17441 (eval-after-load "imenu"
17442 '(progn
17443 (add-hook 'imenu-after-jump-hook
17444 (lambda ()
17445 (if (eq major-mode 'org-mode)
17446 (org-show-context 'org-goto))))))
17448 (defun org-link-display-format (link)
17449 "Replace a link with either the description, or the link target
17450 if no description is present"
17451 (save-match-data
17452 (if (string-match org-bracket-link-analytic-regexp link)
17453 (replace-match (or (match-string 5 link)
17454 (concat (match-string 1 link)
17455 (match-string 3 link)))
17456 nil nil link)
17457 link)))
17459 ;; Speedbar support
17461 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17462 "Overlay marking the agenda restriction line in speedbar.")
17463 (org-overlay-put org-speedbar-restriction-lock-overlay
17464 'face 'org-agenda-restriction-lock)
17465 (org-overlay-put org-speedbar-restriction-lock-overlay
17466 'help-echo "Agendas are currently limited to this item.")
17467 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17469 (defun org-speedbar-set-agenda-restriction ()
17470 "Restrict future agenda commands to the location at point in speedbar.
17471 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17472 (interactive)
17473 (require 'org-agenda)
17474 (let (p m tp np dir txt)
17475 (cond
17476 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17477 'org-imenu t))
17478 (setq m (get-text-property p 'org-imenu-marker))
17479 (save-excursion
17480 (save-restriction
17481 (set-buffer (marker-buffer m))
17482 (goto-char m)
17483 (org-agenda-set-restriction-lock 'subtree))))
17484 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17485 'speedbar-function 'speedbar-find-file))
17486 (setq tp (previous-single-property-change
17487 (1+ p) 'speedbar-function)
17488 np (next-single-property-change
17489 tp 'speedbar-function)
17490 dir (speedbar-line-directory)
17491 txt (buffer-substring-no-properties (or tp (point-min))
17492 (or np (point-max))))
17493 (save-excursion
17494 (save-restriction
17495 (set-buffer (find-file-noselect
17496 (let ((default-directory dir))
17497 (expand-file-name txt))))
17498 (unless (org-mode-p)
17499 (error "Cannot restrict to non-Org-mode file"))
17500 (org-agenda-set-restriction-lock 'file))))
17501 (t (error "Don't know how to restrict Org-mode's agenda")))
17502 (org-move-overlay org-speedbar-restriction-lock-overlay
17503 (point-at-bol) (point-at-eol))
17504 (setq current-prefix-arg nil)
17505 (org-agenda-maybe-redo)))
17507 (eval-after-load "speedbar"
17508 '(progn
17509 (speedbar-add-supported-extension ".org")
17510 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17511 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17512 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17513 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17514 (add-hook 'speedbar-visiting-tag-hook
17515 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17518 ;;; Fixes and Hacks for problems with other packages
17520 ;; Make flyspell not check words in links, to not mess up our keymap
17521 (defun org-mode-flyspell-verify ()
17522 "Don't let flyspell put overlays at active buttons."
17523 (and (not (get-text-property (point) 'keymap))
17524 (not (get-text-property (point) 'org-no-flyspell))))
17526 (defun org-remove-flyspell-overlays-in (beg end)
17527 "Remove flyspell overlays in region."
17528 (and (org-bound-and-true-p flyspell-mode)
17529 (fboundp 'flyspell-delete-region-overlays)
17530 (flyspell-delete-region-overlays beg end))
17531 (add-text-properties beg end '(org-no-flyspell t)))
17533 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17534 (eval-after-load "bookmark"
17535 '(if (boundp 'bookmark-after-jump-hook)
17536 ;; We can use the hook
17537 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17538 ;; Hook not available, use advice
17539 (defadvice bookmark-jump (after org-make-visible activate)
17540 "Make the position visible."
17541 (org-bookmark-jump-unhide))))
17543 ;; Make sure saveplace shows the location if it was hidden
17544 (eval-after-load "saveplace"
17545 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17546 "Make the position visible."
17547 (org-bookmark-jump-unhide)))
17549 ;; Make sure ecb shows the location if it was hidden
17550 (eval-after-load "ecb"
17551 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17552 "Make hierarchy visible when jumping into location from ECB tree buffer."
17553 (if (eq major-mode 'org-mode)
17554 (org-show-context))))
17556 (defun org-bookmark-jump-unhide ()
17557 "Unhide the current position, to show the bookmark location."
17558 (and (org-mode-p)
17559 (or (org-invisible-p)
17560 (save-excursion (goto-char (max (point-min) (1- (point))))
17561 (org-invisible-p)))
17562 (org-show-context 'bookmark-jump)))
17564 ;; Make session.el ignore our circular variable
17565 (eval-after-load "session"
17566 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17568 ;;;; Experimental code
17570 (defun org-closed-in-range ()
17571 "Sparse tree of items closed in a certain time range.
17572 Still experimental, may disappear in the future."
17573 (interactive)
17574 ;; Get the time interval from the user.
17575 (let* ((time1 (org-float-time
17576 (org-read-date nil 'to-time nil "Starting date: ")))
17577 (time2 (org-float-time
17578 (org-read-date nil 'to-time nil "End date:")))
17579 ;; callback function
17580 (callback (lambda ()
17581 (let ((time
17582 (org-float-time
17583 (apply 'encode-time
17584 (org-parse-time-string
17585 (match-string 1))))))
17586 ;; check if time in interval
17587 (and (>= time time1) (<= time time2))))))
17588 ;; make tree, check each match with the callback
17589 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17591 ;;;; Finish up
17593 (provide 'org)
17595 (run-hooks 'org-load-hook)
17597 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17599 ;;; org.el ends here