Release 6.33a
[org-mode/org-tableheadings.git] / lisp / org.el
blobc5499a328092ed7e98c4e9d2d4895b88dfdbd212
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.33a
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.33a"
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* ((origin default-directory)
106 (version org-version)
107 (git-version)
108 (dir (concat (file-name-directory (locate-library "org")) "../" )))
109 (when (and (file-exists-p (expand-file-name ".git" dir))
110 (executable-find "git"))
111 (unwind-protect
112 (progn
113 (cd dir)
114 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
115 (with-current-buffer "*Shell Command Output*"
116 (goto-char (point-min))
117 (setq git-version (buffer-substring (point) (point-at-eol))))
118 (subst-char-in-string ?- ?. git-version t)
119 (when (string-match "\\S-"
120 (shell-command-to-string
121 "git diff-index --name-only HEAD --"))
122 (setq git-version (concat git-version ".dirty")))
123 (setq version (concat version " (" git-version ")"))))
124 (cd origin)))
125 (setq version (format "Org-mode version %s" version))
126 (if here (insert version))
127 (message 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 bookmark: Org-mode links to bookmarks" org-bookmark)
211 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
212 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
213 (const :tag "C collector: Collect properties into tables" org-collector)
214 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
215 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
216 (const :tag "C eval: Include command output as text" org-eval)
217 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
218 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
219 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
220 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
221 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
223 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
225 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
226 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
227 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
228 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
229 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
230 (const :tag "C mtags: Support for muse-like tags" org-mtags)
231 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
232 (const :tag "C R: Computation using the R language" org-R)
233 (const :tag "C registry: A registry for Org-mode links" org-registry)
234 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
235 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
236 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
237 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
238 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
239 (const :tag "C track: Keep up with Org-mode development" org-track)
240 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
242 (defcustom org-support-shift-select nil
243 "Non-nil means, make shift-cursor commands select text when possible.
245 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
246 selecting a region, or enlarge thusly regions started in this way.
247 In Org-mode, in special contexts, these same keys are used for other
248 purposes, important enough to compete with shift selection. Org tries
249 to balance these needs by supporting `shift-select-mode' outside these
250 special contexts, under control of this variable.
252 The default of this variable is nil, to avoid confusing behavior. Shifted
253 cursor keys will then execute Org commands in the following contexts:
254 - on a headline, changing TODO state (left/right) and priority (up/down)
255 - on a time stamp, changing the time
256 - in a plain list item, changing the bullet type
257 - in a property definition line, switching between allowed values
258 - in the BEGIN line of a clock table (changing the time block).
259 Outside these contexts, the commands will throw an error.
261 When this variable is t and the cursor is not in a special context,
262 Org-mode will support shift-selection for making and enlarging regions.
263 To make this more effective, the bullet cycling will no longer happen
264 anywhere in an item line, but only if the cursor is exactly on the bullet.
266 If you set this variable to the symbol `always', then the keys
267 will not be special in headlines, property lines, and item lines, to make
268 shift selection work there as well. If this is what you want, you can
269 use the following alternative commands: `C-c C-t' and `C-c ,' to
270 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
271 TODO sets, `C-c -' to cycle item bullet types, and properties can be
272 edited by hand or in column view.
274 However, when the cursor is on a timestamp, shift-cursor commands
275 will still edit the time stamp - this is just too good to give up.
277 XEmacs user should have this variable set to nil, because shift-select-mode
278 is Emacs 23 only."
279 :group 'org
280 :type '(choice
281 (const :tag "Never" nil)
282 (const :tag "When outside special context" t)
283 (const :tag "Everywhere except timestamps" always)))
285 (defgroup org-startup nil
286 "Options concerning startup of Org-mode."
287 :tag "Org Startup"
288 :group 'org)
290 (defcustom org-startup-folded t
291 "Non-nil means, entering Org-mode will switch to OVERVIEW.
292 This can also be configured on a per-file basis by adding one of
293 the following lines anywhere in the buffer:
295 #+STARTUP: fold (or `overview', this is equivalent)
296 #+STARTUP: nofold (or `showall', this is equivalent)
297 #+STARTUP: content
298 #+STARTUP: showeverything"
299 :group 'org-startup
300 :type '(choice
301 (const :tag "nofold: show all" nil)
302 (const :tag "fold: overview" t)
303 (const :tag "content: all headlines" content)
304 (const :tag "show everything, even drawers" showeverything)))
306 (defcustom org-startup-truncated t
307 "Non-nil means, entering Org-mode will set `truncate-lines'.
308 This is useful since some lines containing links can be very long and
309 uninteresting. Also tables look terrible when wrapped."
310 :group 'org-startup
311 :type 'boolean)
313 (defcustom org-startup-indented nil
314 "Non-nil means, turn on `org-indent-mode' on startup.
315 This can also be configured on a per-file basis by adding one of
316 the following lines anywhere in the buffer:
318 #+STARTUP: indent
319 #+STARTUP: noindent"
320 :group 'org-structure
321 :type '(choice
322 (const :tag "Not" nil)
323 (const :tag "Globally (slow on startup in large files)" t)))
325 (defcustom org-startup-align-all-tables nil
326 "Non-nil means, align all tables when visiting a file.
327 This is useful when the column width in tables is forced with <N> cookies
328 in table fields. Such tables will look correct only after the first re-align.
329 This can also be configured on a per-file basis by adding one of
330 the following lines anywhere in the buffer:
331 #+STARTUP: align
332 #+STARTUP: noalign"
333 :group 'org-startup
334 :type 'boolean)
336 (defcustom org-insert-mode-line-in-empty-file nil
337 "Non-nil means insert the first line setting Org-mode in empty files.
338 When the function `org-mode' is called interactively in an empty file, this
339 normally means that the file name does not automatically trigger Org-mode.
340 To ensure that the file will always be in Org-mode in the future, a
341 line enforcing Org-mode will be inserted into the buffer, if this option
342 has been set."
343 :group 'org-startup
344 :type 'boolean)
346 (defcustom org-replace-disputed-keys nil
347 "Non-nil means use alternative key bindings for some keys.
348 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
349 These keys are also used by other packages like shift-selection-mode'
350 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
351 If you want to use Org-mode together with one of these other modes,
352 or more generally if you would like to move some Org-mode commands to
353 other keys, set this variable and configure the keys with the variable
354 `org-disputed-keys'.
356 This option is only relevant at load-time of Org-mode, and must be set
357 *before* org.el is loaded. Changing it requires a restart of Emacs to
358 become effective."
359 :group 'org-startup
360 :type 'boolean)
362 (defcustom org-use-extra-keys nil
363 "Non-nil means use extra key sequence definitions for certain
364 commands. This happens automatically if you run XEmacs or if
365 window-system is nil. This variable lets you do the same
366 manually. You must set it before loading org.
368 Example: on Carbon Emacs 22 running graphically, with an external
369 keyboard on a Powerbook, the default way of setting M-left might
370 not work for either Alt or ESC. Setting this variable will make
371 it work for ESC."
372 :group 'org-startup
373 :type 'boolean)
375 (if (fboundp 'defvaralias)
376 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
378 (defcustom org-disputed-keys
379 '(([(shift up)] . [(meta p)])
380 ([(shift down)] . [(meta n)])
381 ([(shift left)] . [(meta -)])
382 ([(shift right)] . [(meta +)])
383 ([(control shift right)] . [(meta shift +)])
384 ([(control shift left)] . [(meta shift -)]))
385 "Keys for which Org-mode and other modes compete.
386 This is an alist, cars are the default keys, second element specifies
387 the alternative to use when `org-replace-disputed-keys' is t.
389 Keys can be specified in any syntax supported by `define-key'.
390 The value of this option takes effect only at Org-mode's startup,
391 therefore you'll have to restart Emacs to apply it after changing."
392 :group 'org-startup
393 :type 'alist)
395 (defun org-key (key)
396 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
397 Or return the original if not disputed."
398 (if org-replace-disputed-keys
399 (let* ((nkey (key-description key))
400 (x (org-find-if (lambda (x)
401 (equal (key-description (car x)) nkey))
402 org-disputed-keys)))
403 (if x (cdr x) key))
404 key))
406 (defun org-find-if (predicate seq)
407 (catch 'exit
408 (while seq
409 (if (funcall predicate (car seq))
410 (throw 'exit (car seq))
411 (pop seq)))))
413 (defun org-defkey (keymap key def)
414 "Define a key, possibly translated, as returned by `org-key'."
415 (define-key keymap (org-key key) def))
417 (defcustom org-ellipsis nil
418 "The ellipsis to use in the Org-mode outline.
419 When nil, just use the standard three dots. When a string, use that instead,
420 When a face, use the standard 3 dots, but with the specified face.
421 The change affects only Org-mode (which will then use its own display table).
422 Changing this requires executing `M-x org-mode' in a buffer to become
423 effective."
424 :group 'org-startup
425 :type '(choice (const :tag "Default" nil)
426 (face :tag "Face" :value org-warning)
427 (string :tag "String" :value "...#")))
429 (defvar org-display-table nil
430 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
432 (defgroup org-keywords nil
433 "Keywords in Org-mode."
434 :tag "Org Keywords"
435 :group 'org)
437 (defcustom org-deadline-string "DEADLINE:"
438 "String to mark deadline entries.
439 A deadline is this string, followed by a time stamp. Should be a word,
440 terminated by a colon. You can insert a schedule keyword and
441 a timestamp with \\[org-deadline].
442 Changes become only effective after restarting Emacs."
443 :group 'org-keywords
444 :type 'string)
446 (defcustom org-scheduled-string "SCHEDULED:"
447 "String to mark scheduled TODO entries.
448 A schedule is this string, followed by a time stamp. Should be a word,
449 terminated by a colon. You can insert a schedule keyword and
450 a timestamp with \\[org-schedule].
451 Changes become only effective after restarting Emacs."
452 :group 'org-keywords
453 :type 'string)
455 (defcustom org-closed-string "CLOSED:"
456 "String used as the prefix for timestamps logging closing a TODO entry."
457 :group 'org-keywords
458 :type 'string)
460 (defcustom org-clock-string "CLOCK:"
461 "String used as prefix for timestamps clocking work hours on an item."
462 :group 'org-keywords
463 :type 'string)
465 (defcustom org-comment-string "COMMENT"
466 "Entries starting with this keyword will never be exported.
467 An entry can be toggled between COMMENT and normal with
468 \\[org-toggle-comment].
469 Changes become only effective after restarting Emacs."
470 :group 'org-keywords
471 :type 'string)
473 (defcustom org-quote-string "QUOTE"
474 "Entries starting with this keyword will be exported in fixed-width font.
475 Quoting applies only to the text in the entry following the headline, and does
476 not extend beyond the next headline, even if that is lower level.
477 An entry can be toggled between QUOTE and normal with
478 \\[org-toggle-fixed-width-section]."
479 :group 'org-keywords
480 :type 'string)
482 (defconst org-repeat-re
483 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
484 "Regular expression for specifying repeated events.
485 After a match, group 1 contains the repeat expression.")
487 (defgroup org-structure nil
488 "Options concerning the general structure of Org-mode files."
489 :tag "Org Structure"
490 :group 'org)
492 (defgroup org-reveal-location nil
493 "Options about how to make context of a location visible."
494 :tag "Org Reveal Location"
495 :group 'org-structure)
497 (defconst org-context-choice
498 '(choice
499 (const :tag "Always" t)
500 (const :tag "Never" nil)
501 (repeat :greedy t :tag "Individual contexts"
502 (cons
503 (choice :tag "Context"
504 (const agenda)
505 (const org-goto)
506 (const occur-tree)
507 (const tags-tree)
508 (const link-search)
509 (const mark-goto)
510 (const bookmark-jump)
511 (const isearch)
512 (const default))
513 (boolean))))
514 "Contexts for the reveal options.")
516 (defcustom org-show-hierarchy-above '((default . t))
517 "Non-nil means, show full hierarchy when revealing a location.
518 Org-mode often shows locations in an org-mode file which might have
519 been invisible before. When this is set, the hierarchy of headings
520 above the exposed location is shown.
521 Turning this off for example for sparse trees makes them very compact.
522 Instead of t, this can also be an alist specifying this option for different
523 contexts. Valid contexts are
524 agenda when exposing an entry from the agenda
525 org-goto when using the command `org-goto' on key C-c C-j
526 occur-tree when using the command `org-occur' on key C-c /
527 tags-tree when constructing a sparse tree based on tags matches
528 link-search when exposing search matches associated with a link
529 mark-goto when exposing the jump goal of a mark
530 bookmark-jump when exposing a bookmark location
531 isearch when exiting from an incremental search
532 default default for all contexts not set explicitly"
533 :group 'org-reveal-location
534 :type org-context-choice)
536 (defcustom org-show-following-heading '((default . nil))
537 "Non-nil means, show following heading when revealing a location.
538 Org-mode often shows locations in an org-mode file which might have
539 been invisible before. When this is set, the heading following the
540 match is shown.
541 Turning this off for example for sparse trees makes them very compact,
542 but makes it harder to edit the location of the match. In such a case,
543 use the command \\[org-reveal] to show more context.
544 Instead of t, this can also be an alist specifying this option for different
545 contexts. See `org-show-hierarchy-above' for valid contexts."
546 :group 'org-reveal-location
547 :type org-context-choice)
549 (defcustom org-show-siblings '((default . nil) (isearch t))
550 "Non-nil means, show all sibling heading when revealing a location.
551 Org-mode often shows locations in an org-mode file which might have
552 been invisible before. When this is set, the sibling of the current entry
553 heading are all made visible. If `org-show-hierarchy-above' is t,
554 the same happens on each level of the hierarchy above the current entry.
556 By default this is on for the isearch context, off for all other contexts.
557 Turning this off for example for sparse trees makes them very compact,
558 but makes it harder to edit the location of the match. In such a case,
559 use the command \\[org-reveal] to show more context.
560 Instead of t, this can also be an alist specifying this option for different
561 contexts. See `org-show-hierarchy-above' for valid contexts."
562 :group 'org-reveal-location
563 :type org-context-choice)
565 (defcustom org-show-entry-below '((default . nil))
566 "Non-nil means, show the entry below a headline when revealing a location.
567 Org-mode often shows locations in an org-mode file which might have
568 been invisible before. When this is set, the text below the headline that is
569 exposed is also shown.
571 By default this is off for all contexts.
572 Instead of t, this can also be an alist specifying this option for different
573 contexts. See `org-show-hierarchy-above' for valid contexts."
574 :group 'org-reveal-location
575 :type org-context-choice)
577 (defcustom org-indirect-buffer-display 'other-window
578 "How should indirect tree buffers be displayed?
579 This applies to indirect buffers created with the commands
580 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
581 Valid values are:
582 current-window Display in the current window
583 other-window Just display in another window.
584 dedicated-frame Create one new frame, and re-use it each time.
585 new-frame Make a new frame each time. Note that in this case
586 previously-made indirect buffers are kept, and you need to
587 kill these buffers yourself."
588 :group 'org-structure
589 :group 'org-agenda-windows
590 :type '(choice
591 (const :tag "In current window" current-window)
592 (const :tag "In current frame, other window" other-window)
593 (const :tag "Each time a new frame" new-frame)
594 (const :tag "One dedicated frame" dedicated-frame)))
596 (defcustom org-use-speed-commands nil
597 "Non-nil means, activate single letter commands at beginning of a headline.
598 This may also be a function to test for appropriate locations where speed
599 commands should be active."
600 :group 'org-structure
601 :type '(choice
602 (const :tag "Never" nil)
603 (const :tag "At beginning of headline stars" t)
604 (function)))
606 (defcustom org-speed-commands-user nil
607 "Alist of additional speed commands.
608 This list will be checked before `org-speed-commands-default'
609 when the variable `org-use-speed-commands' is non-nil
610 and when the cursor is at the beginning of a headline.
611 The car if each entry is a string with a single letter, which must
612 be assigned to `self-insert-command' in the global map.
613 The cdr is either a command to be called interactively, a function
614 to be called, or a form to be evaluated."
615 :group 'org-structure
616 :type '(repeat
617 (cons
618 (string "Command letter")
619 (choice
620 (function)
621 (sexp)))))
623 (defgroup org-cycle nil
624 "Options concerning visibility cycling in Org-mode."
625 :tag "Org Cycle"
626 :group 'org-structure)
628 (defcustom org-cycle-skip-children-state-if-no-children t
629 "Non-nil means, skip CHILDREN state in entries that don't have any."
630 :group 'org-cycle
631 :type 'boolean)
633 (defcustom org-cycle-max-level nil
634 "Maximum level which should still be subject to visibility cycling.
635 Levels higher than this will, for cycling, be treated as text, not a headline.
636 When `org-odd-levels-only' is set, a value of N in this variable actually
637 means 2N-1 stars as the limiting headline.
638 When nil, cycle all levels.
639 Note that the limiting level of cycling is also influenced by
640 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
641 `org-inlinetask-min-level' is, cycling will be limited to levels one less
642 than its value."
643 :group 'org-cycle
644 :type '(choice
645 (const :tag "No limit" nil)
646 (integer :tag "Maximum level")))
648 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
649 "Names of drawers. Drawers are not opened by cycling on the headline above.
650 Drawers only open with a TAB on the drawer line itself. A drawer looks like
651 this:
652 :DRAWERNAME:
653 .....
654 :END:
655 The drawer \"PROPERTIES\" is special for capturing properties through
656 the property API.
658 Drawers can be defined on the per-file basis with a line like:
660 #+DRAWERS: HIDDEN STATE PROPERTIES"
661 :group 'org-structure
662 :group 'org-cycle
663 :type '(repeat (string :tag "Drawer Name")))
665 (defcustom org-hide-block-startup nil
666 "Non-nil means, , entering Org-mode will fold all blocks.
667 This can also be set in on a per-file basis with
669 #+STARTUP: hideblocks
670 #+STARTUP: showblocks"
671 :group 'org-startup
672 :group 'org-cycle
673 :type 'boolean)
675 (defcustom org-cycle-global-at-bob nil
676 "Cycle globally if cursor is at beginning of buffer and not at a headline.
677 This makes it possible to do global cycling without having to use S-TAB or
678 C-u TAB. For this special case to work, the first line of the buffer
679 must not be a headline - it may be empty or some other text. When used in
680 this way, `org-cycle-hook' is disables temporarily, to make sure the
681 cursor stays at the beginning of the buffer.
682 When this option is nil, don't do anything special at the beginning
683 of the buffer."
684 :group 'org-cycle
685 :type 'boolean)
687 (defcustom org-cycle-level-after-item/entry-creation t
688 "Non-nil means, cycle entry level or item indentation in new empty entries.
690 When the cursor is at the end of an empty headline, i.e with only stars
691 and maybe a TODO keyword, TAB will then switch the entry to become a child,
692 and then all possible anchestor states, before returning to the original state.
693 This makes data entry extremely fast: M-RET to create a new headline,
694 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
696 When the cursor is at the end of an empty plain list item, one TAB will
697 make it a subitem, two or more tabs will back up to make this an item
698 higher up in the item hierarchy."
699 :group 'org-cycle
700 :type 'boolean)
702 (defcustom org-cycle-emulate-tab t
703 "Where should `org-cycle' emulate TAB.
704 nil Never
705 white Only in completely white lines
706 whitestart Only at the beginning of lines, before the first non-white char
707 t Everywhere except in headlines
708 exc-hl-bol Everywhere except at the start of a headline
709 If TAB is used in a place where it does not emulate TAB, the current subtree
710 visibility is cycled."
711 :group 'org-cycle
712 :type '(choice (const :tag "Never" nil)
713 (const :tag "Only in completely white lines" white)
714 (const :tag "Before first char in a line" whitestart)
715 (const :tag "Everywhere except in headlines" t)
716 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
719 (defcustom org-cycle-separator-lines 2
720 "Number of empty lines needed to keep an empty line between collapsed trees.
721 If you leave an empty line between the end of a subtree and the following
722 headline, this empty line is hidden when the subtree is folded.
723 Org-mode will leave (exactly) one empty line visible if the number of
724 empty lines is equal or larger to the number given in this variable.
725 So the default 2 means, at least 2 empty lines after the end of a subtree
726 are needed to produce free space between a collapsed subtree and the
727 following headline.
729 If the number is negative, and the number of empty lines is at least -N,
730 all empty lines are shown.
732 Special case: when 0, never leave empty lines in collapsed view."
733 :group 'org-cycle
734 :type 'integer)
735 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
737 (defcustom org-pre-cycle-hook nil
738 "Hook that is run before visibility cycling is happening.
739 The function(s) in this hook must accept a single argument which indicates
740 the new state that will be set right after running this hook. The
741 argument is a symbol. Before a global state change, it can have the values
742 `overview', `content', or `all'. Before a local state change, it can have
743 the values `folded', `children', or `subtree'."
744 :group 'org-cycle
745 :type 'hook)
747 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
748 org-cycle-hide-drawers
749 org-cycle-show-empty-lines
750 org-optimize-window-after-visibility-change)
751 "Hook that is run after `org-cycle' has changed the buffer visibility.
752 The function(s) in this hook must accept a single argument which indicates
753 the new state that was set by the most recent `org-cycle' command. The
754 argument is a symbol. After a global state change, it can have the values
755 `overview', `content', or `all'. After a local state change, it can have
756 the values `folded', `children', or `subtree'."
757 :group 'org-cycle
758 :type 'hook)
760 (defgroup org-edit-structure nil
761 "Options concerning structure editing in Org-mode."
762 :tag "Org Edit Structure"
763 :group 'org-structure)
765 (defcustom org-odd-levels-only nil
766 "Non-nil means, skip even levels and only use odd levels for the outline.
767 This has the effect that two stars are being added/taken away in
768 promotion/demotion commands. It also influences how levels are
769 handled by the exporters.
770 Changing it requires restart of `font-lock-mode' to become effective
771 for fontification also in regions already fontified.
772 You may also set this on a per-file basis by adding one of the following
773 lines to the buffer:
775 #+STARTUP: odd
776 #+STARTUP: oddeven"
777 :group 'org-edit-structure
778 :group 'org-font-lock
779 :type 'boolean)
781 (defcustom org-adapt-indentation t
782 "Non-nil means, adapt indentation to outline node level.
784 When this variable is set, Org assumes that you write outlines by
785 indenting text in each node to align with the headline (after the stars).
786 The following issues are influenced by this variable:
788 - When this is set and the *entire* text in an entry is indented, the
789 indentation is increased by one space in a demotion command, and
790 decreased by one in a promotion command. If any line in the entry
791 body starts with text at column 0, indentation is not changed at all.
793 - Property drawers and planning information is inserted indented when
794 this variable s set. When nil, they will not be indented.
796 - TAB indents a line relative to context. The lines below a headline
797 will be indented when this variable is set.
799 Note that this is all about true indentation, by adding and removing
800 space characters. See also `org-indent.el' which does level-dependent
801 indentation in a virtual way, i.e. at display time in Emacs."
802 :group 'org-edit-structure
803 :type 'boolean)
805 (defcustom org-special-ctrl-a/e nil
806 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
808 When t, `C-a' will bring back the cursor to the beginning of the
809 headline text, i.e. after the stars and after a possible TODO keyword.
810 In an item, this will be the position after the bullet.
811 When the cursor is already at that position, another `C-a' will bring
812 it to the beginning of the line.
814 `C-e' will jump to the end of the headline, ignoring the presence of tags
815 in the headline. A second `C-e' will then jump to the true end of the
816 line, after any tags. This also means that, when this variable is
817 non-nil, `C-e' also will never jump beyond the end of the heading of a
818 folded section, i.e. not after the ellipses.
820 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
821 going to the true line boundary first. Only a directly following, identical
822 keypress will bring the cursor to the special positions.
824 This may also be a cons cell where the behavior for `C-a' and `C-e' is
825 set separately."
826 :group 'org-edit-structure
827 :type '(choice
828 (const :tag "off" nil)
829 (const :tag "on: after stars/bullet and before tags first" t)
830 (const :tag "reversed: true line boundary first" reversed)
831 (cons :tag "Set C-a and C-e separately"
832 (choice :tag "Special C-a"
833 (const :tag "off" nil)
834 (const :tag "on: after stars/bullet first" t)
835 (const :tag "reversed: before stars/bullet first" reversed))
836 (choice :tag "Special C-e"
837 (const :tag "off" nil)
838 (const :tag "on: before tags first" t)
839 (const :tag "reversed: after tags first" reversed)))))
840 (if (fboundp 'defvaralias)
841 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
843 (defcustom org-special-ctrl-k nil
844 "Non-nil means `C-k' will behave specially in headlines.
845 When nil, `C-k' will call the default `kill-line' command.
846 When t, the following will happen while the cursor is in the headline:
848 - When the cursor is at the beginning of a headline, kill the entire
849 line and possible the folded subtree below the line.
850 - When in the middle of the headline text, kill the headline up to the tags.
851 - When after the headline text, kill the tags."
852 :group 'org-edit-structure
853 :type 'boolean)
855 (defcustom org-yank-folded-subtrees t
856 "Non-nil means, when yanking subtrees, fold them.
857 If the kill is a single subtree, or a sequence of subtrees, i.e. if
858 it starts with a heading and all other headings in it are either children
859 or siblings, then fold all the subtrees. However, do this only if no
860 text after the yank would be swallowed into a folded tree by this action."
861 :group 'org-edit-structure
862 :type 'boolean)
864 (defcustom org-yank-adjusted-subtrees nil
865 "Non-nil means, when yanking subtrees, adjust the level.
866 With this setting, `org-paste-subtree' is used to insert the subtree, see
867 this function for details."
868 :group 'org-edit-structure
869 :type 'boolean)
871 (defcustom org-M-RET-may-split-line '((default . t))
872 "Non-nil means, M-RET will split the line at the cursor position.
873 When nil, it will go to the end of the line before making a
874 new line.
875 You may also set this option in a different way for different
876 contexts. Valid contexts are:
878 headline when creating a new headline
879 item when creating a new item
880 table in a table field
881 default the value to be used for all contexts not explicitly
882 customized"
883 :group 'org-structure
884 :group 'org-table
885 :type '(choice
886 (const :tag "Always" t)
887 (const :tag "Never" nil)
888 (repeat :greedy t :tag "Individual contexts"
889 (cons
890 (choice :tag "Context"
891 (const headline)
892 (const item)
893 (const table)
894 (const default))
895 (boolean)))))
898 (defcustom org-insert-heading-respect-content nil
899 "Non-nil means, insert new headings after the current subtree.
900 When nil, the new heading is created directly after the current line.
901 The commands \\[org-insert-heading-respect-content] and
902 \\[org-insert-todo-heading-respect-content] turn this variable on
903 for the duration of the command."
904 :group 'org-structure
905 :type 'boolean)
907 (defcustom org-blank-before-new-entry '((heading . auto)
908 (plain-list-item . auto))
909 "Should `org-insert-heading' leave a blank line before new heading/item?
910 The value is an alist, with `heading' and `plain-list-item' as car,
911 and a boolean flag as cdr. For plain lists, if the variable
912 `org-empty-line-terminates-plain-lists' is set, the setting here
913 is ignored and no empty line is inserted, to keep the list in tact."
914 :group 'org-edit-structure
915 :type '(list
916 (cons (const heading)
917 (choice (const :tag "Never" nil)
918 (const :tag "Always" t)
919 (const :tag "Auto" auto)))
920 (cons (const plain-list-item)
921 (choice (const :tag "Never" nil)
922 (const :tag "Always" t)
923 (const :tag "Auto" auto)))))
925 (defcustom org-insert-heading-hook nil
926 "Hook being run after inserting a new heading."
927 :group 'org-edit-structure
928 :type 'hook)
930 (defcustom org-enable-fixed-width-editor t
931 "Non-nil means, lines starting with \":\" are treated as fixed-width.
932 This currently only means, they are never auto-wrapped.
933 When nil, such lines will be treated like ordinary lines.
934 See also the QUOTE keyword."
935 :group 'org-edit-structure
936 :type 'boolean)
939 (defcustom org-goto-auto-isearch t
940 "Non-nil means, typing characters in org-goto starts incremental search."
941 :group 'org-edit-structure
942 :type 'boolean)
944 (defgroup org-sparse-trees nil
945 "Options concerning sparse trees in Org-mode."
946 :tag "Org Sparse Trees"
947 :group 'org-structure)
949 (defcustom org-highlight-sparse-tree-matches t
950 "Non-nil means, highlight all matches that define a sparse tree.
951 The highlights will automatically disappear the next time the buffer is
952 changed by an edit command."
953 :group 'org-sparse-trees
954 :type 'boolean)
956 (defcustom org-remove-highlights-with-change t
957 "Non-nil means, any change to the buffer will remove temporary highlights.
958 Such highlights are created by `org-occur' and `org-clock-display'.
959 When nil, `C-c C-c needs to be used to get rid of the highlights.
960 The highlights created by `org-preview-latex-fragment' always need
961 `C-c C-c' to be removed."
962 :group 'org-sparse-trees
963 :group 'org-time
964 :type 'boolean)
967 (defcustom org-occur-hook '(org-first-headline-recenter)
968 "Hook that is run after `org-occur' has constructed a sparse tree.
969 This can be used to recenter the window to show as much of the structure
970 as possible."
971 :group 'org-sparse-trees
972 :type 'hook)
974 (defgroup org-imenu-and-speedbar nil
975 "Options concerning imenu and speedbar in Org-mode."
976 :tag "Org Imenu and Speedbar"
977 :group 'org-structure)
979 (defcustom org-imenu-depth 2
980 "The maximum level for Imenu access to Org-mode headlines.
981 This also applied for speedbar access."
982 :group 'org-imenu-and-speedbar
983 :type 'integer)
985 (defgroup org-table nil
986 "Options concerning tables in Org-mode."
987 :tag "Org Table"
988 :group 'org)
990 (defcustom org-enable-table-editor 'optimized
991 "Non-nil means, lines starting with \"|\" are handled by the table editor.
992 When nil, such lines will be treated like ordinary lines.
994 When equal to the symbol `optimized', the table editor will be optimized to
995 do the following:
996 - Automatic overwrite mode in front of whitespace in table fields.
997 This makes the structure of the table stay in tact as long as the edited
998 field does not exceed the column width.
999 - Minimize the number of realigns. Normally, the table is aligned each time
1000 TAB or RET are pressed to move to another field. With optimization this
1001 happens only if changes to a field might have changed the column width.
1002 Optimization requires replacing the functions `self-insert-command',
1003 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1004 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1005 very good at guessing when a re-align will be necessary, but you can always
1006 force one with \\[org-ctrl-c-ctrl-c].
1008 If you would like to use the optimized version in Org-mode, but the
1009 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1011 This variable can be used to turn on and off the table editor during a session,
1012 but in order to toggle optimization, a restart is required.
1014 See also the variable `org-table-auto-blank-field'."
1015 :group 'org-table
1016 :type '(choice
1017 (const :tag "off" nil)
1018 (const :tag "on" t)
1019 (const :tag "on, optimized" optimized)))
1021 (defcustom org-self-insert-cluster-for-undo t
1022 "Non-nil means cluster self-insert commands for undo when possible.
1023 If this is set, then, like in the Emacs command loop, 20 consecutive
1024 characters will be undone together.
1025 This is configurable, because there is some impact on typing performance."
1026 :group 'org-table
1027 :type 'boolean)
1029 (defcustom org-table-tab-recognizes-table.el t
1030 "Non-nil means, TAB will automatically notice a table.el table.
1031 When it sees such a table, it moves point into it and - if necessary -
1032 calls `table-recognize-table'."
1033 :group 'org-table-editing
1034 :type 'boolean)
1036 (defgroup org-link nil
1037 "Options concerning links in Org-mode."
1038 :tag "Org Link"
1039 :group 'org)
1041 (defvar org-link-abbrev-alist-local nil
1042 "Buffer-local version of `org-link-abbrev-alist', which see.
1043 The value of this is taken from the #+LINK lines.")
1044 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1046 (defcustom org-link-abbrev-alist nil
1047 "Alist of link abbreviations.
1048 The car of each element is a string, to be replaced at the start of a link.
1049 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1050 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1052 [[linkkey:tag][description]]
1054 The 'linkkey' must be a word word, starting with a letter, followed
1055 by letters, numbers, '-' or '_'.
1057 If REPLACE is a string, the tag will simply be appended to create the link.
1058 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1059 the placeholder \"%h\" will cause a url-encoded version of the tag to
1060 be inserted at that point (see the function `url-hexify-string').
1062 REPLACE may also be a function that will be called with the tag as the
1063 only argument to create the link, which should be returned as a string.
1065 See the manual for examples."
1066 :group 'org-link
1067 :type '(repeat
1068 (cons
1069 (string :tag "Protocol")
1070 (choice
1071 (string :tag "Format")
1072 (function)))))
1074 (defcustom org-descriptive-links t
1075 "Non-nil means, hide link part and only show description of bracket links.
1076 Bracket links are like [[link][description]]. This variable sets the initial
1077 state in new org-mode buffers. The setting can then be toggled on a
1078 per-buffer basis from the Org->Hyperlinks menu."
1079 :group 'org-link
1080 :type 'boolean)
1082 (defcustom org-link-file-path-type 'adaptive
1083 "How the path name in file links should be stored.
1084 Valid values are:
1086 relative Relative to the current directory, i.e. the directory of the file
1087 into which the link is being inserted.
1088 absolute Absolute path, if possible with ~ for home directory.
1089 noabbrev Absolute path, no abbreviation of home directory.
1090 adaptive Use relative path for files in the current directory and sub-
1091 directories of it. For other files, use an absolute path."
1092 :group 'org-link
1093 :type '(choice
1094 (const relative)
1095 (const absolute)
1096 (const noabbrev)
1097 (const adaptive)))
1099 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1100 "Types of links that should be activated in Org-mode files.
1101 This is a list of symbols, each leading to the activation of a certain link
1102 type. In principle, it does not hurt to turn on most link types - there may
1103 be a small gain when turning off unused link types. The types are:
1105 bracket The recommended [[link][description]] or [[link]] links with hiding.
1106 angular Links in angular brackets that may contain whitespace like
1107 <bbdb:Carsten Dominik>.
1108 plain Plain links in normal text, no whitespace, like http://google.com.
1109 radio Text that is matched by a radio target, see manual for details.
1110 tag Tag settings in a headline (link to tag search).
1111 date Time stamps (link to calendar).
1112 footnote Footnote labels.
1114 Changing this variable requires a restart of Emacs to become effective."
1115 :group 'org-link
1116 :type '(set :greedy t
1117 (const :tag "Double bracket links (new style)" bracket)
1118 (const :tag "Angular bracket links (old style)" angular)
1119 (const :tag "Plain text links" plain)
1120 (const :tag "Radio target matches" radio)
1121 (const :tag "Tags" tag)
1122 (const :tag "Timestamps" date)
1123 (const :tag "Footnotes" footnote)))
1125 (defcustom org-make-link-description-function nil
1126 "Function to use to generate link descriptions from links. If
1127 nil the link location will be used. This function must take two
1128 parameters; the first is the link and the second the description
1129 org-insert-link has generated, and should return the description
1130 to use."
1131 :group 'org-link
1132 :type 'function)
1134 (defgroup org-link-store nil
1135 "Options concerning storing links in Org-mode."
1136 :tag "Org Store Link"
1137 :group 'org-link)
1139 (defcustom org-email-link-description-format "Email %c: %.30s"
1140 "Format of the description part of a link to an email or usenet message.
1141 The following %-escapes will be replaced by corresponding information:
1143 %F full \"From\" field
1144 %f name, taken from \"From\" field, address if no name
1145 %T full \"To\" field
1146 %t first name in \"To\" field, address if no name
1147 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1148 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1149 %s subject
1150 %m message-id.
1152 You may use normal field width specification between the % and the letter.
1153 This is for example useful to limit the length of the subject.
1155 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1156 :group 'org-link-store
1157 :type 'string)
1159 (defcustom org-from-is-user-regexp
1160 (let (r1 r2)
1161 (when (and user-mail-address (not (string= user-mail-address "")))
1162 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1163 (when (and user-full-name (not (string= user-full-name "")))
1164 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1165 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1166 "Regexp matched against the \"From:\" header of an email or usenet message.
1167 It should match if the message is from the user him/herself."
1168 :group 'org-link-store
1169 :type 'regexp)
1171 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1172 "Non-nil means, storing a link to an Org file will use entry IDs.
1174 Note that before this variable is even considered, org-id must be loaded,
1175 so please customize `org-modules' and turn it on.
1177 The variable can have the following values:
1179 t Create an ID if needed to make a link to the current entry.
1181 create-if-interactive
1182 If `org-store-link' is called directly (interactively, as a user
1183 command), do create an ID to support the link. But when doing the
1184 job for remember, only use the ID if it already exists. The
1185 purpose of this setting is to avoid proliferation of unwanted
1186 IDs, just because you happen to be in an Org file when you
1187 call `org-remember' that automatically and preemptively
1188 creates a link. If you do want to get an ID link in a remember
1189 template to an entry not having an ID, create it first by
1190 explicitly creating a link to it, using `C-c C-l' first.
1192 create-if-interactive-and-no-custom-id
1193 Like create-if-interactive, but do not create an ID if there is
1194 a CUSTOM_ID property defined in the entry. This is the default.
1196 use-existing
1197 Use existing ID, do not create one.
1199 nil Never use an ID to make a link, instead link using a text search for
1200 the headline text."
1201 :group 'org-link-store
1202 :type '(choice
1203 (const :tag "Create ID to make link" t)
1204 (const :tag "Create if storing link interactively"
1205 create-if-interactive)
1206 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1207 create-if-interactive-and-no-custom-id)
1208 (const :tag "Only use existing" use-existing)
1209 (const :tag "Do not use ID to create link" nil)))
1211 (defcustom org-context-in-file-links t
1212 "Non-nil means, file links from `org-store-link' contain context.
1213 A search string will be added to the file name with :: as separator and
1214 used to find the context when the link is activated by the command
1215 `org-open-at-point'.
1216 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1217 negates this setting for the duration of the command."
1218 :group 'org-link-store
1219 :type 'boolean)
1221 (defcustom org-keep-stored-link-after-insertion nil
1222 "Non-nil means, keep link in list for entire session.
1224 The command `org-store-link' adds a link pointing to the current
1225 location to an internal list. These links accumulate during a session.
1226 The command `org-insert-link' can be used to insert links into any
1227 Org-mode file (offering completion for all stored links). When this
1228 option is nil, every link which has been inserted once using \\[org-insert-link]
1229 will be removed from the list, to make completing the unused links
1230 more efficient."
1231 :group 'org-link-store
1232 :type 'boolean)
1234 (defgroup org-link-follow nil
1235 "Options concerning following links in Org-mode."
1236 :tag "Org Follow Link"
1237 :group 'org-link)
1239 (defcustom org-link-translation-function nil
1240 "Function to translate links with different syntax to Org syntax.
1241 This can be used to translate links created for example by the Planner
1242 or emacs-wiki packages to Org syntax.
1243 The function must accept two parameters, a TYPE containing the link
1244 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1245 which is everything after the link protocol. It should return a cons
1246 with possibly modified values of type and path.
1247 Org contains a function for this, so if you set this variable to
1248 `org-translate-link-from-planner', you should be able follow many
1249 links created by planner."
1250 :group 'org-link-follow
1251 :type 'function)
1253 (defcustom org-follow-link-hook nil
1254 "Hook that is run after a link has been followed."
1255 :group 'org-link-follow
1256 :type 'hook)
1258 (defcustom org-tab-follows-link nil
1259 "Non-nil means, on links TAB will follow the link.
1260 Needs to be set before org.el is loaded.
1261 This really should not be used, it does not make sense, and the
1262 implementation is bad."
1263 :group 'org-link-follow
1264 :type 'boolean)
1266 (defcustom org-return-follows-link nil
1267 "Non-nil means, on links RET will follow the link.
1268 Needs to be set before org.el is loaded."
1269 :group 'org-link-follow
1270 :type 'boolean)
1272 (defcustom org-mouse-1-follows-link
1273 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1274 "Non-nil means, mouse-1 on a link will follow the link.
1275 A longer mouse click will still set point. Does not work on XEmacs.
1276 Needs to be set before org.el is loaded."
1277 :group 'org-link-follow
1278 :type 'boolean)
1280 (defcustom org-mark-ring-length 4
1281 "Number of different positions to be recorded in the ring
1282 Changing this requires a restart of Emacs to work correctly."
1283 :group 'org-link-follow
1284 :type 'integer)
1286 (defcustom org-link-frame-setup
1287 '((vm . vm-visit-folder-other-frame)
1288 (gnus . gnus-other-frame)
1289 (file . find-file-other-window))
1290 "Setup the frame configuration for following links.
1291 When following a link with Emacs, it may often be useful to display
1292 this link in another window or frame. This variable can be used to
1293 set this up for the different types of links.
1294 For VM, use any of
1295 `vm-visit-folder'
1296 `vm-visit-folder-other-frame'
1297 For Gnus, use any of
1298 `gnus'
1299 `gnus-other-frame'
1300 `org-gnus-no-new-news'
1301 For FILE, use any of
1302 `find-file'
1303 `find-file-other-window'
1304 `find-file-other-frame'
1305 For the calendar, use the variable `calendar-setup'.
1306 For BBDB, it is currently only possible to display the matches in
1307 another window."
1308 :group 'org-link-follow
1309 :type '(list
1310 (cons (const vm)
1311 (choice
1312 (const vm-visit-folder)
1313 (const vm-visit-folder-other-window)
1314 (const vm-visit-folder-other-frame)))
1315 (cons (const gnus)
1316 (choice
1317 (const gnus)
1318 (const gnus-other-frame)
1319 (const org-gnus-no-new-news)))
1320 (cons (const file)
1321 (choice
1322 (const find-file)
1323 (const find-file-other-window)
1324 (const find-file-other-frame)))))
1326 (defcustom org-display-internal-link-with-indirect-buffer nil
1327 "Non-nil means, use indirect buffer to display infile links.
1328 Activating internal links (from one location in a file to another location
1329 in the same file) normally just jumps to the location. When the link is
1330 activated with a C-u prefix (or with mouse-3), the link is displayed in
1331 another window. When this option is set, the other window actually displays
1332 an indirect buffer clone of the current buffer, to avoid any visibility
1333 changes to the current buffer."
1334 :group 'org-link-follow
1335 :type 'boolean)
1337 (defcustom org-open-non-existing-files nil
1338 "Non-nil means, `org-open-file' will open non-existing files.
1339 When nil, an error will be generated.
1340 This variable applies only to external applications because they
1341 might choke on non-existing files. If the link is to a file that
1342 will be opened in Emacs, the variable is ignored."
1343 :group 'org-link-follow
1344 :type 'boolean)
1346 (defcustom org-open-directory-means-index-dot-org nil
1347 "Non-nil means, a link to a directory really means to index.org.
1348 When nil, following a directory link will run dired or open a finder/explorer
1349 window on that directory."
1350 :group 'org-link-follow
1351 :type 'boolean)
1353 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1354 "Function and arguments to call for following mailto links.
1355 This is a list with the first element being a lisp function, and the
1356 remaining elements being arguments to the function. In string arguments,
1357 %a will be replaced by the address, and %s will be replaced by the subject
1358 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1359 :group 'org-link-follow
1360 :type '(choice
1361 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1362 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1363 (const :tag "message-mail" (message-mail "%a" "%s"))
1364 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1366 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1367 "Non-nil means, ask for confirmation before executing shell links.
1368 Shell links can be dangerous: just think about a link
1370 [[shell:rm -rf ~/*][Google Search]]
1372 This link would show up in your Org-mode document as \"Google Search\",
1373 but really it would remove your entire home directory.
1374 Therefore we advise against setting this variable to nil.
1375 Just change it to `y-or-n-p' if you want to confirm with a
1376 single keystroke rather than having to type \"yes\"."
1377 :group 'org-link-follow
1378 :type '(choice
1379 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1380 (const :tag "with y-or-n (faster)" y-or-n-p)
1381 (const :tag "no confirmation (dangerous)" nil)))
1383 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1384 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1385 Elisp links can be dangerous: just think about a link
1387 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1389 This link would show up in your Org-mode document as \"Google Search\",
1390 but really it would remove your entire home directory.
1391 Therefore we advise against setting this variable to nil.
1392 Just change it to `y-or-n-p' if you want to confirm with a
1393 single keystroke rather than having to type \"yes\"."
1394 :group 'org-link-follow
1395 :type '(choice
1396 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1397 (const :tag "with y-or-n (faster)" y-or-n-p)
1398 (const :tag "no confirmation (dangerous)" nil)))
1400 (defconst org-file-apps-defaults-gnu
1401 '((remote . emacs)
1402 (system . mailcap)
1403 (t . mailcap))
1404 "Default file applications on a UNIX or GNU/Linux system.
1405 See `org-file-apps'.")
1407 (defconst org-file-apps-defaults-macosx
1408 '((remote . emacs)
1409 (t . "open %s")
1410 (system . "open %s")
1411 ("ps.gz" . "gv %s")
1412 ("eps.gz" . "gv %s")
1413 ("dvi" . "xdvi %s")
1414 ("fig" . "xfig %s"))
1415 "Default file applications on a MacOS X system.
1416 The system \"open\" is known as a default, but we use X11 applications
1417 for some files for which the OS does not have a good default.
1418 See `org-file-apps'.")
1420 (defconst org-file-apps-defaults-windowsnt
1421 (list
1422 '(remote . emacs)
1423 (cons t
1424 (list (if (featurep 'xemacs)
1425 'mswindows-shell-execute
1426 'w32-shell-execute)
1427 "open" 'file))
1428 (cons 'system
1429 (list (if (featurep 'xemacs)
1430 'mswindows-shell-execute
1431 'w32-shell-execute)
1432 "open" 'file)))
1433 "Default file applications on a Windows NT system.
1434 The system \"open\" is used for most files.
1435 See `org-file-apps'.")
1437 (defcustom org-file-apps
1439 (auto-mode . emacs)
1440 ("\\.mm\\'" . default)
1441 ("\\.x?html?\\'" . default)
1442 ("\\.pdf\\'" . default)
1444 "External applications for opening `file:path' items in a document.
1445 Org-mode uses system defaults for different file types, but
1446 you can use this variable to set the application for a given file
1447 extension. The entries in this list are cons cells where the car identifies
1448 files and the cdr the corresponding command. Possible values for the
1449 file identifier are
1450 \"regex\" Regular expression matched against the file name. For backward
1451 compatibility, this can also be a string with only alphanumeric
1452 characters, which is then interpreted as an extension.
1453 `directory' Matches a directory
1454 `remote' Matches a remote file, accessible through tramp or efs.
1455 Remote files most likely should be visited through Emacs
1456 because external applications cannot handle such paths.
1457 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1458 so all files Emacs knows how to handle. Using this with
1459 command `emacs' will open most files in Emacs. Beware that this
1460 will also open html files inside Emacs, unless you add
1461 (\"html\" . default) to the list as well.
1462 t Default for files not matched by any of the other options.
1463 `system' The system command to open files, like `open' on Windows
1464 and Mac OS X, and mailcap under GNU/Linux. This is the command
1465 that will be selected if you call `C-c C-o' with a double
1466 `C-u C-u' prefix.
1468 Possible values for the command are:
1469 `emacs' The file will be visited by the current Emacs process.
1470 `default' Use the default application for this file type, which is the
1471 association for t in the list, most likely in the system-specific
1472 part.
1473 This can be used to overrule an unwanted setting in the
1474 system-specific variable.
1475 `system' Use the system command for opening files, like \"open\".
1476 This command is specified by the entry whose car is `system'.
1477 Most likely, the system-specific version of this variable
1478 does define this command, but you can overrule/replace it
1479 here.
1480 string A command to be executed by a shell; %s will be replaced
1481 by the path to the file.
1482 sexp A Lisp form which will be evaluated. The file path will
1483 be available in the Lisp variable `file'.
1484 For more examples, see the system specific constants
1485 `org-file-apps-defaults-macosx'
1486 `org-file-apps-defaults-windowsnt'
1487 `org-file-apps-defaults-gnu'."
1488 :group 'org-link-follow
1489 :type '(repeat
1490 (cons (choice :value ""
1491 (string :tag "Extension")
1492 (const :tag "System command to open files" system)
1493 (const :tag "Default for unrecognized files" t)
1494 (const :tag "Remote file" remote)
1495 (const :tag "Links to a directory" directory)
1496 (const :tag "Any files that have Emacs modes"
1497 auto-mode))
1498 (choice :value ""
1499 (const :tag "Visit with Emacs" emacs)
1500 (const :tag "Use default" default)
1501 (const :tag "Use the system command" system)
1502 (string :tag "Command")
1503 (sexp :tag "Lisp form")))))
1505 (defgroup org-refile nil
1506 "Options concerning refiling entries in Org-mode."
1507 :tag "Org Refile"
1508 :group 'org)
1510 (defcustom org-directory "~/org"
1511 "Directory with org files.
1512 This is just a default location to look for Org files. There is no need
1513 at all to put your files into this directory. It is only used in the
1514 following situations:
1516 1. When a remember template specifies a target file that is not an
1517 absolute path. The path will then be interpreted relative to
1518 `org-directory'
1519 2. When a remember note is filed away in an interactive way (when exiting the
1520 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1521 with `org-directory' as the default path."
1522 :group 'org-refile
1523 :group 'org-remember
1524 :type 'directory)
1526 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1527 "Default target for storing notes.
1528 Used by the hooks for remember.el. This can be a string, or nil to mean
1529 the value of `remember-data-file'.
1530 You can set this on a per-template basis with the variable
1531 `org-remember-templates'."
1532 :group 'org-refile
1533 :group 'org-remember
1534 :type '(choice
1535 (const :tag "Default from remember-data-file" nil)
1536 file))
1538 (defcustom org-goto-interface 'outline
1539 "The default interface to be used for `org-goto'.
1540 Allowed values are:
1541 outline The interface shows an outline of the relevant file
1542 and the correct heading is found by moving through
1543 the outline or by searching with incremental search.
1544 outline-path-completion Headlines in the current buffer are offered via
1545 completion. This is the interface also used by
1546 the refile command."
1547 :group 'org-refile
1548 :type '(choice
1549 (const :tag "Outline" outline)
1550 (const :tag "Outline-path-completion" outline-path-completion)))
1552 (defcustom org-goto-max-level 5
1553 "Maximum level to be considered when running org-goto with refile interface."
1554 :group 'org-refile
1555 :type 'integer)
1557 (defcustom org-reverse-note-order nil
1558 "Non-nil means, store new notes at the beginning of a file or entry.
1559 When nil, new notes will be filed to the end of a file or entry.
1560 This can also be a list with cons cells of regular expressions that
1561 are matched against file names, and values."
1562 :group 'org-remember
1563 :group 'org-refile
1564 :type '(choice
1565 (const :tag "Reverse always" t)
1566 (const :tag "Reverse never" nil)
1567 (repeat :tag "By file name regexp"
1568 (cons regexp boolean))))
1570 (defcustom org-refile-targets nil
1571 "Targets for refiling entries with \\[org-refile].
1572 This is list of cons cells. Each cell contains:
1573 - a specification of the files to be considered, either a list of files,
1574 or a symbol whose function or variable value will be used to retrieve
1575 a file name or a list of file names. If you use `org-agenda-files' for
1576 that, all agenda files will be scanned for targets. Nil means, consider
1577 headings in the current buffer.
1578 - A specification of how to find candidate refile targets. This may be
1579 any of:
1580 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1581 This tag has to be present in all target headlines, inheritance will
1582 not be considered.
1583 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1584 todo keyword.
1585 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1586 headlines that are refiling targets.
1587 - a cons cell (:level . N). Any headline of level N is considered a target.
1588 Note that, when `org-odd-levels-only' is set, level corresponds to
1589 order in hierarchy, not to the number of stars.
1590 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1591 Note that, when `org-odd-levels-only' is set, level corresponds to
1592 order in hierarchy, not to the number of stars.
1594 You can set the variable `org-refile-target-verify-function' to a function
1595 to verify each headline found by the simple critery above.
1597 When this variable is nil, all top-level headlines in the current buffer
1598 are used, equivalent to the value `((nil . (:level . 1))'."
1599 :group 'org-refile
1600 :type '(repeat
1601 (cons
1602 (choice :value org-agenda-files
1603 (const :tag "All agenda files" org-agenda-files)
1604 (const :tag "Current buffer" nil)
1605 (function) (variable) (file))
1606 (choice :tag "Identify target headline by"
1607 (cons :tag "Specific tag" (const :value :tag) (string))
1608 (cons :tag "TODO keyword" (const :value :todo) (string))
1609 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1610 (cons :tag "Level number" (const :value :level) (integer))
1611 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1613 (defcustom org-refile-target-verify-function nil
1614 "Function to verify if the headline at point should be a refile target.
1615 The function will be called without arguments, with point at the
1616 beginning of the headline. It should return t and leave point
1617 where it is if the headline is a valid target for refiling.
1619 If the target should not be selected, the function must return nil.
1620 In addition to this, it may move point to a place from where the search
1621 should be continued. For example, the function may decide that the entire
1622 subtree of the current entry should be excluded and move point to the end
1623 of the subtree."
1624 :group 'org-refile
1625 :type 'function)
1627 (defcustom org-refile-use-outline-path nil
1628 "Non-nil means, provide refile targets as paths.
1629 So a level 3 headline will be available as level1/level2/level3.
1631 When the value is `file', also include the file name (without directory)
1632 into the path. In this case, you can also stop the completion after
1633 the file name, to get entries inserted as top level in the file.
1635 When `full-file-path', include the full file path."
1636 :group 'org-refile
1637 :type '(choice
1638 (const :tag "Not" nil)
1639 (const :tag "Yes" t)
1640 (const :tag "Start with file name" file)
1641 (const :tag "Start with full file path" full-file-path)))
1643 (defcustom org-outline-path-complete-in-steps t
1644 "Non-nil means, complete the outline path in hierarchical steps.
1645 When Org-mode uses the refile interface to select an outline path
1646 \(see variable `org-refile-use-outline-path'), the completion of
1647 the path can be done is a single go, or if can be done in steps down
1648 the headline hierarchy. Going in steps is probably the best if you
1649 do not use a special completion package like `ido' or `icicles'.
1650 However, when using these packages, going in one step can be very
1651 fast, while still showing the whole path to the entry."
1652 :group 'org-refile
1653 :type 'boolean)
1655 (defcustom org-refile-allow-creating-parent-nodes nil
1656 "Non-nil means, allow to create new nodes as refile targets.
1657 New nodes are then created by adding \"/new node name\" to the completion
1658 of an existing node. When the value of this variable is `confirm',
1659 new node creation must be confirmed by the user (recommended)
1660 When nil, the completion must match an existing entry.
1662 Note that, if the new heading is not seen by the criteria
1663 listed in `org-refile-targets', multiple instances of the same
1664 heading would be created by trying again to file under the new
1665 heading."
1666 :group 'org-refile
1667 :type '(choice
1668 (const :tag "Never" nil)
1669 (const :tag "Always" t)
1670 (const :tag "Prompt for confirmation" confirm)))
1672 (defgroup org-todo nil
1673 "Options concerning TODO items in Org-mode."
1674 :tag "Org TODO"
1675 :group 'org)
1677 (defgroup org-progress nil
1678 "Options concerning Progress logging in Org-mode."
1679 :tag "Org Progress"
1680 :group 'org-time)
1682 (defvar org-todo-interpretation-widgets
1684 (:tag "Sequence (cycling hits every state)" sequence)
1685 (:tag "Type (cycling directly to DONE)" type))
1686 "The available interpretation symbols for customizing
1687 `org-todo-keywords'.
1688 Interested libraries should add to this list.")
1690 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1691 "List of TODO entry keyword sequences and their interpretation.
1692 \\<org-mode-map>This is a list of sequences.
1694 Each sequence starts with a symbol, either `sequence' or `type',
1695 indicating if the keywords should be interpreted as a sequence of
1696 action steps, or as different types of TODO items. The first
1697 keywords are states requiring action - these states will select a headline
1698 for inclusion into the global TODO list Org-mode produces. If one of
1699 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1700 signify that no further action is necessary. If \"|\" is not found,
1701 the last keyword is treated as the only DONE state of the sequence.
1703 The command \\[org-todo] cycles an entry through these states, and one
1704 additional state where no keyword is present. For details about this
1705 cycling, see the manual.
1707 TODO keywords and interpretation can also be set on a per-file basis with
1708 the special #+SEQ_TODO and #+TYP_TODO lines.
1710 Each keyword can optionally specify a character for fast state selection
1711 \(in combination with the variable `org-use-fast-todo-selection')
1712 and specifiers for state change logging, using the same syntax
1713 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1714 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1715 indicates to record a time stamp each time this state is selected.
1717 Each keyword may also specify if a timestamp or a note should be
1718 recorded when entering or leaving the state, by adding additional
1719 characters in the parenthesis after the keyword. This looks like this:
1720 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1721 record only the time of the state change. With X and Y being either
1722 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1723 Y when leaving the state if and only if the *target* state does not
1724 define X. You may omit any of the fast-selection key or X or /Y,
1725 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1727 For backward compatibility, this variable may also be just a list
1728 of keywords - in this case the interpretation (sequence or type) will be
1729 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1730 :group 'org-todo
1731 :group 'org-keywords
1732 :type '(choice
1733 (repeat :tag "Old syntax, just keywords"
1734 (string :tag "Keyword"))
1735 (repeat :tag "New syntax"
1736 (cons
1737 (choice
1738 :tag "Interpretation"
1739 ;;Quick and dirty way to see
1740 ;;`org-todo-interpretations'. This takes the
1741 ;;place of item arguments
1742 :convert-widget
1743 (lambda (widget)
1744 (widget-put widget
1745 :args (mapcar
1746 #'(lambda (x)
1747 (widget-convert
1748 (cons 'const x)))
1749 org-todo-interpretation-widgets))
1750 widget))
1751 (repeat
1752 (string :tag "Keyword"))))))
1754 (defvar org-todo-keywords-1 nil
1755 "All TODO and DONE keywords active in a buffer.")
1756 (make-variable-buffer-local 'org-todo-keywords-1)
1757 (defvar org-todo-keywords-for-agenda nil)
1758 (defvar org-done-keywords-for-agenda nil)
1759 (defvar org-drawers-for-agenda nil)
1760 (defvar org-todo-keyword-alist-for-agenda nil)
1761 (defvar org-tag-alist-for-agenda nil)
1762 (defvar org-agenda-contributing-files nil)
1763 (defvar org-not-done-keywords nil)
1764 (make-variable-buffer-local 'org-not-done-keywords)
1765 (defvar org-done-keywords nil)
1766 (make-variable-buffer-local 'org-done-keywords)
1767 (defvar org-todo-heads nil)
1768 (make-variable-buffer-local 'org-todo-heads)
1769 (defvar org-todo-sets nil)
1770 (make-variable-buffer-local 'org-todo-sets)
1771 (defvar org-todo-log-states nil)
1772 (make-variable-buffer-local 'org-todo-log-states)
1773 (defvar org-todo-kwd-alist nil)
1774 (make-variable-buffer-local 'org-todo-kwd-alist)
1775 (defvar org-todo-key-alist nil)
1776 (make-variable-buffer-local 'org-todo-key-alist)
1777 (defvar org-todo-key-trigger nil)
1778 (make-variable-buffer-local 'org-todo-key-trigger)
1780 (defcustom org-todo-interpretation 'sequence
1781 "Controls how TODO keywords are interpreted.
1782 This variable is in principle obsolete and is only used for
1783 backward compatibility, if the interpretation of todo keywords is
1784 not given already in `org-todo-keywords'. See that variable for
1785 more information."
1786 :group 'org-todo
1787 :group 'org-keywords
1788 :type '(choice (const sequence)
1789 (const type)))
1791 (defcustom org-use-fast-todo-selection t
1792 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1793 This variable describes if and under what circumstances the cycling
1794 mechanism for TODO keywords will be replaced by a single-key, direct
1795 selection scheme.
1797 When nil, fast selection is never used.
1799 When the symbol `prefix', it will be used when `org-todo' is called with
1800 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1801 in an agenda buffer.
1803 When t, fast selection is used by default. In this case, the prefix
1804 argument forces cycling instead.
1806 In all cases, the special interface is only used if access keys have actually
1807 been assigned by the user, i.e. if keywords in the configuration are followed
1808 by a letter in parenthesis, like TODO(t)."
1809 :group 'org-todo
1810 :type '(choice
1811 (const :tag "Never" nil)
1812 (const :tag "By default" t)
1813 (const :tag "Only with C-u C-c C-t" prefix)))
1815 (defcustom org-provide-todo-statistics t
1816 "Non-nil means, update todo statistics after insert and toggle.
1817 ALL-HEADLINES means update todo statistics by including headlines
1818 with no TODO keyword as well, counting them as not done.
1819 A list of TODO keywords means the same, but skip keywords that are
1820 not in this list.
1822 When this is set, todo statistics is updated in the parent of the
1823 current entry each time a todo state is changed."
1824 :group 'org-todo
1825 :type '(choice
1826 (const :tag "Yes, only for TODO entries" t)
1827 (const :tag "Yes, including all entries" 'all-headlines)
1828 (repeat :tag "Yes, for TODOs in this list"
1829 (string :tag "TODO keyword"))
1830 (other :tag "No TODO statistics" nil)))
1832 (defcustom org-hierarchical-todo-statistics t
1833 "Non-nil means, TODO statistics covers just direct children.
1834 When nil, all entries in the subtree are considered.
1835 This has only an effect if `org-provide-todo-statistics' is set.
1836 To set this to nil for only a single subtree, use a COOKIE_DATA
1837 property and include the word \"recursive\" into the value."
1838 :group 'org-todo
1839 :type 'boolean)
1841 (defcustom org-after-todo-state-change-hook nil
1842 "Hook which is run after the state of a TODO item was changed.
1843 The new state (a string with a TODO keyword, or nil) is available in the
1844 Lisp variable `state'."
1845 :group 'org-todo
1846 :type 'hook)
1848 (defvar org-blocker-hook nil
1849 "Hook for functions that are allowed to block a state change.
1851 Each function gets as its single argument a property list, see
1852 `org-trigger-hook' for more information about this list.
1854 If any of the functions in this hook returns nil, the state change
1855 is blocked.")
1857 (defvar org-trigger-hook nil
1858 "Hook for functions that are triggered by a state change.
1860 Each function gets as its single argument a property list with at least
1861 the following elements:
1863 (:type type-of-change :position pos-at-entry-start
1864 :from old-state :to new-state)
1866 Depending on the type, more properties may be present.
1868 This mechanism is currently implemented for:
1870 TODO state changes
1871 ------------------
1872 :type todo-state-change
1873 :from previous state (keyword as a string), or nil, or a symbol
1874 'todo' or 'done', to indicate the general type of state.
1875 :to new state, like in :from")
1877 (defcustom org-enforce-todo-dependencies nil
1878 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1879 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1880 be blocked if any prior sibling is not yet done.
1881 Finally, if the parent is blocked because of ordered siblings of its own,
1882 the child will also be blocked.
1883 This variable needs to be set before org.el is loaded, and you need to
1884 restart Emacs after a change to make the change effective. The only way
1885 to change is while Emacs is running is through the customize interface."
1886 :set (lambda (var val)
1887 (set var val)
1888 (if val
1889 (add-hook 'org-blocker-hook
1890 'org-block-todo-from-children-or-siblings-or-parent)
1891 (remove-hook 'org-blocker-hook
1892 'org-block-todo-from-children-or-siblings-or-parent)))
1893 :group 'org-todo
1894 :type 'boolean)
1896 (defcustom org-enforce-todo-checkbox-dependencies nil
1897 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1898 When this is nil, checkboxes have no influence on switching TODO states.
1899 When non-nil, you first need to check off all check boxes before the TODO
1900 entry can be switched to DONE.
1901 This variable needs to be set before org.el is loaded, and you need to
1902 restart Emacs after a change to make the change effective. The only way
1903 to change is while Emacs is running is through the customize interface."
1904 :set (lambda (var val)
1905 (set var val)
1906 (if val
1907 (add-hook 'org-blocker-hook
1908 'org-block-todo-from-checkboxes)
1909 (remove-hook 'org-blocker-hook
1910 'org-block-todo-from-checkboxes)))
1911 :group 'org-todo
1912 :type 'boolean)
1914 (defcustom org-treat-insert-todo-heading-as-state-change nil
1915 "Non-nil means, inserting a TODO heading is treated as state change.
1916 So when the command \\[org-insert-todo-heading] is used, state change
1917 logging will apply if appropriate. When nil, the new TODO item will
1918 be inserted directly, and no logging will take place."
1919 :group 'org-todo
1920 :type 'boolean)
1922 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1923 "Non-nil means, switching TODO states with S-cursor counts as state change.
1924 This is the default behavior. However, setting this to nil allows a
1925 convenient way to select a TODO state and bypass any logging associated
1926 with that."
1927 :group 'org-todo
1928 :type 'boolean)
1930 (defcustom org-todo-state-tags-triggers nil
1931 "Tag changes that should be triggered by TODO state changes.
1932 This is a list. Each entry is
1934 (state-change (tag . flag) .......)
1936 State-change can be a string with a state, and empty string to indicate the
1937 state that has no TODO keyword, or it can be one of the symbols `todo'
1938 or `done', meaning any not-done or done state, respectively."
1939 :group 'org-todo
1940 :group 'org-tags
1941 :type '(repeat
1942 (cons (choice :tag "When changing to"
1943 (const :tag "Not-done state" todo)
1944 (const :tag "Done state" done)
1945 (string :tag "State"))
1946 (repeat
1947 (cons :tag "Tag action"
1948 (string :tag "Tag")
1949 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1951 (defcustom org-log-done nil
1952 "Information to record when a task moves to the DONE state.
1954 Possible values are:
1956 nil Don't add anything, just change the keyword
1957 time Add a time stamp to the task
1958 note Prompt for a note and add it with template `org-log-note-headings'
1960 This option can also be set with on a per-file-basis with
1962 #+STARTUP: nologdone
1963 #+STARTUP: logdone
1964 #+STARTUP: lognotedone
1966 You can have local logging settings for a subtree by setting the LOGGING
1967 property to one or more of these keywords."
1968 :group 'org-todo
1969 :group 'org-progress
1970 :type '(choice
1971 (const :tag "No logging" nil)
1972 (const :tag "Record CLOSED timestamp" time)
1973 (const :tag "Record CLOSED timestamp with note." note)))
1975 ;; Normalize old uses of org-log-done.
1976 (cond
1977 ((eq org-log-done t) (setq org-log-done 'time))
1978 ((and (listp org-log-done) (memq 'done org-log-done))
1979 (setq org-log-done 'note)))
1981 (defcustom org-log-reschedule nil
1982 "Information to record when the scheduling date of a tasks is modified.
1984 Possible values are:
1986 nil Don't add anything, just change the date
1987 time Add a time stamp to the task
1988 note Prompt for a note and add it with template `org-log-note-headings'
1990 This option can also be set with on a per-file-basis with
1992 #+STARTUP: nologreschedule
1993 #+STARTUP: logreschedule
1994 #+STARTUP: lognotereschedule"
1995 :group 'org-todo
1996 :group 'org-progress
1997 :type '(choice
1998 (const :tag "No logging" nil)
1999 (const :tag "Record timestamp" time)
2000 (const :tag "Record timestamp with note." note)))
2002 (defcustom org-log-redeadline nil
2003 "Information to record when the deadline date of a tasks is modified.
2005 Possible values are:
2007 nil Don't add anything, just change the date
2008 time Add a time stamp to the task
2009 note Prompt for a note and add it with template `org-log-note-headings'
2011 This option can also be set with on a per-file-basis with
2013 #+STARTUP: nologredeadline
2014 #+STARTUP: logredeadline
2015 #+STARTUP: lognoteredeadline
2017 You can have local logging settings for a subtree by setting the LOGGING
2018 property to one or more of these keywords."
2019 :group 'org-todo
2020 :group 'org-progress
2021 :type '(choice
2022 (const :tag "No logging" nil)
2023 (const :tag "Record timestamp" time)
2024 (const :tag "Record timestamp with note." note)))
2026 (defcustom org-log-note-clock-out nil
2027 "Non-nil means, record a note when clocking out of an item.
2028 This can also be configured on a per-file basis by adding one of
2029 the following lines anywhere in the buffer:
2031 #+STARTUP: lognoteclock-out
2032 #+STARTUP: nolognoteclock-out"
2033 :group 'org-todo
2034 :group 'org-progress
2035 :type 'boolean)
2037 (defcustom org-log-done-with-time t
2038 "Non-nil means, the CLOSED time stamp will contain date and time.
2039 When nil, only the date will be recorded."
2040 :group 'org-progress
2041 :type 'boolean)
2043 (defcustom org-log-note-headings
2044 '((done . "CLOSING NOTE %t")
2045 (state . "State %-12s from %-12S %t")
2046 (note . "Note taken on %t")
2047 (reschedule . "Rescheduled from %S on %t")
2048 (redeadline . "New deadline from %S on %t")
2049 (clock-out . ""))
2050 "Headings for notes added to entries.
2051 The value is an alist, with the car being a symbol indicating the note
2052 context, and the cdr is the heading to be used. The heading may also be the
2053 empty string.
2054 %t in the heading will be replaced by a time stamp.
2055 %s will be replaced by the new TODO state, in double quotes.
2056 %S will be replaced by the old TODO state, in double quotes.
2057 %u will be replaced by the user name.
2058 %U will be replaced by the full user name."
2059 :group 'org-todo
2060 :group 'org-progress
2061 :type '(list :greedy t
2062 (cons (const :tag "Heading when closing an item" done) string)
2063 (cons (const :tag
2064 "Heading when changing todo state (todo sequence only)"
2065 state) string)
2066 (cons (const :tag "Heading when just taking a note" note) string)
2067 (cons (const :tag "Heading when clocking out" clock-out) string)
2068 (cons (const :tag "Heading when rescheduling" reschedule) string)
2069 (cons (const :tag "Heading when changing deadline" redeadline) string)))
2071 (unless (assq 'note org-log-note-headings)
2072 (push '(note . "%t") org-log-note-headings))
2074 (defcustom org-log-into-drawer nil
2075 "Non-nil means, insert state change notes and time stamps into a drawer.
2076 When nil, state changes notes will be inserted after the headline and
2077 any scheduling and clock lines, but not inside a drawer.
2079 The value of this variable should be the name of the drawer to use.
2080 LOGBOOK is proposed at the default drawer for this purpose, you can
2081 also set this to a string to define the drawer of your choice.
2083 A value of t is also allowed, representing \"LOGBOOK\".
2085 If this variable is set, `org-log-state-notes-insert-after-drawers'
2086 will be ignored.
2088 You can set the property LOG_INTO_DRAWER to overrule this setting for
2089 a subtree."
2090 :group 'org-todo
2091 :group 'org-progress
2092 :type '(choice
2093 (const :tag "Not into a drawer" nil)
2094 (const :tag "LOGBOOK" t)
2095 (string :tag "Other")))
2097 (if (fboundp 'defvaralias)
2098 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2100 (defun org-log-into-drawer ()
2101 "Return the value of `org-log-into-drawer', but let properties overrule.
2102 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2103 used instead of the default value."
2104 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2105 (cond
2106 ((or (not p) (equal p "nil")) org-log-into-drawer)
2107 ((equal p "t") "LOGBOOK")
2108 (t p))))
2110 (defcustom org-log-state-notes-insert-after-drawers nil
2111 "Non-nil means, insert state change notes after any drawers in entry.
2112 Only the drawers that *immediately* follow the headline and the
2113 deadline/scheduled line are skipped.
2114 When nil, insert notes right after the heading and perhaps the line
2115 with deadline/scheduling if present.
2117 This variable will have no effect if `org-log-into-drawer' is
2118 set."
2119 :group 'org-todo
2120 :group 'org-progress
2121 :type 'boolean)
2123 (defcustom org-log-states-order-reversed t
2124 "Non-nil means, the latest state change note will be directly after heading.
2125 When nil, the notes will be orderer according to time."
2126 :group 'org-todo
2127 :group 'org-progress
2128 :type 'boolean)
2130 (defcustom org-log-repeat 'time
2131 "Non-nil means, record moving through the DONE state when triggering repeat.
2132 An auto-repeating task is immediately switched back to TODO when
2133 marked DONE. If you are not logging state changes (by adding \"@\"
2134 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2135 record a closing note, there will be no record of the task moving
2136 through DONE. This variable forces taking a note anyway.
2138 nil Don't force a record
2139 time Record a time stamp
2140 note Record a note
2142 This option can also be set with on a per-file-basis with
2144 #+STARTUP: logrepeat
2145 #+STARTUP: lognoterepeat
2146 #+STARTUP: nologrepeat
2148 You can have local logging settings for a subtree by setting the LOGGING
2149 property to one or more of these keywords."
2150 :group 'org-todo
2151 :group 'org-progress
2152 :type '(choice
2153 (const :tag "Don't force a record" nil)
2154 (const :tag "Force recording the DONE state" time)
2155 (const :tag "Force recording a note with the DONE state" note)))
2158 (defgroup org-priorities nil
2159 "Priorities in Org-mode."
2160 :tag "Org Priorities"
2161 :group 'org-todo)
2163 (defcustom org-enable-priority-commands t
2164 "Non-nil means, priority commands are active.
2165 When nil, these commands will be disabled, so that you never accidentally
2166 set a priority."
2167 :group 'org-priorities
2168 :type 'boolean)
2170 (defcustom org-highest-priority ?A
2171 "The highest priority of TODO items. A character like ?A, ?B etc.
2172 Must have a smaller ASCII number than `org-lowest-priority'."
2173 :group 'org-priorities
2174 :type 'character)
2176 (defcustom org-lowest-priority ?C
2177 "The lowest priority of TODO items. A character like ?A, ?B etc.
2178 Must have a larger ASCII number than `org-highest-priority'."
2179 :group 'org-priorities
2180 :type 'character)
2182 (defcustom org-default-priority ?B
2183 "The default priority of TODO items.
2184 This is the priority an item get if no explicit priority is given."
2185 :group 'org-priorities
2186 :type 'character)
2188 (defcustom org-priority-start-cycle-with-default t
2189 "Non-nil means, start with default priority when starting to cycle.
2190 When this is nil, the first step in the cycle will be (depending on the
2191 command used) one higher or lower that the default priority."
2192 :group 'org-priorities
2193 :type 'boolean)
2195 (defgroup org-time nil
2196 "Options concerning time stamps and deadlines in Org-mode."
2197 :tag "Org Time"
2198 :group 'org)
2200 (defcustom org-insert-labeled-timestamps-at-point nil
2201 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2202 When nil, these labeled time stamps are forces into the second line of an
2203 entry, just after the headline. When scheduling from the global TODO list,
2204 the time stamp will always be forced into the second line."
2205 :group 'org-time
2206 :type 'boolean)
2208 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2209 "Formats for `format-time-string' which are used for time stamps.
2210 It is not recommended to change this constant.")
2212 (defcustom org-time-stamp-rounding-minutes '(0 5)
2213 "Number of minutes to round time stamps to.
2214 These are two values, the first applies when first creating a time stamp.
2215 The second applies when changing it with the commands `S-up' and `S-down'.
2216 When changing the time stamp, this means that it will change in steps
2217 of N minutes, as given by the second value.
2219 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2220 numbers should be factors of 60, so for example 5, 10, 15.
2222 When this is larger than 1, you can still force an exact time-stamp by using
2223 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2224 and by using a prefix arg to `S-up/down' to specify the exact number
2225 of minutes to shift."
2226 :group 'org-time
2227 :get '(lambda (var) ; Make sure all entries have 5 elements
2228 (if (integerp (default-value var))
2229 (list (default-value var) 5)
2230 (default-value var)))
2231 :type '(list
2232 (integer :tag "when inserting times")
2233 (integer :tag "when modifying times")))
2235 ;; Normalize old customizations of this variable.
2236 (when (integerp org-time-stamp-rounding-minutes)
2237 (setq org-time-stamp-rounding-minutes
2238 (list org-time-stamp-rounding-minutes
2239 org-time-stamp-rounding-minutes)))
2241 (defcustom org-display-custom-times nil
2242 "Non-nil means, overlay custom formats over all time stamps.
2243 The formats are defined through the variable `org-time-stamp-custom-formats'.
2244 To turn this on on a per-file basis, insert anywhere in the file:
2245 #+STARTUP: customtime"
2246 :group 'org-time
2247 :set 'set-default
2248 :type 'sexp)
2249 (make-variable-buffer-local 'org-display-custom-times)
2251 (defcustom org-time-stamp-custom-formats
2252 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2253 "Custom formats for time stamps. See `format-time-string' for the syntax.
2254 These are overlayed over the default ISO format if the variable
2255 `org-display-custom-times' is set. Time like %H:%M should be at the
2256 end of the second format. The custom formats are also honored by export
2257 commands, if custom time display is turned on at the time of export."
2258 :group 'org-time
2259 :type 'sexp)
2261 (defun org-time-stamp-format (&optional long inactive)
2262 "Get the right format for a time string."
2263 (let ((f (if long (cdr org-time-stamp-formats)
2264 (car org-time-stamp-formats))))
2265 (if inactive
2266 (concat "[" (substring f 1 -1) "]")
2267 f)))
2269 (defcustom org-time-clocksum-format "%d:%02d"
2270 "The format string used when creating CLOCKSUM lines, or when
2271 org-mode generates a time duration."
2272 :group 'org-time
2273 :type 'string)
2275 (defcustom org-time-clocksum-use-fractional nil
2276 "If non-nil, \\[org-clock-display] uses fractional times.
2277 org-mode generates a time duration."
2278 :group 'org-time
2279 :type 'boolean)
2281 (defcustom org-time-clocksum-fractional-format "%.2f"
2282 "The format string used when creating CLOCKSUM lines, or when
2283 org-mode generates a time duration."
2284 :group 'org-time
2285 :type 'string)
2287 (defcustom org-deadline-warning-days 14
2288 "No. of days before expiration during which a deadline becomes active.
2289 This variable governs the display in sparse trees and in the agenda.
2290 When 0 or negative, it means use this number (the absolute value of it)
2291 even if a deadline has a different individual lead time specified.
2293 Custom commands can set this variable in the options section."
2294 :group 'org-time
2295 :group 'org-agenda-daily/weekly
2296 :type 'integer)
2298 (defcustom org-read-date-prefer-future t
2299 "Non-nil means, assume future for incomplete date input from user.
2300 This affects the following situations:
2301 1. The user gives a month but not a year.
2302 For example, if it is april and you enter \"feb 2\", this will be read
2303 as feb 2, *next* year. \"May 5\", however, will be this year.
2304 2. The user gives a day, but no month.
2305 For example, if today is the 15th, and you enter \"3\", Org-mode will
2306 read this as the third of *next* month. However, if you enter \"17\",
2307 it will be considered as *this* month.
2309 If you set this variable to the symbol `time', then also the following
2310 will work:
2312 3. If the user gives a time, but no day. If the time is before now,
2313 to will be interpreted as tomorrow.
2315 Currently none of this works for ISO week specifications.
2317 When this option is nil, the current day, month and year will always be
2318 used as defaults."
2319 :group 'org-time
2320 :type '(choice
2321 (const :tag "Never" nil)
2322 (const :tag "Check month and day" t)
2323 (const :tag "Check month, day, and time" time)))
2325 (defcustom org-read-date-display-live t
2326 "Non-nil means, display current interpretation of date prompt live.
2327 This display will be in an overlay, in the minibuffer."
2328 :group 'org-time
2329 :type 'boolean)
2331 (defcustom org-read-date-popup-calendar t
2332 "Non-nil means, pop up a calendar when prompting for a date.
2333 In the calendar, the date can be selected with mouse-1. However, the
2334 minibuffer will also be active, and you can simply enter the date as well.
2335 When nil, only the minibuffer will be available."
2336 :group 'org-time
2337 :type 'boolean)
2338 (if (fboundp 'defvaralias)
2339 (defvaralias 'org-popup-calendar-for-date-prompt
2340 'org-read-date-popup-calendar))
2342 (defcustom org-read-date-minibuffer-setup-hook nil
2343 "Hook to be used to set up keys for the date/time interface.
2344 Add key definitions to `minibuffer-local-map', which will be a temporary
2345 copy."
2346 :group 'org-time
2347 :type 'hook)
2349 (defcustom org-extend-today-until 0
2350 "The hour when your day really ends. Must be an integer.
2351 This has influence for the following applications:
2352 - When switching the agenda to \"today\". It it is still earlier than
2353 the time given here, the day recognized as TODAY is actually yesterday.
2354 - When a date is read from the user and it is still before the time given
2355 here, the current date and time will be assumed to be yesterday, 23:59.
2356 Also, timestamps inserted in remember templates follow this rule.
2358 IMPORTANT: This is a feature whose implementation is and likely will
2359 remain incomplete. Really, it is only here because past midnight seems to
2360 be the favorite working time of John Wiegley :-)"
2361 :group 'org-time
2362 :type 'integer)
2364 (defcustom org-edit-timestamp-down-means-later nil
2365 "Non-nil means, S-down will increase the time in a time stamp.
2366 When nil, S-up will increase."
2367 :group 'org-time
2368 :type 'boolean)
2370 (defcustom org-calendar-follow-timestamp-change t
2371 "Non-nil means, make the calendar window follow timestamp changes.
2372 When a timestamp is modified and the calendar window is visible, it will be
2373 moved to the new date."
2374 :group 'org-time
2375 :type 'boolean)
2377 (defgroup org-tags nil
2378 "Options concerning tags in Org-mode."
2379 :tag "Org Tags"
2380 :group 'org)
2382 (defcustom org-tag-alist nil
2383 "List of tags allowed in Org-mode files.
2384 When this list is nil, Org-mode will base TAG input on what is already in the
2385 buffer.
2386 The value of this variable is an alist, the car of each entry must be a
2387 keyword as a string, the cdr may be a character that is used to select
2388 that tag through the fast-tag-selection interface.
2389 See the manual for details."
2390 :group 'org-tags
2391 :type '(repeat
2392 (choice
2393 (cons (string :tag "Tag name")
2394 (character :tag "Access char"))
2395 (list :tag "Start radio group"
2396 (const :startgroup)
2397 (option (string :tag "Group description")))
2398 (list :tag "End radio group"
2399 (const :endgroup)
2400 (option (string :tag "Group description")))
2401 (const :tag "New line" (:newline)))))
2403 (defcustom org-tag-persistent-alist nil
2404 "List of tags that will always appear in all Org-mode files.
2405 This is in addition to any in buffer settings or customizations
2406 of `org-tag-alist'.
2407 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2408 The value of this variable is an alist, the car of each entry must be a
2409 keyword as a string, the cdr may be a character that is used to select
2410 that tag through the fast-tag-selection interface.
2411 See the manual for details.
2412 To disable these tags on a per-file basis, insert anywhere in the file:
2413 #+STARTUP: noptag"
2414 :group 'org-tags
2415 :type '(repeat
2416 (choice
2417 (cons (string :tag "Tag name")
2418 (character :tag "Access char"))
2419 (const :tag "Start radio group" (:startgroup))
2420 (const :tag "End radio group" (:endgroup))
2421 (const :tag "New line" (:newline)))))
2423 (defvar org-file-tags nil
2424 "List of tags that can be inherited by all entries in the file.
2425 The tags will be inherited if the variable `org-use-tag-inheritance'
2426 says they should be.
2427 This variable is populated from #+FILETAGS lines.")
2429 (defcustom org-use-fast-tag-selection 'auto
2430 "Non-nil means, use fast tag selection scheme.
2431 This is a special interface to select and deselect tags with single keys.
2432 When nil, fast selection is never used.
2433 When the symbol `auto', fast selection is used if and only if selection
2434 characters for tags have been configured, either through the variable
2435 `org-tag-alist' or through a #+TAGS line in the buffer.
2436 When t, fast selection is always used and selection keys are assigned
2437 automatically if necessary."
2438 :group 'org-tags
2439 :type '(choice
2440 (const :tag "Always" t)
2441 (const :tag "Never" nil)
2442 (const :tag "When selection characters are configured" 'auto)))
2444 (defcustom org-fast-tag-selection-single-key nil
2445 "Non-nil means, fast tag selection exits after first change.
2446 When nil, you have to press RET to exit it.
2447 During fast tag selection, you can toggle this flag with `C-c'.
2448 This variable can also have the value `expert'. In this case, the window
2449 displaying the tags menu is not even shown, until you press C-c again."
2450 :group 'org-tags
2451 :type '(choice
2452 (const :tag "No" nil)
2453 (const :tag "Yes" t)
2454 (const :tag "Expert" expert)))
2456 (defvar org-fast-tag-selection-include-todo nil
2457 "Non-nil means, fast tags selection interface will also offer TODO states.
2458 This is an undocumented feature, you should not rely on it.")
2460 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2461 "The column to which tags should be indented in a headline.
2462 If this number is positive, it specifies the column. If it is negative,
2463 it means that the tags should be flushright to that column. For example,
2464 -80 works well for a normal 80 character screen."
2465 :group 'org-tags
2466 :type 'integer)
2468 (defcustom org-auto-align-tags t
2469 "Non-nil means, realign tags after pro/demotion of TODO state change.
2470 These operations change the length of a headline and therefore shift
2471 the tags around. With this options turned on, after each such operation
2472 the tags are again aligned to `org-tags-column'."
2473 :group 'org-tags
2474 :type 'boolean)
2476 (defcustom org-use-tag-inheritance t
2477 "Non-nil means, tags in levels apply also for sublevels.
2478 When nil, only the tags directly given in a specific line apply there.
2479 This may also be a list of tags that should be inherited, or a regexp that
2480 matches tags that should be inherited. Additional control is possible
2481 with the variable `org-tags-exclude-from-inheritance' which gives an
2482 explicit list of tags to be excluded from inheritance., even if the value of
2483 `org-use-tag-inheritance' would select it for inheritance.
2485 If this option is t, a match early-on in a tree can lead to a large
2486 number of matches in the subtree when constructing the agenda or creating
2487 a sparse tree. If you only want to see the first match in a tree during
2488 a search, check out the variable `org-tags-match-list-sublevels'."
2489 :group 'org-tags
2490 :type '(choice
2491 (const :tag "Not" nil)
2492 (const :tag "Always" t)
2493 (repeat :tag "Specific tags" (string :tag "Tag"))
2494 (regexp :tag "Tags matched by regexp")))
2496 (defcustom org-tags-exclude-from-inheritance nil
2497 "List of tags that should never be inherited.
2498 This is a way to exclude a few tags from inheritance. For way to do
2499 the opposite, to actively allow inheritance for selected tags,
2500 see the variable `org-use-tag-inheritance'."
2501 :group 'org-tags
2502 :type '(repeat (string :tag "Tag")))
2504 (defun org-tag-inherit-p (tag)
2505 "Check if TAG is one that should be inherited."
2506 (cond
2507 ((member tag org-tags-exclude-from-inheritance) nil)
2508 ((eq org-use-tag-inheritance t) t)
2509 ((not org-use-tag-inheritance) nil)
2510 ((stringp org-use-tag-inheritance)
2511 (string-match org-use-tag-inheritance tag))
2512 ((listp org-use-tag-inheritance)
2513 (member tag org-use-tag-inheritance))
2514 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2516 (defcustom org-tags-match-list-sublevels t
2517 "Non-nil means list also sublevels of headlines matching a search.
2518 This variable applies to tags/property searches, and also to stuck
2519 projects because this search is based on a tags match as well.
2521 When set to the symbol `indented', sublevels are indented with
2522 leading dots.
2524 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2525 the sublevels of a headline matching a tag search often also match
2526 the same search. Listing all of them can create very long lists.
2527 Setting this variable to nil causes subtrees of a match to be skipped.
2529 This variable is semi-obsolete and probably should always be true. It
2530 is better to limit inheritance to certain tags using the variables
2531 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2532 :group 'org-tags
2533 :type '(choice
2534 (const :tag "No, don't list them" nil)
2535 (const :tag "Yes, do list them" t)
2536 (const :tag "List them, indented with leading dots" indented)))
2538 (defcustom org-tags-sort-function nil
2539 "When set, tags are sorted using this function as a comparator"
2540 :group 'org-tags
2541 :type '(choice
2542 (const :tag "No sorting" nil)
2543 (const :tag "Alphabetical" string<)
2544 (const :tag "Reverse alphabetical" string>)
2545 (function :tag "Custom function" nil)))
2547 (defvar org-tags-history nil
2548 "History of minibuffer reads for tags.")
2549 (defvar org-last-tags-completion-table nil
2550 "The last used completion table for tags.")
2551 (defvar org-after-tags-change-hook nil
2552 "Hook that is run after the tags in a line have changed.")
2554 (defgroup org-properties nil
2555 "Options concerning properties in Org-mode."
2556 :tag "Org Properties"
2557 :group 'org)
2559 (defcustom org-property-format "%-10s %s"
2560 "How property key/value pairs should be formatted by `indent-line'.
2561 When `indent-line' hits a property definition, it will format the line
2562 according to this format, mainly to make sure that the values are
2563 lined-up with respect to each other."
2564 :group 'org-properties
2565 :type 'string)
2567 (defcustom org-use-property-inheritance nil
2568 "Non-nil means, properties apply also for sublevels.
2570 This setting is chiefly used during property searches. Turning it on can
2571 cause significant overhead when doing a search, which is why it is not
2572 on by default.
2574 When nil, only the properties directly given in the current entry count.
2575 When t, every property is inherited. The value may also be a list of
2576 properties that should have inheritance, or a regular expression matching
2577 properties that should be inherited.
2579 However, note that some special properties use inheritance under special
2580 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2581 and the properties ending in \"_ALL\" when they are used as descriptor
2582 for valid values of a property.
2584 Note for programmers:
2585 When querying an entry with `org-entry-get', you can control if inheritance
2586 should be used. By default, `org-entry-get' looks only at the local
2587 properties. You can request inheritance by setting the inherit argument
2588 to t (to force inheritance) or to `selective' (to respect the setting
2589 in this variable)."
2590 :group 'org-properties
2591 :type '(choice
2592 (const :tag "Not" nil)
2593 (const :tag "Always" t)
2594 (repeat :tag "Specific properties" (string :tag "Property"))
2595 (regexp :tag "Properties matched by regexp")))
2597 (defun org-property-inherit-p (property)
2598 "Check if PROPERTY is one that should be inherited."
2599 (cond
2600 ((eq org-use-property-inheritance t) t)
2601 ((not org-use-property-inheritance) nil)
2602 ((stringp org-use-property-inheritance)
2603 (string-match org-use-property-inheritance property))
2604 ((listp org-use-property-inheritance)
2605 (member property org-use-property-inheritance))
2606 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2608 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2609 "The default column format, if no other format has been defined.
2610 This variable can be set on the per-file basis by inserting a line
2612 #+COLUMNS: %25ITEM ....."
2613 :group 'org-properties
2614 :type 'string)
2616 (defcustom org-columns-ellipses ".."
2617 "The ellipses to be used when a field in column view is truncated.
2618 When this is the empty string, as many characters as possible are shown,
2619 but then there will be no visual indication that the field has been truncated.
2620 When this is a string of length N, the last N characters of a truncated
2621 field are replaced by this string. If the column is narrower than the
2622 ellipses string, only part of the ellipses string will be shown."
2623 :group 'org-properties
2624 :type 'string)
2626 (defcustom org-columns-modify-value-for-display-function nil
2627 "Function that modifies values for display in column view.
2628 For example, it can be used to cut out a certain part from a time stamp.
2629 The function must take 2 arguments:
2631 column-title The title of the column (*not* the property name)
2632 value The value that should be modified.
2634 The function should return the value that should be displayed,
2635 or nil if the normal value should be used."
2636 :group 'org-properties
2637 :type 'function)
2639 (defcustom org-effort-property "Effort"
2640 "The property that is being used to keep track of effort estimates.
2641 Effort estimates given in this property need to have the format H:MM."
2642 :group 'org-properties
2643 :group 'org-progress
2644 :type '(string :tag "Property"))
2646 (defconst org-global-properties-fixed
2647 '(("VISIBILITY_ALL" . "folded children content all")
2648 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2649 "List of property/value pairs that can be inherited by any entry.
2651 These are fixed values, for the preset properties. The user variable
2652 that can be used to add to this list is `org-global-properties'.
2654 The entries in this list are cons cells where the car is a property
2655 name and cdr is a string with the value. If the value represents
2656 multiple items like an \"_ALL\" property, separate the items by
2657 spaces.")
2659 (defcustom org-global-properties nil
2660 "List of property/value pairs that can be inherited by any entry.
2662 This list will be combined with the constant `org-global-properties-fixed'.
2664 The entries in this list are cons cells where the car is a property
2665 name and cdr is a string with the value.
2667 You can set buffer-local values for the same purpose in the variable
2668 `org-file-properties' this by adding lines like
2670 #+PROPERTY: NAME VALUE"
2671 :group 'org-properties
2672 :type '(repeat
2673 (cons (string :tag "Property")
2674 (string :tag "Value"))))
2676 (defvar org-file-properties nil
2677 "List of property/value pairs that can be inherited by any entry.
2678 Valid for the current buffer.
2679 This variable is populated from #+PROPERTY lines.")
2680 (make-variable-buffer-local 'org-file-properties)
2682 (defgroup org-agenda nil
2683 "Options concerning agenda views in Org-mode."
2684 :tag "Org Agenda"
2685 :group 'org)
2687 (defvar org-category nil
2688 "Variable used by org files to set a category for agenda display.
2689 Such files should use a file variable to set it, for example
2691 # -*- mode: org; org-category: \"ELisp\"
2693 or contain a special line
2695 #+CATEGORY: ELisp
2697 If the file does not specify a category, then file's base name
2698 is used instead.")
2699 (make-variable-buffer-local 'org-category)
2700 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2702 (defcustom org-agenda-files nil
2703 "The files to be used for agenda display.
2704 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2705 \\[org-remove-file]. You can also use customize to edit the list.
2707 If an entry is a directory, all files in that directory that are matched by
2708 `org-agenda-file-regexp' will be part of the file list.
2710 If the value of the variable is not a list but a single file name, then
2711 the list of agenda files is actually stored and maintained in that file, one
2712 agenda file per line."
2713 :group 'org-agenda
2714 :type '(choice
2715 (repeat :tag "List of files and directories" file)
2716 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2718 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2719 "Regular expression to match files for `org-agenda-files'.
2720 If any element in the list in that variable contains a directory instead
2721 of a normal file, all files in that directory that are matched by this
2722 regular expression will be included."
2723 :group 'org-agenda
2724 :type 'regexp)
2726 (defcustom org-agenda-text-search-extra-files nil
2727 "List of extra files to be searched by text search commands.
2728 These files will be search in addition to the agenda files by the
2729 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2730 Note that these files will only be searched for text search commands,
2731 not for the other agenda views like todo lists, tag searches or the weekly
2732 agenda. This variable is intended to list notes and possibly archive files
2733 that should also be searched by these two commands.
2734 In fact, if the first element in the list is the symbol `agenda-archives',
2735 than all archive files of all agenda files will be added to the search
2736 scope."
2737 :group 'org-agenda
2738 :type '(set :greedy t
2739 (const :tag "Agenda Archives" agenda-archives)
2740 (repeat :inline t (file))))
2742 (if (fboundp 'defvaralias)
2743 (defvaralias 'org-agenda-multi-occur-extra-files
2744 'org-agenda-text-search-extra-files))
2746 (defcustom org-agenda-skip-unavailable-files nil
2747 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2748 A nil value means to remove them, after a query, from the list."
2749 :group 'org-agenda
2750 :type 'boolean)
2752 (defcustom org-calendar-to-agenda-key [?c]
2753 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2754 The command `org-calendar-goto-agenda' will be bound to this key. The
2755 default is the character `c' because then `c' can be used to switch back and
2756 forth between agenda and calendar."
2757 :group 'org-agenda
2758 :type 'sexp)
2760 (defcustom org-calendar-agenda-action-key [?k]
2761 "The key to be installed in `calendar-mode-map' for agenda-action.
2762 The command `org-agenda-action' will be bound to this key. The
2763 default is the character `k' because we use the same key in the agenda."
2764 :group 'org-agenda
2765 :type 'sexp)
2767 (defcustom org-calendar-insert-diary-entry-key [?i]
2768 "The key to be installed in `calendar-mode-map' for adding diary entries.
2769 This option is irrelevant until `org-agenda-diary-file' has been configured
2770 to point to an Org-mode file. When that is the case, the command
2771 `org-agenda-diary-entry' will be bound to the key given here, by default
2772 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2773 if you want to continue doing this, you need to change this to a different
2774 key."
2775 :group 'org-agenda
2776 :type 'sexp)
2778 (defcustom org-agenda-diary-file 'diary-file
2779 "File to which to add new entries with the `i' key in agenda and calendar.
2780 When this is the symbol `diary-file', the functionality in the Emacs
2781 calendar will be used to add entries to the `diary-file'. But when this
2782 points to a file, `org-agenda-diary-entry' will be used instead."
2783 :group 'org-agenda
2784 :type '(choice
2785 (const :tag "The standard Emacs diary file" diary-file)
2786 (file :tag "Special Org file diary entries")))
2788 (eval-after-load "calendar"
2789 '(progn
2790 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2791 'org-calendar-goto-agenda)
2792 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2793 'org-agenda-action)
2794 (add-hook 'calendar-mode-hook
2795 (lambda ()
2796 (unless (eq org-agenda-diary-file 'diary-file)
2797 (define-key calendar-mode-map
2798 org-calendar-insert-diary-entry-key
2799 'org-agenda-diary-entry))))))
2801 (defgroup org-latex nil
2802 "Options for embedding LaTeX code into Org-mode."
2803 :tag "Org LaTeX"
2804 :group 'org)
2806 (defcustom org-format-latex-options
2807 '(:foreground default :background default :scale 1.0
2808 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2809 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2810 "Options for creating images from LaTeX fragments.
2811 This is a property list with the following properties:
2812 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2813 `default' means use the foreground of the default face.
2814 :background the background color, or \"Transparent\".
2815 `default' means use the background of the default face.
2816 :scale a scaling factor for the size of the images.
2817 :html-foreground, :html-background, :html-scale
2818 the same numbers for HTML export.
2819 :matchers a list indicating which matchers should be used to
2820 find LaTeX fragments. Valid members of this list are:
2821 \"begin\" find environments
2822 \"$1\" find single characters surrounded by $.$
2823 \"$\" find math expressions surrounded by $...$
2824 \"$$\" find math expressions surrounded by $$....$$
2825 \"\\(\" find math expressions surrounded by \\(...\\)
2826 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2827 :group 'org-latex
2828 :type 'plist)
2830 (defcustom org-format-latex-header "\\documentclass{article}
2831 \\usepackage{amssymb}
2832 \\usepackage[usenames]{color}
2833 \\usepackage{amsmath}
2834 \\usepackage{latexsym}
2835 \\usepackage[mathscr]{eucal}
2836 \\pagestyle{empty} % do not remove
2837 % The settings below are copied from fullpage.sty
2838 \\setlength{\\textwidth}{\\paperwidth}
2839 \\addtolength{\\textwidth}{-3cm}
2840 \\setlength{\\oddsidemargin}{1.5cm}
2841 \\addtolength{\\oddsidemargin}{-2.54cm}
2842 \\setlength{\\evensidemargin}{\\oddsidemargin}
2843 \\setlength{\\textheight}{\\paperheight}
2844 \\addtolength{\\textheight}{-\\headheight}
2845 \\addtolength{\\textheight}{-\\headsep}
2846 \\addtolength{\\textheight}{-\\footskip}
2847 \\addtolength{\\textheight}{-3cm}
2848 \\setlength{\\topmargin}{1.5cm}
2849 \\addtolength{\\topmargin}{-2.54cm}"
2850 "The document header used for processing LaTeX fragments.
2851 It is imperative that this header make sure that no page number
2852 appears on the page."
2853 :group 'org-latex
2854 :type 'string)
2857 (defgroup org-font-lock nil
2858 "Font-lock settings for highlighting in Org-mode."
2859 :tag "Org Font Lock"
2860 :group 'org)
2862 (defcustom org-level-color-stars-only nil
2863 "Non-nil means fontify only the stars in each headline.
2864 When nil, the entire headline is fontified.
2865 Changing it requires restart of `font-lock-mode' to become effective
2866 also in regions already fontified."
2867 :group 'org-font-lock
2868 :type 'boolean)
2870 (defcustom org-hide-leading-stars nil
2871 "Non-nil means, hide the first N-1 stars in a headline.
2872 This works by using the face `org-hide' for these stars. This
2873 face is white for a light background, and black for a dark
2874 background. You may have to customize the face `org-hide' to
2875 make this work.
2876 Changing it requires restart of `font-lock-mode' to become effective
2877 also in regions already fontified.
2878 You may also set this on a per-file basis by adding one of the following
2879 lines to the buffer:
2881 #+STARTUP: hidestars
2882 #+STARTUP: showstars"
2883 :group 'org-font-lock
2884 :type 'boolean)
2886 (defcustom org-fontify-done-headline nil
2887 "Non-nil means, change the face of a headline if it is marked DONE.
2888 Normally, only the TODO/DONE keyword indicates the state of a headline.
2889 When this is non-nil, the headline after the keyword is set to the
2890 `org-headline-done' as an additional indication."
2891 :group 'org-font-lock
2892 :type 'boolean)
2894 (defcustom org-fontify-emphasized-text t
2895 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2896 Changing this variable requires a restart of Emacs to take effect."
2897 :group 'org-font-lock
2898 :type 'boolean)
2900 (defcustom org-fontify-whole-heading-line nil
2901 "Non-nil means fontify the whole line for headings.
2902 This is useful when setting a background color for the
2903 org-level-* faces."
2904 :group 'org-font-lock
2905 :type 'boolean)
2907 (defcustom org-highlight-latex-fragments-and-specials nil
2908 "Non-nil means, fontify what is treated specially by the exporters."
2909 :group 'org-font-lock
2910 :type 'boolean)
2912 (defcustom org-hide-emphasis-markers nil
2913 "Non-nil mean font-lock should hide the emphasis marker characters."
2914 :group 'org-font-lock
2915 :type 'boolean)
2917 (defvar org-emph-re nil
2918 "Regular expression for matching emphasis.")
2919 (defvar org-verbatim-re nil
2920 "Regular expression for matching verbatim text.")
2921 (defvar org-emphasis-regexp-components) ; defined just below
2922 (defvar org-emphasis-alist) ; defined just below
2923 (defun org-set-emph-re (var val)
2924 "Set variable and compute the emphasis regular expression."
2925 (set var val)
2926 (when (and (boundp 'org-emphasis-alist)
2927 (boundp 'org-emphasis-regexp-components)
2928 org-emphasis-alist org-emphasis-regexp-components)
2929 (let* ((e org-emphasis-regexp-components)
2930 (pre (car e))
2931 (post (nth 1 e))
2932 (border (nth 2 e))
2933 (body (nth 3 e))
2934 (nl (nth 4 e))
2935 (body1 (concat body "*?"))
2936 (markers (mapconcat 'car org-emphasis-alist ""))
2937 (vmarkers (mapconcat
2938 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2939 org-emphasis-alist "")))
2940 ;; make sure special characters appear at the right position in the class
2941 (if (string-match "\\^" markers)
2942 (setq markers (concat (replace-match "" t t markers) "^")))
2943 (if (string-match "-" markers)
2944 (setq markers (concat (replace-match "" t t markers) "-")))
2945 (if (string-match "\\^" vmarkers)
2946 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2947 (if (string-match "-" vmarkers)
2948 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2949 (if (> nl 0)
2950 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2951 (int-to-string nl) "\\}")))
2952 ;; Make the regexp
2953 (setq org-emph-re
2954 (concat "\\([" pre "]\\|^\\)"
2955 "\\("
2956 "\\([" markers "]\\)"
2957 "\\("
2958 "[^" border "]\\|"
2959 "[^" border "]"
2960 body1
2961 "[^" border "]"
2962 "\\)"
2963 "\\3\\)"
2964 "\\([" post "]\\|$\\)"))
2965 (setq org-verbatim-re
2966 (concat "\\([" pre "]\\|^\\)"
2967 "\\("
2968 "\\([" vmarkers "]\\)"
2969 "\\("
2970 "[^" border "]\\|"
2971 "[^" border "]"
2972 body1
2973 "[^" border "]"
2974 "\\)"
2975 "\\3\\)"
2976 "\\([" post "]\\|$\\)")))))
2978 (defcustom org-emphasis-regexp-components
2979 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2980 "Components used to build the regular expression for emphasis.
2981 This is a list with 6 entries. Terminology: In an emphasis string
2982 like \" *strong word* \", we call the initial space PREMATCH, the final
2983 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2984 and \"trong wor\" is the body. The different components in this variable
2985 specify what is allowed/forbidden in each part:
2987 pre Chars allowed as prematch. Beginning of line will be allowed too.
2988 post Chars allowed as postmatch. End of line will be allowed too.
2989 border The chars *forbidden* as border characters.
2990 body-regexp A regexp like \".\" to match a body character. Don't use
2991 non-shy groups here, and don't allow newline here.
2992 newline The maximum number of newlines allowed in an emphasis exp.
2994 Use customize to modify this, or restart Emacs after changing it."
2995 :group 'org-font-lock
2996 :set 'org-set-emph-re
2997 :type '(list
2998 (sexp :tag "Allowed chars in pre ")
2999 (sexp :tag "Allowed chars in post ")
3000 (sexp :tag "Forbidden chars in border ")
3001 (sexp :tag "Regexp for body ")
3002 (integer :tag "number of newlines allowed")
3003 (option (boolean :tag "Please ignore this button"))))
3005 (defcustom org-emphasis-alist
3006 `(("*" bold "<b>" "</b>")
3007 ("/" italic "<i>" "</i>")
3008 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3009 ("=" org-code "<code>" "</code>" verbatim)
3010 ("~" org-verbatim "<code>" "</code>" verbatim)
3011 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3012 "<del>" "</del>")
3014 "Special syntax for emphasized text.
3015 Text starting and ending with a special character will be emphasized, for
3016 example *bold*, _underlined_ and /italic/. This variable sets the marker
3017 characters, the face to be used by font-lock for highlighting in Org-mode
3018 Emacs buffers, and the HTML tags to be used for this.
3019 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3020 Use customize to modify this, or restart Emacs after changing it."
3021 :group 'org-font-lock
3022 :set 'org-set-emph-re
3023 :type '(repeat
3024 (list
3025 (string :tag "Marker character")
3026 (choice
3027 (face :tag "Font-lock-face")
3028 (plist :tag "Face property list"))
3029 (string :tag "HTML start tag")
3030 (string :tag "HTML end tag")
3031 (option (const verbatim)))))
3033 (defvar org-protecting-blocks
3034 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3035 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3036 This is needed for font-lock setup.")
3038 ;;; Miscellaneous options
3040 (defgroup org-completion nil
3041 "Completion in Org-mode."
3042 :tag "Org Completion"
3043 :group 'org)
3045 (defcustom org-completion-use-ido nil
3046 "Non-nil means, use ido completion wherever possible.
3047 Note that `ido-mode' must be active for this variable to be relevant.
3048 If you decide to turn this variable on, you might well want to turn off
3049 `org-outline-path-complete-in-steps'.
3050 See also `org-completion-use-iswitchb'."
3051 :group 'org-completion
3052 :type 'boolean)
3054 (defcustom org-completion-use-iswitchb nil
3055 "Non-nil means, use iswitchb completion wherever possible.
3056 Note that `iswitchb-mode' must be active for this variable to be relevant.
3057 If you decide to turn this variable on, you might well want to turn off
3058 `org-outline-path-complete-in-steps'.
3059 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3060 :group 'org-completion
3061 :type 'boolean)
3063 (defcustom org-completion-fallback-command 'hippie-expand
3064 "The expansion command called by \\[org-complete] in normal context.
3065 Normal means, no org-mode-specific context."
3066 :group 'org-completion
3067 :type 'function)
3069 ;;; Functions and variables from their packages
3070 ;; Declared here to avoid compiler warnings
3072 ;; XEmacs only
3073 (defvar outline-mode-menu-heading)
3074 (defvar outline-mode-menu-show)
3075 (defvar outline-mode-menu-hide)
3076 (defvar zmacs-regions) ; XEmacs regions
3078 ;; Emacs only
3079 (defvar mark-active)
3081 ;; Various packages
3082 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3083 (declare-function calendar-forward-day "cal-move" (arg))
3084 (declare-function calendar-goto-date "cal-move" (date))
3085 (declare-function calendar-goto-today "cal-move" ())
3086 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3087 (defvar calc-embedded-close-formula)
3088 (defvar calc-embedded-open-formula)
3089 (declare-function cdlatex-tab "ext:cdlatex" ())
3090 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3091 (defvar font-lock-unfontify-region-function)
3092 (declare-function iswitchb-read-buffer "iswitchb"
3093 (prompt &optional default require-match start matches-set))
3094 (defvar iswitchb-temp-buflist)
3095 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3096 (defvar org-agenda-tags-todo-honor-ignore-options)
3097 (declare-function org-agenda-skip "org-agenda" ())
3098 (declare-function org-format-agenda-item "org-agenda"
3099 (extra txt &optional category tags dotime noprefix remove-re))
3100 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3101 (declare-function org-agenda-change-all-lines "org-agenda"
3102 (newhead hdmarker &optional fixface just-this))
3103 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3104 (declare-function org-agenda-maybe-redo "org-agenda" ())
3105 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3106 (beg end))
3107 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3108 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3109 "org-agenda" (&optional end))
3110 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3111 (declare-function org-indent-mode "org-indent" (&optional arg))
3112 (declare-function parse-time-string "parse-time" (string))
3113 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3114 (defvar remember-data-file)
3115 (defvar texmathp-why)
3116 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3117 (declare-function table--at-cell-p "table" (position &optional object at-column))
3119 (defvar w3m-current-url)
3120 (defvar w3m-current-title)
3122 (defvar org-latex-regexps)
3124 ;;; Autoload and prepare some org modules
3126 ;; Some table stuff that needs to be defined here, because it is used
3127 ;; by the functions setting up org-mode or checking for table context.
3129 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3130 "Detects an org-type or table-type table.")
3131 (defconst org-table-line-regexp "^[ \t]*|"
3132 "Detects an org-type table line.")
3133 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3134 "Detects an org-type table line.")
3135 (defconst org-table-hline-regexp "^[ \t]*|-"
3136 "Detects an org-type table hline.")
3137 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3138 "Detects a table-type table hline.")
3139 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3140 "Searching from within a table (any type) this finds the first line
3141 outside the table.")
3143 ;; Autoload the functions in org-table.el that are needed by functions here.
3145 (eval-and-compile
3146 (org-autoload "org-table"
3147 '(org-table-align org-table-begin org-table-blank-field
3148 org-table-convert org-table-convert-region org-table-copy-down
3149 org-table-copy-region org-table-create
3150 org-table-create-or-convert-from-region
3151 org-table-create-with-table.el org-table-current-dline
3152 org-table-cut-region org-table-delete-column org-table-edit-field
3153 org-table-edit-formulas org-table-end org-table-eval-formula
3154 org-table-export org-table-field-info
3155 org-table-get-stored-formulas org-table-goto-column
3156 org-table-hline-and-move org-table-import org-table-insert-column
3157 org-table-insert-hline org-table-insert-row org-table-iterate
3158 org-table-justify-field-maybe org-table-kill-row
3159 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3160 org-table-move-column org-table-move-column-left
3161 org-table-move-column-right org-table-move-row
3162 org-table-move-row-down org-table-move-row-up
3163 org-table-next-field org-table-next-row org-table-paste-rectangle
3164 org-table-previous-field org-table-recalculate
3165 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3166 org-table-toggle-coordinate-overlays
3167 org-table-toggle-formula-debugger org-table-wrap-region
3168 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3170 (defun org-at-table-p (&optional table-type)
3171 "Return t if the cursor is inside an org-type table.
3172 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3173 (if org-enable-table-editor
3174 (save-excursion
3175 (beginning-of-line 1)
3176 (looking-at (if table-type org-table-any-line-regexp
3177 org-table-line-regexp)))
3178 nil))
3179 (defsubst org-table-p () (org-at-table-p))
3181 (defun org-at-table.el-p ()
3182 "Return t if and only if we are at a table.el table."
3183 (and (org-at-table-p 'any)
3184 (save-excursion
3185 (goto-char (org-table-begin 'any))
3186 (looking-at org-table1-hline-regexp))))
3187 (defun org-table-recognize-table.el ()
3188 "If there is a table.el table nearby, recognize it and move into it."
3189 (if org-table-tab-recognizes-table.el
3190 (if (org-at-table.el-p)
3191 (progn
3192 (beginning-of-line 1)
3193 (if (looking-at org-table-dataline-regexp)
3195 (if (looking-at org-table1-hline-regexp)
3196 (progn
3197 (beginning-of-line 2)
3198 (if (looking-at org-table-any-border-regexp)
3199 (beginning-of-line -1)))))
3200 (if (re-search-forward "|" (org-table-end t) t)
3201 (progn
3202 (require 'table)
3203 (if (table--at-cell-p (point))
3205 (message "recognizing table.el table...")
3206 (table-recognize-table)
3207 (message "recognizing table.el table...done")))
3208 (error "This should not happen..."))
3210 nil)
3211 nil))
3213 (defun org-at-table-hline-p ()
3214 "Return t if the cursor is inside a hline in a table."
3215 (if org-enable-table-editor
3216 (save-excursion
3217 (beginning-of-line 1)
3218 (looking-at org-table-hline-regexp))
3219 nil))
3221 (defvar org-table-clean-did-remove-column nil)
3223 (defun org-table-map-tables (function)
3224 "Apply FUNCTION to the start of all tables in the buffer."
3225 (save-excursion
3226 (save-restriction
3227 (widen)
3228 (goto-char (point-min))
3229 (while (re-search-forward org-table-any-line-regexp nil t)
3230 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3231 (beginning-of-line 1)
3232 (when (looking-at org-table-line-regexp)
3233 (save-excursion (funcall function))
3234 (or (looking-at org-table-line-regexp)
3235 (forward-char 1)))
3236 (re-search-forward org-table-any-border-regexp nil 1))))
3237 (message "Mapping tables: done"))
3239 ;; Declare and autoload functions from org-exp.el & Co
3241 (declare-function org-default-export-plist "org-exp")
3242 (declare-function org-infile-export-plist "org-exp")
3243 (declare-function org-get-current-options "org-exp")
3244 (eval-and-compile
3245 (org-autoload "org-exp"
3246 '(org-export org-export-visible
3247 org-insert-export-options-template
3248 org-table-clean-before-export))
3249 (org-autoload "org-ascii"
3250 '(org-export-as-ascii org-export-ascii-preprocess
3251 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3252 org-export-region-as-ascii))
3253 (org-autoload "org-html"
3254 '(org-export-as-html-and-open
3255 org-export-as-html-batch org-export-as-html-to-buffer
3256 org-replace-region-by-html org-export-region-as-html
3257 org-export-as-html))
3258 (org-autoload "org-icalendar"
3259 '(org-export-icalendar-this-file
3260 org-export-icalendar-all-agenda-files
3261 org-export-icalendar-combine-agenda-files))
3262 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3264 ;; Declare and autoload functions from org-agenda.el
3266 (eval-and-compile
3267 (org-autoload "org-agenda"
3268 '(org-agenda org-agenda-list org-search-view
3269 org-todo-list org-tags-view org-agenda-list-stuck-projects
3270 org-diary org-agenda-to-appt
3271 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3273 ;; Autoload org-remember
3275 (eval-and-compile
3276 (org-autoload "org-remember"
3277 '(org-remember-insinuate org-remember-annotation
3278 org-remember-apply-template org-remember org-remember-handler)))
3280 ;; Autoload org-clock.el
3283 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3284 (beg end))
3285 (declare-function org-clock-update-mode-line "org-clock" ())
3286 (declare-function org-resolve-clocks "org-clock"
3287 (&optional also-non-dangling-p prompt last-valid))
3288 (defvar org-clock-start-time)
3289 (defvar org-clock-marker (make-marker)
3290 "Marker recording the last clock-in.")
3291 (defvar org-clock-hd-marker (make-marker)
3292 "Marker recording the last clock-in, but the headline position.")
3293 (defvar org-clock-heading ""
3294 "The heading of the current clock entry.")
3295 (defun org-clock-is-active ()
3296 "Return non-nil if clock is currently running.
3297 The return value is actually the clock marker."
3298 (marker-buffer org-clock-marker))
3300 (eval-and-compile
3301 (org-autoload
3302 "org-clock"
3303 '(org-clock-in org-clock-out org-clock-cancel
3304 org-clock-goto org-clock-sum org-clock-display
3305 org-clock-remove-overlays org-clock-report
3306 org-clocktable-shift org-dblock-write:clocktable
3307 org-get-clocktable org-resolve-clocks)))
3309 (defun org-clock-update-time-maybe ()
3310 "If this is a CLOCK line, update it and return t.
3311 Otherwise, return nil."
3312 (interactive)
3313 (save-excursion
3314 (beginning-of-line 1)
3315 (skip-chars-forward " \t")
3316 (when (looking-at org-clock-string)
3317 (let ((re (concat "[ \t]*" org-clock-string
3318 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3319 "\\([ \t]*=>.*\\)?\\)?"))
3320 ts te h m s neg)
3321 (cond
3322 ((not (looking-at re))
3323 nil)
3324 ((not (match-end 2))
3325 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3326 (> org-clock-marker (point))
3327 (<= org-clock-marker (point-at-eol)))
3328 ;; The clock is running here
3329 (setq org-clock-start-time
3330 (apply 'encode-time
3331 (org-parse-time-string (match-string 1))))
3332 (org-clock-update-mode-line)))
3334 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3335 (end-of-line 1)
3336 (setq ts (match-string 1)
3337 te (match-string 3))
3338 (setq s (- (org-float-time
3339 (apply 'encode-time (org-parse-time-string te)))
3340 (org-float-time
3341 (apply 'encode-time (org-parse-time-string ts))))
3342 neg (< s 0)
3343 s (abs s)
3344 h (floor (/ s 3600))
3345 s (- s (* 3600 h))
3346 m (floor (/ s 60))
3347 s (- s (* 60 s)))
3348 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3349 t))))))
3351 (defun org-check-running-clock ()
3352 "Check if the current buffer contains the running clock.
3353 If yes, offer to stop it and to save the buffer with the changes."
3354 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3355 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3356 (buffer-name))))
3357 (org-clock-out)
3358 (when (y-or-n-p "Save changed buffer?")
3359 (save-buffer))))
3361 (defun org-clocktable-try-shift (dir n)
3362 "Check if this line starts a clock table, if yes, shift the time block."
3363 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3364 (org-clocktable-shift dir n)))
3366 ;; Autoload org-timer.el
3368 (eval-and-compile
3369 (org-autoload
3370 "org-timer"
3371 '(org-timer-start org-timer org-timer-item
3372 org-timer-change-times-in-region
3373 org-timer-set-timer
3374 org-timer-reset-timers
3375 org-timer-show-remaining-time)))
3377 ;; Autoload org-feed.el
3379 (eval-and-compile
3380 (org-autoload
3381 "org-feed"
3382 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3385 ;; Autoload org-indent.el
3387 ;; Define the variable already here, to make sure we have it.
3388 (defvar org-indent-mode nil
3389 "Non-nil if Org-Indent mode is enabled.
3390 Use the command `org-indent-mode' to change this variable.")
3392 (eval-and-compile
3393 (org-autoload
3394 "org-indent"
3395 '(org-indent-mode)))
3397 ;; Autoload org-mobile.el
3399 (eval-and-compile
3400 (org-autoload
3401 "org-mobile"
3402 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3404 ;; Autoload archiving code
3405 ;; The stuff that is needed for cycling and tags has to be defined here.
3407 (defgroup org-archive nil
3408 "Options concerning archiving in Org-mode."
3409 :tag "Org Archive"
3410 :group 'org-structure)
3412 (defcustom org-archive-location "%s_archive::"
3413 "The location where subtrees should be archived.
3415 The value of this variable is a string, consisting of two parts,
3416 separated by a double-colon. The first part is a filename and
3417 the second part is a headline.
3419 When the filename is omitted, archiving happens in the same file.
3420 %s in the filename will be replaced by the current file
3421 name (without the directory part). Archiving to a different file
3422 is useful to keep archived entries from contributing to the
3423 Org-mode Agenda.
3425 The archived entries will be filed as subtrees of the specified
3426 headline. When the headline is omitted, the subtrees are simply
3427 filed away at the end of the file, as top-level entries. Also in
3428 the heading you can use %s to represent the file name, this can be
3429 useful when using the same archive for a number of different files.
3431 Here are a few examples:
3432 \"%s_archive::\"
3433 If the current file is Projects.org, archive in file
3434 Projects.org_archive, as top-level trees. This is the default.
3436 \"::* Archived Tasks\"
3437 Archive in the current file, under the top-level headline
3438 \"* Archived Tasks\".
3440 \"~/org/archive.org::\"
3441 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3443 \"~/org/archive.org::From %s\"
3444 Archive in file ~/org/archive.org (absolute path), under headlines
3445 \"From FILENAME\" where file name is the current file name.
3447 \"basement::** Finished Tasks\"
3448 Archive in file ./basement (relative path), as level 3 trees
3449 below the level 2 heading \"** Finished Tasks\".
3451 You may set this option on a per-file basis by adding to the buffer a
3452 line like
3454 #+ARCHIVE: basement::** Finished Tasks
3456 You may also define it locally for a subtree by setting an ARCHIVE property
3457 in the entry. If such a property is found in an entry, or anywhere up
3458 the hierarchy, it will be used."
3459 :group 'org-archive
3460 :type 'string)
3462 (defcustom org-archive-tag "ARCHIVE"
3463 "The tag that marks a subtree as archived.
3464 An archived subtree does not open during visibility cycling, and does
3465 not contribute to the agenda listings.
3466 After changing this, font-lock must be restarted in the relevant buffers to
3467 get the proper fontification."
3468 :group 'org-archive
3469 :group 'org-keywords
3470 :type 'string)
3472 (defcustom org-agenda-skip-archived-trees t
3473 "Non-nil means, the agenda will skip any items located in archived trees.
3474 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3475 variable is no longer recommended, you should leave it at the value t.
3476 Instead, use the key `v' to cycle the archives-mode in the agenda."
3477 :group 'org-archive
3478 :group 'org-agenda-skip
3479 :type 'boolean)
3481 (defcustom org-columns-skip-archived-trees t
3482 "Non-nil means, ignore archived trees when creating column view."
3483 :group 'org-archive
3484 :group 'org-properties
3485 :type 'boolean)
3487 (defcustom org-cycle-open-archived-trees nil
3488 "Non-nil means, `org-cycle' will open archived trees.
3489 An archived tree is a tree marked with the tag ARCHIVE.
3490 When nil, archived trees will stay folded. You can still open them with
3491 normal outline commands like `show-all', but not with the cycling commands."
3492 :group 'org-archive
3493 :group 'org-cycle
3494 :type 'boolean)
3496 (defcustom org-sparse-tree-open-archived-trees nil
3497 "Non-nil means sparse tree construction shows matches in archived trees.
3498 When nil, matches in these trees are highlighted, but the trees are kept in
3499 collapsed state."
3500 :group 'org-archive
3501 :group 'org-sparse-trees
3502 :type 'boolean)
3504 (defun org-cycle-hide-archived-subtrees (state)
3505 "Re-hide all archived subtrees after a visibility state change."
3506 (when (and (not org-cycle-open-archived-trees)
3507 (not (memq state '(overview folded))))
3508 (save-excursion
3509 (let* ((globalp (memq state '(contents all)))
3510 (beg (if globalp (point-min) (point)))
3511 (end (if globalp (point-max) (org-end-of-subtree t))))
3512 (org-hide-archived-subtrees beg end)
3513 (goto-char beg)
3514 (if (looking-at (concat ".*:" org-archive-tag ":"))
3515 (message "%s" (substitute-command-keys
3516 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3518 (defun org-force-cycle-archived ()
3519 "Cycle subtree even if it is archived."
3520 (interactive)
3521 (setq this-command 'org-cycle)
3522 (let ((org-cycle-open-archived-trees t))
3523 (call-interactively 'org-cycle)))
3525 (defun org-hide-archived-subtrees (beg end)
3526 "Re-hide all archived subtrees after a visibility state change."
3527 (save-excursion
3528 (let* ((re (concat ":" org-archive-tag ":")))
3529 (goto-char beg)
3530 (while (re-search-forward re end t)
3531 (and (org-on-heading-p) (org-flag-subtree t))
3532 (org-end-of-subtree t)))))
3534 (defun org-flag-subtree (flag)
3535 (save-excursion
3536 (org-back-to-heading t)
3537 (outline-end-of-heading)
3538 (outline-flag-region (point)
3539 (progn (org-end-of-subtree t) (point))
3540 flag)))
3542 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3544 (eval-and-compile
3545 (org-autoload "org-archive"
3546 '(org-add-archive-files org-archive-subtree
3547 org-archive-to-archive-sibling org-toggle-archive-tag)))
3549 ;; Autoload Column View Code
3551 (declare-function org-columns-number-to-string "org-colview")
3552 (declare-function org-columns-get-format-and-top-level "org-colview")
3553 (declare-function org-columns-compute "org-colview")
3555 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3556 '(org-columns-number-to-string org-columns-get-format-and-top-level
3557 org-columns-compute org-agenda-columns org-columns-remove-overlays
3558 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3560 ;; Autoload ID code
3562 (declare-function org-id-store-link "org-id")
3563 (declare-function org-id-locations-load "org-id")
3564 (declare-function org-id-locations-save "org-id")
3565 (defvar org-id-track-globally)
3566 (org-autoload "org-id"
3567 '(org-id-get-create org-id-new org-id-copy org-id-get
3568 org-id-get-with-outline-path-completion
3569 org-id-get-with-outline-drilling
3570 org-id-goto org-id-find org-id-store-link))
3572 ;; Autoload Plotting Code
3574 (org-autoload "org-plot"
3575 '(org-plot/gnuplot))
3577 ;;; Variables for pre-computed regular expressions, all buffer local
3579 (defvar org-drawer-regexp nil
3580 "Matches first line of a hidden block.")
3581 (make-variable-buffer-local 'org-drawer-regexp)
3582 (defvar org-todo-regexp nil
3583 "Matches any of the TODO state keywords.")
3584 (make-variable-buffer-local 'org-todo-regexp)
3585 (defvar org-not-done-regexp nil
3586 "Matches any of the TODO state keywords except the last one.")
3587 (make-variable-buffer-local 'org-not-done-regexp)
3588 (defvar org-not-done-heading-regexp nil
3589 "Matches a TODO headline that is not done.")
3590 (make-variable-buffer-local 'org-not-done-regexp)
3591 (defvar org-todo-line-regexp nil
3592 "Matches a headline and puts TODO state into group 2 if present.")
3593 (make-variable-buffer-local 'org-todo-line-regexp)
3594 (defvar org-complex-heading-regexp nil
3595 "Matches a headline and puts everything into groups:
3596 group 1: the stars
3597 group 2: The todo keyword, maybe
3598 group 3: Priority cookie
3599 group 4: True headline
3600 group 5: Tags")
3601 (make-variable-buffer-local 'org-complex-heading-regexp)
3602 (defvar org-complex-heading-regexp-format nil)
3603 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3604 (defvar org-todo-line-tags-regexp nil
3605 "Matches a headline and puts TODO state into group 2 if present.
3606 Also put tags into group 4 if tags are present.")
3607 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3608 (defvar org-nl-done-regexp nil
3609 "Matches newline followed by a headline with the DONE keyword.")
3610 (make-variable-buffer-local 'org-nl-done-regexp)
3611 (defvar org-looking-at-done-regexp nil
3612 "Matches the DONE keyword a point.")
3613 (make-variable-buffer-local 'org-looking-at-done-regexp)
3614 (defvar org-ds-keyword-length 12
3615 "Maximum length of the Deadline and SCHEDULED keywords.")
3616 (make-variable-buffer-local 'org-ds-keyword-length)
3617 (defvar org-deadline-regexp nil
3618 "Matches the DEADLINE keyword.")
3619 (make-variable-buffer-local 'org-deadline-regexp)
3620 (defvar org-deadline-time-regexp nil
3621 "Matches the DEADLINE keyword together with a time stamp.")
3622 (make-variable-buffer-local 'org-deadline-time-regexp)
3623 (defvar org-deadline-line-regexp nil
3624 "Matches the DEADLINE keyword and the rest of the line.")
3625 (make-variable-buffer-local 'org-deadline-line-regexp)
3626 (defvar org-scheduled-regexp nil
3627 "Matches the SCHEDULED keyword.")
3628 (make-variable-buffer-local 'org-scheduled-regexp)
3629 (defvar org-scheduled-time-regexp nil
3630 "Matches the SCHEDULED keyword together with a time stamp.")
3631 (make-variable-buffer-local 'org-scheduled-time-regexp)
3632 (defvar org-closed-time-regexp nil
3633 "Matches the CLOSED keyword together with a time stamp.")
3634 (make-variable-buffer-local 'org-closed-time-regexp)
3636 (defvar org-keyword-time-regexp nil
3637 "Matches any of the 4 keywords, together with the time stamp.")
3638 (make-variable-buffer-local 'org-keyword-time-regexp)
3639 (defvar org-keyword-time-not-clock-regexp nil
3640 "Matches any of the 3 keywords, together with the time stamp.")
3641 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3642 (defvar org-maybe-keyword-time-regexp nil
3643 "Matches a timestamp, possibly preceeded by a keyword.")
3644 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3645 (defvar org-planning-or-clock-line-re nil
3646 "Matches a line with planning or clock info.")
3647 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3649 (defconst org-plain-time-of-day-regexp
3650 (concat
3651 "\\(\\<[012]?[0-9]"
3652 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3653 "\\(--?"
3654 "\\(\\<[012]?[0-9]"
3655 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3656 "\\)?")
3657 "Regular expression to match a plain time or time range.
3658 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3659 groups carry important information:
3660 0 the full match
3661 1 the first time, range or not
3662 8 the second time, if it is a range.")
3664 (defconst org-plain-time-extension-regexp
3665 (concat
3666 "\\(\\<[012]?[0-9]"
3667 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3668 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3669 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3670 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3671 groups carry important information:
3672 0 the full match
3673 7 hours of duration
3674 9 minutes of duration")
3676 (defconst org-stamp-time-of-day-regexp
3677 (concat
3678 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3679 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3680 "\\(--?"
3681 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3682 "Regular expression to match a timestamp time or time range.
3683 After a match, the following groups carry important information:
3684 0 the full match
3685 1 date plus weekday, for back referencing to make sure both times are on the same day
3686 2 the first time, range or not
3687 4 the second time, if it is a range.")
3689 (defconst org-startup-options
3690 '(("fold" org-startup-folded t)
3691 ("overview" org-startup-folded t)
3692 ("nofold" org-startup-folded nil)
3693 ("showall" org-startup-folded nil)
3694 ("showeverything" org-startup-folded showeverything)
3695 ("content" org-startup-folded content)
3696 ("indent" org-startup-indented t)
3697 ("noindent" org-startup-indented nil)
3698 ("hidestars" org-hide-leading-stars t)
3699 ("showstars" org-hide-leading-stars nil)
3700 ("odd" org-odd-levels-only t)
3701 ("oddeven" org-odd-levels-only nil)
3702 ("align" org-startup-align-all-tables t)
3703 ("noalign" org-startup-align-all-tables nil)
3704 ("customtime" org-display-custom-times t)
3705 ("logdone" org-log-done time)
3706 ("lognotedone" org-log-done note)
3707 ("nologdone" org-log-done nil)
3708 ("lognoteclock-out" org-log-note-clock-out t)
3709 ("nolognoteclock-out" org-log-note-clock-out nil)
3710 ("logrepeat" org-log-repeat state)
3711 ("lognoterepeat" org-log-repeat note)
3712 ("nologrepeat" org-log-repeat nil)
3713 ("logreschedule" org-log-reschedule time)
3714 ("lognotereschedule" org-log-reschedule note)
3715 ("nologreschedule" org-log-reschedule nil)
3716 ("logredeadline" org-log-redeadline time)
3717 ("lognoteredeadline" org-log-redeadline note)
3718 ("nologredeadline" org-log-redeadline nil)
3719 ("fninline" org-footnote-define-inline t)
3720 ("nofninline" org-footnote-define-inline nil)
3721 ("fnlocal" org-footnote-section nil)
3722 ("fnauto" org-footnote-auto-label t)
3723 ("fnprompt" org-footnote-auto-label nil)
3724 ("fnconfirm" org-footnote-auto-label confirm)
3725 ("fnplain" org-footnote-auto-label plain)
3726 ("fnadjust" org-footnote-auto-adjust t)
3727 ("nofnadjust" org-footnote-auto-adjust nil)
3728 ("constcgs" constants-unit-system cgs)
3729 ("constSI" constants-unit-system SI)
3730 ("noptag" org-tag-persistent-alist nil)
3731 ("hideblocks" org-hide-block-startup t)
3732 ("nohideblocks" org-hide-block-startup nil))
3733 "Variable associated with STARTUP options for org-mode.
3734 Each element is a list of three items: The startup options as written
3735 in the #+STARTUP line, the corresponding variable, and the value to
3736 set this variable to if the option is found. An optional forth element PUSH
3737 means to push this value onto the list in the variable.")
3739 (defun org-set-regexps-and-options ()
3740 "Precompute regular expressions for current buffer."
3741 (when (org-mode-p)
3742 (org-set-local 'org-todo-kwd-alist nil)
3743 (org-set-local 'org-todo-key-alist nil)
3744 (org-set-local 'org-todo-key-trigger nil)
3745 (org-set-local 'org-todo-keywords-1 nil)
3746 (org-set-local 'org-done-keywords nil)
3747 (org-set-local 'org-todo-heads nil)
3748 (org-set-local 'org-todo-sets nil)
3749 (org-set-local 'org-todo-log-states nil)
3750 (org-set-local 'org-file-properties nil)
3751 (org-set-local 'org-file-tags nil)
3752 (let ((re (org-make-options-regexp
3753 '("CATEGORY" "TODO" "COLUMNS"
3754 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3755 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3756 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3757 (splitre "[ \t]+")
3758 kwds kws0 kwsa key log value cat arch tags const links hw dws
3759 tail sep kws1 prio props ftags drawers
3760 ext-setup-or-nil setup-contents (start 0))
3761 (save-excursion
3762 (save-restriction
3763 (widen)
3764 (goto-char (point-min))
3765 (while (or (and ext-setup-or-nil
3766 (string-match re ext-setup-or-nil start)
3767 (setq start (match-end 0)))
3768 (and (setq ext-setup-or-nil nil start 0)
3769 (re-search-forward re nil t)))
3770 (setq key (upcase (match-string 1 ext-setup-or-nil))
3771 value (org-match-string-no-properties 2 ext-setup-or-nil))
3772 (cond
3773 ((equal key "CATEGORY")
3774 (if (string-match "[ \t]+$" value)
3775 (setq value (replace-match "" t t value)))
3776 (setq cat value))
3777 ((member key '("SEQ_TODO" "TODO"))
3778 (push (cons 'sequence (org-split-string value splitre)) kwds))
3779 ((equal key "TYP_TODO")
3780 (push (cons 'type (org-split-string value splitre)) kwds))
3781 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3782 ;; general TODO-like setup
3783 (push (cons (intern (downcase (match-string 1 key)))
3784 (org-split-string value splitre)) kwds))
3785 ((equal key "TAGS")
3786 (setq tags (append tags (if tags '("\\n") nil)
3787 (org-split-string value splitre))))
3788 ((equal key "COLUMNS")
3789 (org-set-local 'org-columns-default-format value))
3790 ((equal key "LINK")
3791 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3792 (push (cons (match-string 1 value)
3793 (org-trim (match-string 2 value)))
3794 links)))
3795 ((equal key "PRIORITIES")
3796 (setq prio (org-split-string value " +")))
3797 ((equal key "PROPERTY")
3798 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3799 (push (cons (match-string 1 value) (match-string 2 value))
3800 props)))
3801 ((equal key "FILETAGS")
3802 (when (string-match "\\S-" value)
3803 (setq ftags
3804 (append
3805 ftags
3806 (apply 'append
3807 (mapcar (lambda (x) (org-split-string x ":"))
3808 (org-split-string value)))))))
3809 ((equal key "DRAWERS")
3810 (setq drawers (org-split-string value splitre)))
3811 ((equal key "CONSTANTS")
3812 (setq const (append const (org-split-string value splitre))))
3813 ((equal key "STARTUP")
3814 (let ((opts (org-split-string value splitre))
3815 l var val)
3816 (while (setq l (pop opts))
3817 (when (setq l (assoc l org-startup-options))
3818 (setq var (nth 1 l) val (nth 2 l))
3819 (if (not (nth 3 l))
3820 (set (make-local-variable var) val)
3821 (if (not (listp (symbol-value var)))
3822 (set (make-local-variable var) nil))
3823 (set (make-local-variable var) (symbol-value var))
3824 (add-to-list var val))))))
3825 ((equal key "ARCHIVE")
3826 (string-match " *$" value)
3827 (setq arch (replace-match "" t t value))
3828 (remove-text-properties 0 (length arch)
3829 '(face t fontified t) arch))
3830 ((equal key "SETUPFILE")
3831 (setq setup-contents (org-file-contents
3832 (expand-file-name
3833 (org-remove-double-quotes value))
3834 'noerror))
3835 (if (not ext-setup-or-nil)
3836 (setq ext-setup-or-nil setup-contents start 0)
3837 (setq ext-setup-or-nil
3838 (concat (substring ext-setup-or-nil 0 start)
3839 "\n" setup-contents "\n"
3840 (substring ext-setup-or-nil start)))))
3841 ))))
3842 (when cat
3843 (org-set-local 'org-category (intern cat))
3844 (push (cons "CATEGORY" cat) props))
3845 (when prio
3846 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3847 (setq prio (mapcar 'string-to-char prio))
3848 (org-set-local 'org-highest-priority (nth 0 prio))
3849 (org-set-local 'org-lowest-priority (nth 1 prio))
3850 (org-set-local 'org-default-priority (nth 2 prio)))
3851 (and props (org-set-local 'org-file-properties (nreverse props)))
3852 (and ftags (org-set-local 'org-file-tags
3853 (mapcar 'org-add-prop-inherited ftags)))
3854 (and drawers (org-set-local 'org-drawers drawers))
3855 (and arch (org-set-local 'org-archive-location arch))
3856 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3857 ;; Process the TODO keywords
3858 (unless kwds
3859 ;; Use the global values as if they had been given locally.
3860 (setq kwds (default-value 'org-todo-keywords))
3861 (if (stringp (car kwds))
3862 (setq kwds (list (cons org-todo-interpretation
3863 (default-value 'org-todo-keywords)))))
3864 (setq kwds (reverse kwds)))
3865 (setq kwds (nreverse kwds))
3866 (let (inter kws kw)
3867 (while (setq kws (pop kwds))
3868 (let ((kws (or
3869 (run-hook-with-args-until-success
3870 'org-todo-setup-filter-hook kws)
3871 kws)))
3872 (setq inter (pop kws) sep (member "|" kws)
3873 kws0 (delete "|" (copy-sequence kws))
3874 kwsa nil
3875 kws1 (mapcar
3876 (lambda (x)
3877 ;; 1 2
3878 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3879 (progn
3880 (setq kw (match-string 1 x)
3881 key (and (match-end 2) (match-string 2 x))
3882 log (org-extract-log-state-settings x))
3883 (push (cons kw (and key (string-to-char key))) kwsa)
3884 (and log (push log org-todo-log-states))
3886 (error "Invalid TODO keyword %s" x)))
3887 kws0)
3888 kwsa (if kwsa (append '((:startgroup))
3889 (nreverse kwsa)
3890 '((:endgroup))))
3891 hw (car kws1)
3892 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3893 tail (list inter hw (car dws) (org-last dws))))
3894 (add-to-list 'org-todo-heads hw 'append)
3895 (push kws1 org-todo-sets)
3896 (setq org-done-keywords (append org-done-keywords dws nil))
3897 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3898 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3899 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3900 (setq org-todo-sets (nreverse org-todo-sets)
3901 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3902 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3903 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3904 ;; Process the constants
3905 (when const
3906 (let (e cst)
3907 (while (setq e (pop const))
3908 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3909 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3910 (setq org-table-formula-constants-local cst)))
3912 ;; Process the tags.
3913 (when tags
3914 (let (e tgs)
3915 (while (setq e (pop tags))
3916 (cond
3917 ((equal e "{") (push '(:startgroup) tgs))
3918 ((equal e "}") (push '(:endgroup) tgs))
3919 ((equal e "\\n") (push '(:newline) tgs))
3920 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3921 (push (cons (match-string 1 e)
3922 (string-to-char (match-string 2 e)))
3923 tgs))
3924 (t (push (list e) tgs))))
3925 (org-set-local 'org-tag-alist nil)
3926 (while (setq e (pop tgs))
3927 (or (and (stringp (car e))
3928 (assoc (car e) org-tag-alist))
3929 (push e org-tag-alist)))))
3931 ;; Compute the regular expressions and other local variables
3932 (if (not org-done-keywords)
3933 (setq org-done-keywords (and org-todo-keywords-1
3934 (list (org-last org-todo-keywords-1)))))
3935 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3936 (length org-scheduled-string)
3937 (length org-clock-string)
3938 (length org-closed-string)))
3939 org-drawer-regexp
3940 (concat "^[ \t]*:\\("
3941 (mapconcat 'regexp-quote org-drawers "\\|")
3942 "\\):[ \t]*$")
3943 org-not-done-keywords
3944 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3945 org-todo-regexp
3946 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3947 "\\|") "\\)\\>")
3948 org-not-done-regexp
3949 (concat "\\<\\("
3950 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3951 "\\)\\>")
3952 org-not-done-heading-regexp
3953 (concat "^\\(\\*+\\)[ \t]+\\("
3954 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3955 "\\)\\>")
3956 org-todo-line-regexp
3957 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3958 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3959 "\\)\\>\\)?[ \t]*\\(.*\\)")
3960 org-complex-heading-regexp
3961 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3962 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3963 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3964 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3965 org-complex-heading-regexp-format
3966 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3967 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3968 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3969 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3970 org-nl-done-regexp
3971 (concat "\n\\*+[ \t]+"
3972 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3973 "\\)" "\\>")
3974 org-todo-line-tags-regexp
3975 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3976 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3977 (org-re
3978 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3979 org-looking-at-done-regexp
3980 (concat "^" "\\(?:"
3981 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3982 "\\>")
3983 org-deadline-regexp (concat "\\<" org-deadline-string)
3984 org-deadline-time-regexp
3985 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3986 org-deadline-line-regexp
3987 (concat "\\<\\(" org-deadline-string "\\).*")
3988 org-scheduled-regexp
3989 (concat "\\<" org-scheduled-string)
3990 org-scheduled-time-regexp
3991 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3992 org-closed-time-regexp
3993 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3994 org-keyword-time-regexp
3995 (concat "\\<\\(" org-scheduled-string
3996 "\\|" org-deadline-string
3997 "\\|" org-closed-string
3998 "\\|" org-clock-string "\\)"
3999 " *[[<]\\([^]>]+\\)[]>]")
4000 org-keyword-time-not-clock-regexp
4001 (concat "\\<\\(" org-scheduled-string
4002 "\\|" org-deadline-string
4003 "\\|" org-closed-string
4004 "\\)"
4005 " *[[<]\\([^]>]+\\)[]>]")
4006 org-maybe-keyword-time-regexp
4007 (concat "\\(\\<\\(" org-scheduled-string
4008 "\\|" org-deadline-string
4009 "\\|" org-closed-string
4010 "\\|" org-clock-string "\\)\\)?"
4011 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4012 org-planning-or-clock-line-re
4013 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4014 "\\|" org-deadline-string
4015 "\\|" org-closed-string "\\|" org-clock-string
4016 "\\)\\>\\)")
4018 (org-compute-latex-and-specials-regexp)
4019 (org-set-font-lock-defaults))))
4021 (defun org-file-contents (file &optional noerror)
4022 "Return the contents of FILE, as a string."
4023 (if (or (not file)
4024 (not (file-readable-p file)))
4025 (if noerror
4026 (progn
4027 (message "Cannot read file %s" file)
4028 (ding) (sit-for 2)
4030 (error "Cannot read file %s" file))
4031 (with-temp-buffer
4032 (insert-file-contents file)
4033 (buffer-string))))
4035 (defun org-extract-log-state-settings (x)
4036 "Extract the log state setting from a TODO keyword string.
4037 This will extract info from a string like \"WAIT(w@/!)\"."
4038 (let (kw key log1 log2)
4039 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4040 (setq kw (match-string 1 x)
4041 key (and (match-end 2) (match-string 2 x))
4042 log1 (and (match-end 3) (match-string 3 x))
4043 log2 (and (match-end 4) (match-string 4 x)))
4044 (and (or log1 log2)
4045 (list kw
4046 (and log1 (if (equal log1 "!") 'time 'note))
4047 (and log2 (if (equal log2 "!") 'time 'note)))))))
4049 (defun org-remove-keyword-keys (list)
4050 "Remove a pair of parenthesis at the end of each string in LIST."
4051 (mapcar (lambda (x)
4052 (if (string-match "(.*)$" x)
4053 (substring x 0 (match-beginning 0))
4055 list))
4057 ;; FIXME: this could be done much better, using second characters etc.
4058 (defun org-assign-fast-keys (alist)
4059 "Assign fast keys to a keyword-key alist.
4060 Respect keys that are already there."
4061 (let (new e k c c1 c2 (char ?a))
4062 (while (setq e (pop alist))
4063 (cond
4064 ((equal e '(:startgroup)) (push e new))
4065 ((equal e '(:endgroup)) (push e new))
4066 ((equal e '(:newline)) (push e new))
4068 (setq k (car e) c2 nil)
4069 (if (cdr e)
4070 (setq c (cdr e))
4071 ;; automatically assign a character.
4072 (setq c1 (string-to-char
4073 (downcase (substring
4074 k (if (= (string-to-char k) ?@) 1 0)))))
4075 (if (or (rassoc c1 new) (rassoc c1 alist))
4076 (while (or (rassoc char new) (rassoc char alist))
4077 (setq char (1+ char)))
4078 (setq c2 c1))
4079 (setq c (or c2 char)))
4080 (push (cons k c) new))))
4081 (nreverse new)))
4083 ;;; Some variables used in various places
4085 (defvar org-window-configuration nil
4086 "Used in various places to store a window configuration.")
4087 (defvar org-selected-window nil
4088 "Used in various places to store a window configuration.")
4089 (defvar org-finish-function nil
4090 "Function to be called when `C-c C-c' is used.
4091 This is for getting out of special buffers like remember.")
4094 ;; FIXME: Occasionally check by commenting these, to make sure
4095 ;; no other functions uses these, forgetting to let-bind them.
4096 (defvar entry)
4097 (defvar last-state)
4098 (defvar date)
4100 ;; Defined somewhere in this file, but used before definition.
4101 (defvar org-html-entities)
4102 (defvar org-struct-menu)
4103 (defvar org-org-menu)
4104 (defvar org-tbl-menu)
4106 ;;;; Define the Org-mode
4108 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4109 (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."))
4112 ;; We use a before-change function to check if a table might need
4113 ;; an update.
4114 (defvar org-table-may-need-update t
4115 "Indicates that a table might need an update.
4116 This variable is set by `org-before-change-function'.
4117 `org-table-align' sets it back to nil.")
4118 (defun org-before-change-function (beg end)
4119 "Every change indicates that a table might need an update."
4120 (setq org-table-may-need-update t))
4121 (defvar org-mode-map)
4122 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4123 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4124 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4125 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4126 (defvar org-table-buffer-is-an nil)
4127 (defconst org-outline-regexp "\\*+ ")
4129 ;;;###autoload
4130 (define-derived-mode org-mode outline-mode "Org"
4131 "Outline-based notes management and organizer, alias
4132 \"Carsten's outline-mode for keeping track of everything.\"
4134 Org-mode develops organizational tasks around a NOTES file which
4135 contains information about projects as plain text. Org-mode is
4136 implemented on top of outline-mode, which is ideal to keep the content
4137 of large files well structured. It supports ToDo items, deadlines and
4138 time stamps, which magically appear in the diary listing of the Emacs
4139 calendar. Tables are easily created with a built-in table editor.
4140 Plain text URL-like links connect to websites, emails (VM), Usenet
4141 messages (Gnus), BBDB entries, and any files related to the project.
4142 For printing and sharing of notes, an Org-mode file (or a part of it)
4143 can be exported as a structured ASCII or HTML file.
4145 The following commands are available:
4147 \\{org-mode-map}"
4149 ;; Get rid of Outline menus, they are not needed
4150 ;; Need to do this here because define-derived-mode sets up
4151 ;; the keymap so late. Still, it is a waste to call this each time
4152 ;; we switch another buffer into org-mode.
4153 (if (featurep 'xemacs)
4154 (when (boundp 'outline-mode-menu-heading)
4155 ;; Assume this is Greg's port, it used easymenu
4156 (easy-menu-remove outline-mode-menu-heading)
4157 (easy-menu-remove outline-mode-menu-show)
4158 (easy-menu-remove outline-mode-menu-hide))
4159 (define-key org-mode-map [menu-bar headings] 'undefined)
4160 (define-key org-mode-map [menu-bar hide] 'undefined)
4161 (define-key org-mode-map [menu-bar show] 'undefined))
4163 (org-load-modules-maybe)
4164 (easy-menu-add org-org-menu)
4165 (easy-menu-add org-tbl-menu)
4166 (org-install-agenda-files-menu)
4167 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4168 (org-add-to-invisibility-spec '(org-cwidth))
4169 (org-add-to-invisibility-spec '(org-hide-block . t))
4170 (when (featurep 'xemacs)
4171 (org-set-local 'line-move-ignore-invisible t))
4172 (org-set-local 'outline-regexp org-outline-regexp)
4173 (org-set-local 'outline-level 'org-outline-level)
4174 (when (and org-ellipsis
4175 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4176 (fboundp 'make-glyph-code))
4177 (unless org-display-table
4178 (setq org-display-table (make-display-table)))
4179 (set-display-table-slot
4180 org-display-table 4
4181 (vconcat (mapcar
4182 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4183 org-ellipsis)))
4184 (if (stringp org-ellipsis) org-ellipsis "..."))))
4185 (setq buffer-display-table org-display-table))
4186 (org-set-regexps-and-options)
4187 (when (and org-tag-faces (not org-tags-special-faces-re))
4188 ;; tag faces set outside customize.... force initialization.
4189 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4190 ;; Calc embedded
4191 (org-set-local 'calc-embedded-open-mode "# ")
4192 (modify-syntax-entry ?# "<")
4193 (modify-syntax-entry ?@ "w")
4194 (if org-startup-truncated (setq truncate-lines t))
4195 (org-set-local 'font-lock-unfontify-region-function
4196 'org-unfontify-region)
4197 ;; Activate before-change-function
4198 (org-set-local 'org-table-may-need-update t)
4199 (org-add-hook 'before-change-functions 'org-before-change-function nil
4200 'local)
4201 ;; Check for running clock before killing a buffer
4202 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4203 ;; Paragraphs and auto-filling
4204 (org-set-autofill-regexps)
4205 (setq indent-line-function 'org-indent-line-function)
4206 (org-update-radio-target-regexp)
4207 ;; Make sure dependence stuff works reliably, even for users who set it
4208 ;; too late :-(
4209 (if org-enforce-todo-dependencies
4210 (add-hook 'org-blocker-hook
4211 'org-block-todo-from-children-or-siblings-or-parent)
4212 (remove-hook 'org-blocker-hook
4213 'org-block-todo-from-children-or-siblings-or-parent))
4214 (if org-enforce-todo-checkbox-dependencies
4215 (add-hook 'org-blocker-hook
4216 'org-block-todo-from-checkboxes)
4217 (remove-hook 'org-blocker-hook
4218 'org-block-todo-from-checkboxes))
4220 ;; Comment characters
4221 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4222 (org-set-local 'comment-padding " ")
4224 ;; Align options lines
4225 (org-set-local
4226 'align-mode-rules-list
4227 '((org-in-buffer-settings
4228 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4229 (modes . '(org-mode)))))
4231 ;; Imenu
4232 (org-set-local 'imenu-create-index-function
4233 'org-imenu-get-tree)
4235 ;; Make isearch reveal context
4236 (if (or (featurep 'xemacs)
4237 (not (boundp 'outline-isearch-open-invisible-function)))
4238 ;; Emacs 21 and XEmacs make use of the hook
4239 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4240 ;; Emacs 22 deals with this through a special variable
4241 (org-set-local 'outline-isearch-open-invisible-function
4242 (lambda (&rest ignore) (org-show-context 'isearch))))
4244 ;; If empty file that did not turn on org-mode automatically, make it to.
4245 (if (and org-insert-mode-line-in-empty-file
4246 (interactive-p)
4247 (= (point-min) (point-max)))
4248 (insert "# -*- mode: org -*-\n\n"))
4250 (unless org-inhibit-startup
4251 (when org-startup-align-all-tables
4252 (let ((bmp (buffer-modified-p)))
4253 (org-table-map-tables 'org-table-align)
4254 (set-buffer-modified-p bmp)))
4255 (when org-startup-indented
4256 (require 'org-indent)
4257 (org-indent-mode 1))
4258 (org-set-startup-visibility)))
4260 (when (fboundp 'abbrev-table-put)
4261 (abbrev-table-put org-mode-abbrev-table
4262 :parents (list text-mode-abbrev-table)))
4264 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4266 (defun org-current-time ()
4267 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4268 (if (> (car org-time-stamp-rounding-minutes) 1)
4269 (let ((r (car org-time-stamp-rounding-minutes))
4270 (time (decode-time)))
4271 (apply 'encode-time
4272 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4273 (nthcdr 2 time))))
4274 (current-time)))
4276 ;;;; Font-Lock stuff, including the activators
4278 (defvar org-mouse-map (make-sparse-keymap))
4279 (org-defkey org-mouse-map
4280 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4281 (org-defkey org-mouse-map
4282 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4283 (when org-mouse-1-follows-link
4284 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4285 (when org-tab-follows-link
4286 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4287 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4289 (require 'font-lock)
4291 (defconst org-non-link-chars "]\t\n\r<>")
4292 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4293 "shell" "elisp"))
4294 (defvar org-link-types-re nil
4295 "Matches a link that has a url-like prefix like \"http:\"")
4296 (defvar org-link-re-with-space nil
4297 "Matches a link with spaces, optional angular brackets around it.")
4298 (defvar org-link-re-with-space2 nil
4299 "Matches a link with spaces, optional angular brackets around it.")
4300 (defvar org-link-re-with-space3 nil
4301 "Matches a link with spaces, only for internal part in bracket links.")
4302 (defvar org-angle-link-re nil
4303 "Matches link with angular brackets, spaces are allowed.")
4304 (defvar org-plain-link-re nil
4305 "Matches plain link, without spaces.")
4306 (defvar org-bracket-link-regexp nil
4307 "Matches a link in double brackets.")
4308 (defvar org-bracket-link-analytic-regexp nil
4309 "Regular expression used to analyze links.
4310 Here is what the match groups contain after a match:
4311 1: http:
4312 2: http
4313 3: path
4314 4: [desc]
4315 5: desc")
4316 (defvar org-bracket-link-analytic-regexp++ nil
4317 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4318 (defvar org-any-link-re nil
4319 "Regular expression matching any link.")
4321 (defun org-make-link-regexps ()
4322 "Update the link regular expressions.
4323 This should be called after the variable `org-link-types' has changed."
4324 (setq org-link-types-re
4325 (concat
4326 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4327 org-link-re-with-space
4328 (concat
4329 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4330 "\\([^" org-non-link-chars " ]"
4331 "[^" org-non-link-chars "]*"
4332 "[^" org-non-link-chars " ]\\)>?")
4333 org-link-re-with-space2
4334 (concat
4335 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4336 "\\([^" org-non-link-chars " ]"
4337 "[^\t\n\r]*"
4338 "[^" org-non-link-chars " ]\\)>?")
4339 org-link-re-with-space3
4340 (concat
4341 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4342 "\\([^" org-non-link-chars " ]"
4343 "[^\t\n\r]*\\)")
4344 org-angle-link-re
4345 (concat
4346 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4347 "\\([^" org-non-link-chars " ]"
4348 "[^" org-non-link-chars "]*"
4349 "\\)>")
4350 org-plain-link-re
4351 (concat
4352 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4353 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4354 org-bracket-link-regexp
4355 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4356 org-bracket-link-analytic-regexp
4357 (concat
4358 "\\[\\["
4359 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4360 "\\([^]]+\\)"
4361 "\\]"
4362 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4363 "\\]")
4364 org-bracket-link-analytic-regexp++
4365 (concat
4366 "\\[\\["
4367 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4368 "\\([^]]+\\)"
4369 "\\]"
4370 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4371 "\\]")
4372 org-any-link-re
4373 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4374 org-angle-link-re "\\)\\|\\("
4375 org-plain-link-re "\\)")))
4377 (org-make-link-regexps)
4379 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4380 "Regular expression for fast time stamp matching.")
4381 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4382 "Regular expression for fast time stamp matching.")
4383 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4384 "Regular expression matching time strings for analysis.
4385 This one does not require the space after the date, so it can be used
4386 on a string that terminates immediately after the date.")
4387 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4388 "Regular expression matching time strings for analysis.")
4389 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4390 "Regular expression matching time stamps, with groups.")
4391 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4392 "Regular expression matching time stamps (also [..]), with groups.")
4393 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4394 "Regular expression matching a time stamp range.")
4395 (defconst org-tr-regexp-both
4396 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4397 "Regular expression matching a time stamp range.")
4398 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4399 org-ts-regexp "\\)?")
4400 "Regular expression matching a time stamp or time stamp range.")
4401 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4402 org-ts-regexp-both "\\)?")
4403 "Regular expression matching a time stamp or time stamp range.
4404 The time stamps may be either active or inactive.")
4406 (defvar org-emph-face nil)
4408 (defun org-do-emphasis-faces (limit)
4409 "Run through the buffer and add overlays to links."
4410 (let (rtn a)
4411 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4412 (if (not (= (char-after (match-beginning 3))
4413 (char-after (match-beginning 4))))
4414 (progn
4415 (setq rtn t)
4416 (setq a (assoc (match-string 3) org-emphasis-alist))
4417 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4418 'face
4419 (nth 1 a))
4420 (and (nth 4 a)
4421 (org-remove-flyspell-overlays-in
4422 (match-beginning 0) (match-end 0)))
4423 (add-text-properties (match-beginning 2) (match-end 2)
4424 '(font-lock-multiline t))
4425 (when org-hide-emphasis-markers
4426 (add-text-properties (match-end 4) (match-beginning 5)
4427 '(invisible org-link))
4428 (add-text-properties (match-beginning 3) (match-end 3)
4429 '(invisible org-link)))))
4430 (backward-char 1))
4431 rtn))
4433 (defun org-emphasize (&optional char)
4434 "Insert or change an emphasis, i.e. a font like bold or italic.
4435 If there is an active region, change that region to a new emphasis.
4436 If there is no region, just insert the marker characters and position
4437 the cursor between them.
4438 CHAR should be either the marker character, or the first character of the
4439 HTML tag associated with that emphasis. If CHAR is a space, the means
4440 to remove the emphasis of the selected region.
4441 If char is not given (for example in an interactive call) it
4442 will be prompted for."
4443 (interactive)
4444 (let ((eal org-emphasis-alist) e det
4445 (erc org-emphasis-regexp-components)
4446 (prompt "")
4447 (string "") beg end move tag c s)
4448 (if (org-region-active-p)
4449 (setq beg (region-beginning) end (region-end)
4450 string (buffer-substring beg end))
4451 (setq move t))
4453 (while (setq e (pop eal))
4454 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4455 c (aref tag 0))
4456 (push (cons c (string-to-char (car e))) det)
4457 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4458 (substring tag 1)))))
4459 (setq det (nreverse det))
4460 (unless char
4461 (message "%s" (concat "Emphasis marker or tag:" prompt))
4462 (setq char (read-char-exclusive)))
4463 (setq char (or (cdr (assoc char det)) char))
4464 (if (equal char ?\ )
4465 (setq s "" move nil)
4466 (unless (assoc (char-to-string char) org-emphasis-alist)
4467 (error "No such emphasis marker: \"%c\"" char))
4468 (setq s (char-to-string char)))
4469 (while (and (> (length string) 1)
4470 (equal (substring string 0 1) (substring string -1))
4471 (assoc (substring string 0 1) org-emphasis-alist))
4472 (setq string (substring string 1 -1)))
4473 (setq string (concat s string s))
4474 (if beg (delete-region beg end))
4475 (unless (or (bolp)
4476 (string-match (concat "[" (nth 0 erc) "\n]")
4477 (char-to-string (char-before (point)))))
4478 (insert " "))
4479 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4480 (char-to-string (char-after (point))))
4481 (insert " ") (backward-char 1))
4482 (insert string)
4483 (and move (backward-char 1))))
4485 (defconst org-nonsticky-props
4486 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4488 (defsubst org-rear-nonsticky-at (pos)
4489 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4491 (defun org-activate-plain-links (limit)
4492 "Run through the buffer and add overlays to links."
4493 (catch 'exit
4494 (let (f)
4495 (if (re-search-forward org-plain-link-re limit t)
4496 (progn
4497 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4498 (setq f (get-text-property (match-beginning 0) 'face))
4499 (if (or (eq f 'org-tag)
4500 (and (listp f) (memq 'org-tag f)))
4502 (add-text-properties (match-beginning 0) (match-end 0)
4503 (list 'mouse-face 'highlight
4504 'keymap org-mouse-map))
4505 (org-rear-nonsticky-at (match-end 0)))
4506 t)))))
4508 (defun org-activate-code (limit)
4509 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4510 (progn
4511 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4512 (remove-text-properties (match-beginning 0) (match-end 0)
4513 '(display t invisible t intangible t))
4514 t)))
4516 (defun org-fontify-meta-lines-and-blocks (limit)
4517 "Fontify #+ lines and blocks, in the correct ways."
4518 (let ((case-fold-search t))
4519 (if (re-search-forward
4520 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4521 limit t)
4522 (let ((beg (match-beginning 0))
4523 (beg1 (line-beginning-position 2))
4524 (dc1 (downcase (match-string 2)))
4525 (dc3 (downcase (match-string 3)))
4526 end end1 quoting)
4527 (cond
4528 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4529 ;; a single line of backend-specific content
4530 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4531 (remove-text-properties (match-beginning 0) (match-end 0)
4532 '(display t invisible t intangible t))
4533 (add-text-properties (match-beginning 1) (match-end 3)
4534 '(font-lock-fontified t face org-meta-line))
4535 (add-text-properties (match-beginning 6) (match-end 6)
4536 '(font-lock-fontified t face org-block))
4538 ((and (match-end 4) (equal dc3 "begin"))
4539 ;; Truely a block
4540 (setq quoting (member (downcase (match-string 5))
4541 org-protecting-blocks))
4542 (when (re-search-forward
4543 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4544 nil t) ;; on purpose, we look further than LIMIT
4545 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4546 (when quoting
4547 (remove-text-properties beg end
4548 '(display t invisible t intangible t)))
4549 (add-text-properties
4550 beg end
4551 '(font-lock-fontified t font-lock-multiline t))
4552 (add-text-properties beg beg1 '(face org-meta-line))
4553 (add-text-properties end1 end '(face org-meta-line))
4554 (when quoting
4555 (add-text-properties beg1 end1 '(face org-block)))
4557 ((not (member (char-after beg) '(?\ ?\t)))
4558 ;; just any other in-buffer setting, but not indented
4559 (add-text-properties
4560 beg (match-end 0)
4561 '(font-lock-fontified t face org-meta-line))
4563 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4564 "orgtbl:" "tblfm:" "tblname:"))
4565 (and (match-end 4) (equal dc3 "attr")))
4566 (add-text-properties
4567 beg (match-end 0)
4568 '(font-lock-fontified t face org-meta-line))
4570 ((member dc3 '(" " ""))
4571 (add-text-properties
4572 beg (match-end 0)
4573 '(font-lock-fontified t face font-lock-comment-face)))
4574 (t nil))))))
4576 (defun org-activate-angle-links (limit)
4577 "Run through the buffer and add overlays to links."
4578 (if (re-search-forward org-angle-link-re limit t)
4579 (progn
4580 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4581 (add-text-properties (match-beginning 0) (match-end 0)
4582 (list 'mouse-face 'highlight
4583 'keymap org-mouse-map))
4584 (org-rear-nonsticky-at (match-end 0))
4585 t)))
4587 (defun org-activate-footnote-links (limit)
4588 "Run through the buffer and add overlays to links."
4589 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4590 limit t)
4591 (progn
4592 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4593 (add-text-properties (match-beginning 2) (match-end 2)
4594 (list 'mouse-face 'highlight
4595 'keymap org-mouse-map
4596 'help-echo
4597 (if (= (point-at-bol) (match-beginning 2))
4598 "Footnote definition"
4599 "Footnote reference")
4601 (org-rear-nonsticky-at (match-end 2))
4602 t)))
4604 (defun org-activate-bracket-links (limit)
4605 "Run through the buffer and add overlays to bracketed links."
4606 (if (re-search-forward org-bracket-link-regexp limit t)
4607 (let* ((help (concat "LINK: "
4608 (org-match-string-no-properties 1)))
4609 ;; FIXME: above we should remove the escapes.
4610 ;; but that requires another match, protecting match data,
4611 ;; a lot of overhead for font-lock.
4612 (ip (org-maybe-intangible
4613 (list 'invisible 'org-link
4614 'keymap org-mouse-map 'mouse-face 'highlight
4615 'font-lock-multiline t 'help-echo help)))
4616 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4617 'font-lock-multiline t 'help-echo help)))
4618 ;; We need to remove the invisible property here. Table narrowing
4619 ;; may have made some of this invisible.
4620 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4621 (remove-text-properties (match-beginning 0) (match-end 0)
4622 '(invisible nil))
4623 (if (match-end 3)
4624 (progn
4625 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4626 (org-rear-nonsticky-at (match-beginning 3))
4627 (add-text-properties (match-beginning 3) (match-end 3) vp)
4628 (org-rear-nonsticky-at (match-end 3))
4629 (add-text-properties (match-end 3) (match-end 0) ip)
4630 (org-rear-nonsticky-at (match-end 0)))
4631 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4632 (org-rear-nonsticky-at (match-beginning 1))
4633 (add-text-properties (match-beginning 1) (match-end 1) vp)
4634 (org-rear-nonsticky-at (match-end 1))
4635 (add-text-properties (match-end 1) (match-end 0) ip)
4636 (org-rear-nonsticky-at (match-end 0)))
4637 t)))
4639 (defun org-activate-dates (limit)
4640 "Run through the buffer and add overlays to dates."
4641 (if (re-search-forward org-tsr-regexp-both limit t)
4642 (progn
4643 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4644 (add-text-properties (match-beginning 0) (match-end 0)
4645 (list 'mouse-face 'highlight
4646 'keymap org-mouse-map))
4647 (org-rear-nonsticky-at (match-end 0))
4648 (when org-display-custom-times
4649 (if (match-end 3)
4650 (org-display-custom-time (match-beginning 3) (match-end 3)))
4651 (org-display-custom-time (match-beginning 1) (match-end 1)))
4652 t)))
4654 (defvar org-target-link-regexp nil
4655 "Regular expression matching radio targets in plain text.")
4656 (make-variable-buffer-local 'org-target-link-regexp)
4657 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4658 "Regular expression matching a link target.")
4659 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4660 "Regular expression matching a radio target.")
4661 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4662 "Regular expression matching any target.")
4664 (defun org-activate-target-links (limit)
4665 "Run through the buffer and add overlays to target matches."
4666 (when org-target-link-regexp
4667 (let ((case-fold-search t))
4668 (if (re-search-forward org-target-link-regexp limit t)
4669 (progn
4670 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4671 (add-text-properties (match-beginning 0) (match-end 0)
4672 (list 'mouse-face 'highlight
4673 'keymap org-mouse-map
4674 'help-echo "Radio target link"
4675 'org-linked-text t))
4676 (org-rear-nonsticky-at (match-end 0))
4677 t)))))
4679 (defun org-update-radio-target-regexp ()
4680 "Find all radio targets in this file and update the regular expression."
4681 (interactive)
4682 (when (memq 'radio org-activate-links)
4683 (setq org-target-link-regexp
4684 (org-make-target-link-regexp (org-all-targets 'radio)))
4685 (org-restart-font-lock)))
4687 (defun org-hide-wide-columns (limit)
4688 (let (s e)
4689 (setq s (text-property-any (point) (or limit (point-max))
4690 'org-cwidth t))
4691 (when s
4692 (setq e (next-single-property-change s 'org-cwidth))
4693 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4694 (goto-char e)
4695 t)))
4697 (defvar org-latex-and-specials-regexp nil
4698 "Regular expression for highlighting export special stuff.")
4699 (defvar org-match-substring-regexp)
4700 (defvar org-match-substring-with-braces-regexp)
4702 ;; This should be with the exporter code, but we also use if for font-locking
4703 (defconst org-export-html-special-string-regexps
4704 '(("\\\\-" . "&shy;")
4705 ("---\\([^-]\\)" . "&mdash;\\1")
4706 ("--\\([^-]\\)" . "&ndash;\\1")
4707 ("\\.\\.\\." . "&hellip;"))
4708 "Regular expressions for special string conversion.")
4711 (defun org-compute-latex-and-specials-regexp ()
4712 "Compute regular expression for stuff treated specially by exporters."
4713 (if (not org-highlight-latex-fragments-and-specials)
4714 (org-set-local 'org-latex-and-specials-regexp nil)
4715 (require 'org-exp)
4716 (let*
4717 ((matchers (plist-get org-format-latex-options :matchers))
4718 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4719 org-latex-regexps)))
4720 (options (org-combine-plists (org-default-export-plist)
4721 (org-infile-export-plist)))
4722 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4723 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4724 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4725 (org-export-html-expand (plist-get options :expand-quoted-html))
4726 (org-export-with-special-strings (plist-get options :special-strings))
4727 (re-sub
4728 (cond
4729 ((equal org-export-with-sub-superscripts '{})
4730 (list org-match-substring-with-braces-regexp))
4731 (org-export-with-sub-superscripts
4732 (list org-match-substring-regexp))
4733 (t nil)))
4734 (re-latex
4735 (if org-export-with-LaTeX-fragments
4736 (mapcar (lambda (x) (nth 1 x)) latexs)))
4737 (re-macros
4738 (if org-export-with-TeX-macros
4739 (list (concat "\\\\"
4740 (regexp-opt
4741 (append (mapcar 'car org-html-entities)
4742 (if (boundp 'org-latex-entities)
4743 (mapcar (lambda (x)
4744 (or (car-safe x) x))
4745 org-latex-entities)
4746 nil))
4747 'words))) ; FIXME
4749 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4750 (re-special (if org-export-with-special-strings
4751 (mapcar (lambda (x) (car x))
4752 org-export-html-special-string-regexps)))
4753 (re-rest
4754 (delq nil
4755 (list
4756 (if org-export-html-expand "@<[^>\n]+>")
4757 ))))
4758 (org-set-local
4759 'org-latex-and-specials-regexp
4760 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4761 re-rest) "\\|")))))
4763 (defun org-do-latex-and-special-faces (limit)
4764 "Run through the buffer and add overlays to links."
4765 (when org-latex-and-specials-regexp
4766 (let (rtn d)
4767 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4768 limit t))
4769 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4770 'face))
4771 '(org-code org-verbatim underline)))
4772 (progn
4773 (setq rtn t
4774 d (cond ((member (char-after (1+ (match-beginning 0)))
4775 '(?_ ?^)) 1)
4776 (t 0)))
4777 (font-lock-prepend-text-property
4778 (+ d (match-beginning 0)) (match-end 0)
4779 'face 'org-latex-and-export-specials)
4780 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4781 '(font-lock-multiline t)))))
4782 rtn)))
4784 (defun org-restart-font-lock ()
4785 "Restart font-lock-mode, to force refontification."
4786 (when (and (boundp 'font-lock-mode) font-lock-mode)
4787 (font-lock-mode -1)
4788 (font-lock-mode 1)))
4790 (defun org-all-targets (&optional radio)
4791 "Return a list of all targets in this file.
4792 With optional argument RADIO, only find radio targets."
4793 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4794 rtn)
4795 (save-excursion
4796 (goto-char (point-min))
4797 (while (re-search-forward re nil t)
4798 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4799 rtn)))
4801 (defun org-make-target-link-regexp (targets)
4802 "Make regular expression matching all strings in TARGETS.
4803 The regular expression finds the targets also if there is a line break
4804 between words."
4805 (and targets
4806 (concat
4807 "\\<\\("
4808 (mapconcat
4809 (lambda (x)
4810 (while (string-match " +" x)
4811 (setq x (replace-match "\\s-+" t t x)))
4813 targets
4814 "\\|")
4815 "\\)\\>")))
4817 (defun org-activate-tags (limit)
4818 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4819 (progn
4820 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4821 (add-text-properties (match-beginning 1) (match-end 1)
4822 (list 'mouse-face 'highlight
4823 'keymap org-mouse-map))
4824 (org-rear-nonsticky-at (match-end 1))
4825 t)))
4827 (defun org-outline-level ()
4828 "Compute the outline level of the heading at point.
4829 This function assumes that the cursor is at the beginning of a line matched
4830 by outline-regexp. Otherwise it returns garbage.
4831 If this is called at a normal headline, the level is the number of stars.
4832 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4833 For plain list items, if they are matched by `outline-regexp', this returns
4834 1000 plus the line indentation."
4835 (save-excursion
4836 (looking-at outline-regexp)
4837 (if (match-beginning 1)
4838 (+ (org-get-string-indentation (match-string 1)) 1000)
4839 (1- (- (match-end 0) (match-beginning 0))))))
4841 (defvar org-font-lock-keywords nil)
4843 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4844 "Regular expression matching a property line.")
4846 (defvar org-font-lock-hook nil
4847 "Functions to be called for special font lock stuff.")
4849 (defun org-font-lock-hook (limit)
4850 (run-hook-with-args 'org-font-lock-hook limit))
4852 (defun org-set-font-lock-defaults ()
4853 (let* ((em org-fontify-emphasized-text)
4854 (lk org-activate-links)
4855 (org-font-lock-extra-keywords
4856 (list
4857 ;; Call the hook
4858 '(org-font-lock-hook)
4859 ;; Headlines
4860 `(,(if org-fontify-whole-heading-line
4861 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4862 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4863 (1 (org-get-level-face 1))
4864 (2 (org-get-level-face 2))
4865 (3 (org-get-level-face 3)))
4866 ;; Table lines
4867 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4868 (1 'org-table t))
4869 ;; Table internals
4870 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4871 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4872 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4873 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4874 ;; Drawers
4875 (list org-drawer-regexp '(0 'org-special-keyword t))
4876 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4877 ;; Properties
4878 (list org-property-re
4879 '(1 'org-special-keyword t)
4880 '(3 'org-property-value t))
4881 ;; Links
4882 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4883 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4884 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4885 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4886 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4887 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4888 (if (memq 'footnote lk) '(org-activate-footnote-links
4889 (2 'org-footnote t)))
4890 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4891 '(org-hide-wide-columns (0 nil append))
4892 ;; TODO lines
4893 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4894 '(1 (org-get-todo-face 1) t))
4895 ;; DONE
4896 (if org-fontify-done-headline
4897 (list (concat "^[*]+ +\\<\\("
4898 (mapconcat 'regexp-quote org-done-keywords "\\|")
4899 "\\)\\(.*\\)")
4900 '(2 'org-headline-done t))
4901 nil)
4902 ;; Priorities
4903 '(org-font-lock-add-priority-faces)
4904 ;; Tags
4905 '(org-font-lock-add-tag-faces)
4906 ;; Special keywords
4907 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4908 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4909 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4910 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4911 ;; Emphasis
4912 (if em
4913 (if (featurep 'xemacs)
4914 '(org-do-emphasis-faces (0 nil append))
4915 '(org-do-emphasis-faces)))
4916 ;; Checkboxes
4917 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4918 2 'org-checkbox prepend)
4919 (if org-provide-checkbox-statistics
4920 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4921 (0 (org-get-checkbox-statistics-face) t)))
4922 ;; Description list items
4923 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4924 2 'bold prepend)
4925 ;; ARCHIVEd headings
4926 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4927 '(1 'org-archived prepend))
4928 ;; Specials
4929 '(org-do-latex-and-special-faces)
4930 ;; Code
4931 '(org-activate-code (1 'org-code t))
4932 ;; COMMENT
4933 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4934 "\\|" org-quote-string "\\)\\>")
4935 '(1 'org-special-keyword t))
4936 '("^#.*" (0 'font-lock-comment-face t))
4937 ;; Blocks and meta lines
4938 '(org-fontify-meta-lines-and-blocks)
4940 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4941 ;; Now set the full font-lock-keywords
4942 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4943 (org-set-local 'font-lock-defaults
4944 '(org-font-lock-keywords t nil nil backward-paragraph))
4945 (kill-local-variable 'font-lock-keywords) nil))
4947 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4948 "Fontify string S like in Org-mode"
4949 (with-temp-buffer
4950 (insert s)
4951 (let ((org-odd-levels-only odd-levels))
4952 (org-mode)
4953 (font-lock-fontify-buffer)
4954 (buffer-string))))
4956 (defvar org-m nil)
4957 (defvar org-l nil)
4958 (defvar org-f nil)
4959 (defun org-get-level-face (n)
4960 "Get the right face for match N in font-lock matching of headlines."
4961 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4962 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4963 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4964 (cond
4965 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4966 ((eq n 2) org-f)
4967 (t (if org-level-color-stars-only nil org-f))))
4969 (defun org-get-todo-face (kwd)
4970 "Get the right face for a TODO keyword KWD.
4971 If KWD is a number, get the corresponding match group."
4972 (if (numberp kwd) (setq kwd (match-string kwd)))
4973 (or (cdr (assoc kwd org-todo-keyword-faces))
4974 (and (member kwd org-done-keywords) 'org-done)
4975 'org-todo))
4977 (defun org-font-lock-add-tag-faces (limit)
4978 "Add the special tag faces."
4979 (when (and org-tag-faces org-tags-special-faces-re)
4980 (while (re-search-forward org-tags-special-faces-re limit t)
4981 (add-text-properties (match-beginning 1) (match-end 1)
4982 (list 'face (org-get-tag-face 1)
4983 'font-lock-fontified t))
4984 (backward-char 1))))
4986 (defun org-font-lock-add-priority-faces (limit)
4987 "Add the special priority faces."
4988 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4989 (add-text-properties
4990 (match-beginning 0) (match-end 0)
4991 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4992 org-priority-faces))
4993 'org-special-keyword)
4994 'font-lock-fontified t))))
4996 (defun org-get-tag-face (kwd)
4997 "Get the right face for a TODO keyword KWD.
4998 If KWD is a number, get the corresponding match group."
4999 (if (numberp kwd) (setq kwd (match-string kwd)))
5000 (or (cdr (assoc kwd org-tag-faces))
5001 'org-tag))
5003 (defun org-unfontify-region (beg end &optional maybe_loudly)
5004 "Remove fontification and activation overlays from links."
5005 (font-lock-default-unfontify-region beg end)
5006 (let* ((buffer-undo-list t)
5007 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5008 (inhibit-modification-hooks t)
5009 deactivate-mark buffer-file-name buffer-file-truename)
5010 (remove-text-properties
5011 beg end
5012 (if org-indent-mode
5013 ;; also remove line-prefix and wrap-prefix properties
5014 '(mouse-face t keymap t org-linked-text t
5015 invisible t intangible t
5016 line-prefix t wrap-prefix t
5017 org-no-flyspell t)
5018 '(mouse-face t keymap t org-linked-text t
5019 invisible t intangible t
5020 org-no-flyspell t)))))
5022 ;;;; Visibility cycling, including org-goto and indirect buffer
5024 ;;; Cycling
5026 (defvar org-cycle-global-status nil)
5027 (make-variable-buffer-local 'org-cycle-global-status)
5028 (defvar org-cycle-subtree-status nil)
5029 (make-variable-buffer-local 'org-cycle-subtree-status)
5031 ;;;###autoload
5033 (defvar org-inlinetask-min-level)
5035 (defun org-cycle (&optional arg)
5036 "TAB-action and visibility cycling for Org-mode.
5038 This is the command invoked in Org-mode by the TAB key. Its main purpose
5039 is outline visibility cycling, but it also invokes other actions
5040 in special contexts.
5042 - When this function is called with a prefix argument, rotate the entire
5043 buffer through 3 states (global cycling)
5044 1. OVERVIEW: Show only top-level headlines.
5045 2. CONTENTS: Show all headlines of all levels, but no body text.
5046 3. SHOW ALL: Show everything.
5047 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5048 determined by the variable `org-startup-folded', and by any VISIBILITY
5049 properties in the buffer.
5050 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5051 including any drawers.
5053 - When inside a table, re-align the table and move to the next field.
5055 - When point is at the beginning of a headline, rotate the subtree started
5056 by this line through 3 different states (local cycling)
5057 1. FOLDED: Only the main headline is shown.
5058 2. CHILDREN: The main headline and the direct children are shown.
5059 From this state, you can move to one of the children
5060 and zoom in further.
5061 3. SUBTREE: Show the entire subtree, including body text.
5062 If there is no subtree, switch directly from CHILDREN to FOLDED.
5064 - When there is a numeric prefix, go up to a heading with level ARG, do
5065 a `show-subtree' and return to the previous cursor position. If ARG
5066 is negative, go up that many levels.
5068 - When point is not at the beginning of a headline, execute the global
5069 binding for TAB, which is re-indenting the line. See the option
5070 `org-cycle-emulate-tab' for details.
5072 - Special case: if point is at the beginning of the buffer and there is
5073 no headline in line 1, this function will act as if called with prefix arg.
5074 But only if also the variable `org-cycle-global-at-bob' is t."
5075 (interactive "P")
5076 (org-load-modules-maybe)
5077 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5078 (and org-cycle-level-after-item/entry-creation
5079 (or (org-cycle-level)
5080 (org-cycle-item-indentation))))
5081 (let* ((limit-level
5082 (or org-cycle-max-level
5083 (and (boundp 'org-inlinetask-min-level)
5084 org-inlinetask-min-level
5085 (1- org-inlinetask-min-level))))
5086 (nstars (and limit-level
5087 (if org-odd-levels-only
5088 (and limit-level (1- (* limit-level 2)))
5089 limit-level)))
5090 (outline-regexp
5091 (cond
5092 ((not (org-mode-p)) outline-regexp)
5093 ((or (eq org-cycle-include-plain-lists 'integrate)
5094 (and org-cycle-include-plain-lists (org-at-item-p)))
5095 (concat "\\(?:\\*"
5096 (if nstars (format "\\{1,%d\\}" nstars) "+")
5097 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5098 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5099 (bob-special (and org-cycle-global-at-bob (bobp)
5100 (not (looking-at outline-regexp))))
5101 (org-cycle-hook
5102 (if bob-special
5103 (delq 'org-optimize-window-after-visibility-change
5104 (copy-sequence org-cycle-hook))
5105 org-cycle-hook))
5106 (pos (point)))
5108 (if (or bob-special (equal arg '(4)))
5109 ;; special case: use global cycling
5110 (setq arg t))
5112 (cond
5114 ((equal arg '(16))
5115 (org-set-startup-visibility)
5116 (message "Startup visibility, plus VISIBILITY properties"))
5118 ((equal arg '(64))
5119 (show-all)
5120 (message "Entire buffer visible, including drawers"))
5122 ((org-at-table-p 'any)
5123 ;; Enter the table or move to the next field in the table
5124 (or (org-table-recognize-table.el)
5125 (progn
5126 (if arg (org-table-edit-field t)
5127 (org-table-justify-field-maybe)
5128 (call-interactively 'org-table-next-field)))))
5130 ((run-hook-with-args-until-success
5131 'org-tab-after-check-for-table-hook))
5133 ((eq arg t) ;; Global cycling
5134 (org-cycle-internal-global))
5136 ((and org-drawers org-drawer-regexp
5137 (save-excursion
5138 (beginning-of-line 1)
5139 (looking-at org-drawer-regexp)))
5140 ;; Toggle block visibility
5141 (org-flag-drawer
5142 (not (get-char-property (match-end 0) 'invisible))))
5144 ((integerp arg)
5145 ;; Show-subtree, ARG levels up from here.
5146 (save-excursion
5147 (org-back-to-heading)
5148 (outline-up-heading (if (< arg 0) (- arg)
5149 (- (funcall outline-level) arg)))
5150 (org-show-subtree)))
5152 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5153 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5155 (org-cycle-internal-local))
5157 ;; TAB emulation and template completion
5158 (buffer-read-only (org-back-to-heading))
5160 ((run-hook-with-args-until-success
5161 'org-tab-after-check-for-cycling-hook))
5163 ((org-try-structure-completion))
5165 ((org-try-cdlatex-tab))
5167 ((run-hook-with-args-until-success
5168 'org-tab-before-tab-emulation-hook))
5170 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5171 (or (not (bolp))
5172 (not (looking-at outline-regexp))))
5173 (call-interactively (global-key-binding "\t")))
5175 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5176 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5177 (or (and (eq org-cycle-emulate-tab 'white)
5178 (= (match-end 0) (point-at-eol)))
5179 (and (eq org-cycle-emulate-tab 'whitestart)
5180 (>= (match-end 0) pos))))
5182 (eq org-cycle-emulate-tab t))
5183 (call-interactively (global-key-binding "\t")))
5185 (t (save-excursion
5186 (org-back-to-heading)
5187 (org-cycle)))))))
5189 (defun org-cycle-internal-global ()
5190 "Do the global cycling action."
5191 (cond
5192 ((and (eq last-command this-command)
5193 (eq org-cycle-global-status 'overview))
5194 ;; We just created the overview - now do table of contents
5195 ;; This can be slow in very large buffers, so indicate action
5196 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5197 (message "CONTENTS...")
5198 (org-content)
5199 (message "CONTENTS...done")
5200 (setq org-cycle-global-status 'contents)
5201 (run-hook-with-args 'org-cycle-hook 'contents))
5203 ((and (eq last-command this-command)
5204 (eq org-cycle-global-status 'contents))
5205 ;; We just showed the table of contents - now show everything
5206 (run-hook-with-args 'org-pre-cycle-hook 'all)
5207 (show-all)
5208 (message "SHOW ALL")
5209 (setq org-cycle-global-status 'all)
5210 (run-hook-with-args 'org-cycle-hook 'all))
5213 ;; Default action: go to overview
5214 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5215 (org-overview)
5216 (message "OVERVIEW")
5217 (setq org-cycle-global-status 'overview)
5218 (run-hook-with-args 'org-cycle-hook 'overview))))
5220 (defun org-cycle-internal-local ()
5221 "Do the local cycling action."
5222 (org-back-to-heading)
5223 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5224 ;; First, some boundaries
5225 (save-excursion
5226 (org-back-to-heading)
5227 (setq level (funcall outline-level))
5228 (save-excursion
5229 (beginning-of-line 2)
5230 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5231 ; XEmacs does not have `next-single-char-property-change'
5232 ; I'm not sure about Emacs 21.
5233 (while (and (not (eobp)) ;; this is like `next-line'
5234 (get-char-property (1- (point)) 'invisible))
5235 (beginning-of-line 2))
5236 (while (and (not (eobp)) ;; this is like `next-line'
5237 (get-char-property (1- (point)) 'invisible))
5238 (goto-char (next-single-char-property-change (point) 'invisible))
5239 ;;;??? (or (bolp) (beginning-of-line 2))))
5240 (and (eolp) (beginning-of-line 2))))
5241 (setq eol (point)))
5242 (outline-end-of-heading) (setq eoh (point))
5243 (save-excursion
5244 (outline-next-heading)
5245 (setq has-children (and (org-at-heading-p t)
5246 (> (funcall outline-level) level))))
5247 (org-end-of-subtree t)
5248 (unless (eobp)
5249 (skip-chars-forward " \t\n")
5250 (beginning-of-line 1) ; in case this is an item
5252 (setq eos (if (eobp) (point) (1- (point)))))
5253 ;; Find out what to do next and set `this-command'
5254 (cond
5255 ((= eos eoh)
5256 ;; Nothing is hidden behind this heading
5257 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5258 (message "EMPTY ENTRY")
5259 (setq org-cycle-subtree-status nil)
5260 (save-excursion
5261 (goto-char eos)
5262 (outline-next-heading)
5263 (if (org-invisible-p) (org-flag-heading nil))))
5264 ((and (or (>= eol eos)
5265 (not (string-match "\\S-" (buffer-substring eol eos))))
5266 (or has-children
5267 (not (setq children-skipped
5268 org-cycle-skip-children-state-if-no-children))))
5269 ;; Entire subtree is hidden in one line: children view
5270 (run-hook-with-args 'org-pre-cycle-hook 'children)
5271 (org-show-entry)
5272 (show-children)
5273 (message "CHILDREN")
5274 (save-excursion
5275 (goto-char eos)
5276 (outline-next-heading)
5277 (if (org-invisible-p) (org-flag-heading nil)))
5278 (setq org-cycle-subtree-status 'children)
5279 (run-hook-with-args 'org-cycle-hook 'children))
5280 ((or children-skipped
5281 (and (eq last-command this-command)
5282 (eq org-cycle-subtree-status 'children)))
5283 ;; We just showed the children, or no children are there,
5284 ;; now show everything.
5285 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5286 (org-show-subtree)
5287 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5288 (setq org-cycle-subtree-status 'subtree)
5289 (run-hook-with-args 'org-cycle-hook 'subtree))
5291 ;; Default action: hide the subtree.
5292 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5293 (hide-subtree)
5294 (message "FOLDED")
5295 (setq org-cycle-subtree-status 'folded)
5296 (run-hook-with-args 'org-cycle-hook 'folded)))))
5298 ;;;###autoload
5299 (defun org-global-cycle (&optional arg)
5300 "Cycle the global visibility. For details see `org-cycle'.
5301 With C-u prefix arg, switch to startup visibility.
5302 With a numeric prefix, show all headlines up to that level."
5303 (interactive "P")
5304 (let ((org-cycle-include-plain-lists
5305 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5306 (cond
5307 ((integerp arg)
5308 (show-all)
5309 (hide-sublevels arg)
5310 (setq org-cycle-global-status 'contents))
5311 ((equal arg '(4))
5312 (org-set-startup-visibility)
5313 (message "Startup visibility, plus VISIBILITY properties."))
5315 (org-cycle '(4))))))
5317 (defun org-set-startup-visibility ()
5318 "Set the visibility required by startup options and properties."
5319 (cond
5320 ((eq org-startup-folded t)
5321 (org-cycle '(4)))
5322 ((eq org-startup-folded 'content)
5323 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5324 (org-cycle '(4)) (org-cycle '(4)))))
5325 (unless (eq org-startup-folded 'showeverything)
5326 (if org-hide-block-startup (org-hide-block-all))
5327 (org-set-visibility-according-to-property 'no-cleanup)
5328 (org-cycle-hide-archived-subtrees 'all)
5329 (org-cycle-hide-drawers 'all)
5330 (org-cycle-show-empty-lines 'all)))
5332 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5333 "Switch subtree visibilities according to :VISIBILITY: property."
5334 (interactive)
5335 (let (org-show-entry-below state)
5336 (save-excursion
5337 (goto-char (point-min))
5338 (while (re-search-forward
5339 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5340 nil t)
5341 (setq state (match-string 1))
5342 (save-excursion
5343 (org-back-to-heading t)
5344 (hide-subtree)
5345 (org-reveal)
5346 (cond
5347 ((equal state '("fold" "folded"))
5348 (hide-subtree))
5349 ((equal state "children")
5350 (org-show-hidden-entry)
5351 (show-children))
5352 ((equal state "content")
5353 (save-excursion
5354 (save-restriction
5355 (org-narrow-to-subtree)
5356 (org-content))))
5357 ((member state '("all" "showall"))
5358 (show-subtree)))))
5359 (unless no-cleanup
5360 (org-cycle-hide-archived-subtrees 'all)
5361 (org-cycle-hide-drawers 'all)
5362 (org-cycle-show-empty-lines 'all)))))
5364 (defun org-overview ()
5365 "Switch to overview mode, showing only top-level headlines.
5366 Really, this shows all headlines with level equal or greater than the level
5367 of the first headline in the buffer. This is important, because if the
5368 first headline is not level one, then (hide-sublevels 1) gives confusing
5369 results."
5370 (interactive)
5371 (let ((level (save-excursion
5372 (goto-char (point-min))
5373 (if (re-search-forward (concat "^" outline-regexp) nil t)
5374 (progn
5375 (goto-char (match-beginning 0))
5376 (funcall outline-level))))))
5377 (and level (hide-sublevels level))))
5379 (defun org-content (&optional arg)
5380 "Show all headlines in the buffer, like a table of contents.
5381 With numerical argument N, show content up to level N."
5382 (interactive "P")
5383 (save-excursion
5384 ;; Visit all headings and show their offspring
5385 (and (integerp arg) (org-overview))
5386 (goto-char (point-max))
5387 (catch 'exit
5388 (while (and (progn (condition-case nil
5389 (outline-previous-visible-heading 1)
5390 (error (goto-char (point-min))))
5392 (looking-at outline-regexp))
5393 (if (integerp arg)
5394 (show-children (1- arg))
5395 (show-branches))
5396 (if (bobp) (throw 'exit nil))))))
5399 (defun org-optimize-window-after-visibility-change (state)
5400 "Adjust the window after a change in outline visibility.
5401 This function is the default value of the hook `org-cycle-hook'."
5402 (when (get-buffer-window (current-buffer))
5403 (cond
5404 ((eq state 'content) nil)
5405 ((eq state 'all) nil)
5406 ((eq state 'folded) nil)
5407 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5408 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5410 ;; FIXME: no longer in use
5411 (defun org-compact-display-after-subtree-move ()
5412 "Show a compacter version of the tree of the entry's parent."
5413 (save-excursion
5414 (if (org-up-heading-safe)
5415 (progn
5416 (hide-subtree)
5417 (show-entry)
5418 (show-children)
5419 (org-cycle-show-empty-lines 'children)
5420 (org-cycle-hide-drawers 'children))
5421 (org-overview))))
5423 (defun org-remove-empty-overlays-at (pos)
5424 "Remove outline overlays that do not contain non-white stuff."
5425 (mapc
5426 (lambda (o)
5427 (and (eq 'outline (org-overlay-get o 'invisible))
5428 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5429 (org-overlay-end o))))
5430 (org-delete-overlay o)))
5431 (org-overlays-at pos)))
5433 (defun org-clean-visibility-after-subtree-move ()
5434 "Fix visibility issues after moving a subtree."
5435 ;; First, find a reasonable region to look at:
5436 ;; Start two siblings above, end three below
5437 (let* ((beg (save-excursion
5438 (and (org-get-last-sibling)
5439 (org-get-last-sibling))
5440 (point)))
5441 (end (save-excursion
5442 (and (org-get-next-sibling)
5443 (org-get-next-sibling)
5444 (org-get-next-sibling))
5445 (if (org-at-heading-p)
5446 (point-at-eol)
5447 (point))))
5448 (level (looking-at "\\*+"))
5449 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5450 (save-excursion
5451 (save-restriction
5452 (narrow-to-region beg end)
5453 (when re
5454 ;; Properly fold already folded siblings
5455 (goto-char (point-min))
5456 (while (re-search-forward re nil t)
5457 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5458 (hide-entry))))
5459 (org-cycle-show-empty-lines 'overview)
5460 (org-cycle-hide-drawers 'overview)))))
5462 (defun org-cycle-show-empty-lines (state)
5463 "Show empty lines above all visible headlines.
5464 The region to be covered depends on STATE when called through
5465 `org-cycle-hook'. Lisp program can use t for STATE to get the
5466 entire buffer covered. Note that an empty line is only shown if there
5467 are at least `org-cycle-separator-lines' empty lines before the headline."
5468 (when (not (= org-cycle-separator-lines 0))
5469 (save-excursion
5470 (let* ((n (abs org-cycle-separator-lines))
5471 (re (cond
5472 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5473 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5474 (t (let ((ns (number-to-string (- n 2))))
5475 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5476 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5477 beg end b e)
5478 (cond
5479 ((memq state '(overview contents t))
5480 (setq beg (point-min) end (point-max)))
5481 ((memq state '(children folded))
5482 (setq beg (point) end (progn (org-end-of-subtree t t)
5483 (beginning-of-line 2)
5484 (point)))))
5485 (when beg
5486 (goto-char beg)
5487 (while (re-search-forward re end t)
5488 (unless (get-char-property (match-end 1) 'invisible)
5489 (setq e (match-end 1))
5490 (if (< org-cycle-separator-lines 0)
5491 (setq b (save-excursion
5492 (goto-char (match-beginning 0))
5493 (org-back-over-empty-lines)
5494 (if (save-excursion
5495 (goto-char (max (point-min) (1- (point))))
5496 (org-on-heading-p))
5497 (1- (point))
5498 (point))))
5499 (setq b (match-beginning 1)))
5500 (outline-flag-region b e nil)))))))
5501 ;; Never hide empty lines at the end of the file.
5502 (save-excursion
5503 (goto-char (point-max))
5504 (outline-previous-heading)
5505 (outline-end-of-heading)
5506 (if (and (looking-at "[ \t\n]+")
5507 (= (match-end 0) (point-max)))
5508 (outline-flag-region (point) (match-end 0) nil))))
5510 (defun org-show-empty-lines-in-parent ()
5511 "Move to the parent and re-show empty lines before visible headlines."
5512 (save-excursion
5513 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5514 (org-cycle-show-empty-lines context))))
5516 (defun org-files-list ()
5517 "Return `org-agenda-files' list, plus all open org-mode files.
5518 This is useful for operations that need to scan all of a user's
5519 open and agenda-wise Org files."
5520 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5521 (dolist (buf (buffer-list))
5522 (with-current-buffer buf
5523 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5524 (let ((file (expand-file-name (buffer-file-name))))
5525 (unless (member file files)
5526 (push file files))))))
5527 files))
5529 (defsubst org-entry-beginning-position ()
5530 "Return the beginning position of the current entry."
5531 (save-excursion (outline-back-to-heading t) (point)))
5533 (defsubst org-entry-end-position ()
5534 "Return the end position of the current entry."
5535 (save-excursion (outline-next-heading) (point)))
5537 (defun org-cycle-hide-drawers (state)
5538 "Re-hide all drawers after a visibility state change."
5539 (when (and (org-mode-p)
5540 (not (memq state '(overview folded contents))))
5541 (save-excursion
5542 (let* ((globalp (memq state '(contents all)))
5543 (beg (if globalp (point-min) (point)))
5544 (end (if globalp (point-max)
5545 (if (eq state 'children)
5546 (save-excursion (outline-next-heading) (point))
5547 (org-end-of-subtree t)))))
5548 (goto-char beg)
5549 (while (re-search-forward org-drawer-regexp end t)
5550 (org-flag-drawer t))))))
5552 (defun org-flag-drawer (flag)
5553 (save-excursion
5554 (beginning-of-line 1)
5555 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5556 (let ((b (match-end 0))
5557 (outline-regexp org-outline-regexp))
5558 (if (re-search-forward
5559 "^[ \t]*:END:"
5560 (save-excursion (outline-next-heading) (point)) t)
5561 (outline-flag-region b (point-at-eol) flag)
5562 (error ":END: line missing at position %s" b))))))
5564 (defun org-subtree-end-visible-p ()
5565 "Is the end of the current subtree visible?"
5566 (pos-visible-in-window-p
5567 (save-excursion (org-end-of-subtree t) (point))))
5569 (defun org-first-headline-recenter (&optional N)
5570 "Move cursor to the first headline and recenter the headline.
5571 Optional argument N means, put the headline into the Nth line of the window."
5572 (goto-char (point-min))
5573 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5574 (beginning-of-line)
5575 (recenter (prefix-numeric-value N))))
5577 ;;; Folding of blocks
5579 (defconst org-block-regexp
5581 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5582 "Regular expression for hiding blocks.")
5584 (defvar org-hide-block-overlays nil
5585 "Overlays hiding blocks.")
5586 (make-variable-buffer-local 'org-hide-block-overlays)
5588 (defun org-block-map (function &optional start end)
5589 "Call func at the head of all source blocks in the current
5590 buffer. Optional arguments START and END can be used to limit
5591 the range."
5592 (let ((start (or start (point-min)))
5593 (end (or end (point-max))))
5594 (save-excursion
5595 (goto-char start)
5596 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5597 (save-excursion
5598 (save-match-data
5599 (goto-char (match-beginning 0))
5600 (funcall function)))))))
5602 (defun org-hide-block-toggle-all ()
5603 "Toggle the visibility of all blocks in the current buffer."
5604 (org-block-map #'org-hide-block-toggle))
5606 (defun org-hide-block-all ()
5607 "Fold all blocks in the current buffer."
5608 (interactive)
5609 (org-show-block-all)
5610 (org-block-map #'org-hide-block-toggle-maybe))
5612 (defun org-show-block-all ()
5613 "Unfold all blocks in the current buffer."
5614 (mapc 'org-delete-overlay org-hide-block-overlays)
5615 (setq org-hide-block-overlays nil))
5617 (defun org-hide-block-toggle-maybe ()
5618 "Toggle visibility of block at point."
5619 (interactive)
5620 (let ((case-fold-search t))
5621 (if (save-excursion
5622 (beginning-of-line 1)
5623 (looking-at org-block-regexp))
5624 (progn (org-hide-block-toggle)
5625 t) ;; to signal that we took action
5626 nil))) ;; to signal that we did not
5628 (defun org-hide-block-toggle (&optional force)
5629 "Toggle the visibility of the current block."
5630 (interactive)
5631 (save-excursion
5632 (beginning-of-line)
5633 (if (re-search-forward org-block-regexp nil t)
5634 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5635 (end (match-end 0)) ;; end of entire body
5637 (if (memq t (mapcar (lambda (overlay)
5638 (eq (org-overlay-get overlay 'invisible)
5639 'org-hide-block))
5640 (org-overlays-at start)))
5641 (if (or (not force) (eq force 'off))
5642 (mapc (lambda (ov)
5643 (when (member ov org-hide-block-overlays)
5644 (setq org-hide-block-overlays
5645 (delq ov org-hide-block-overlays)))
5646 (when (eq (org-overlay-get ov 'invisible)
5647 'org-hide-block)
5648 (org-delete-overlay ov)))
5649 (org-overlays-at start)))
5650 (setq ov (org-make-overlay start end))
5651 (org-overlay-put ov 'invisible 'org-hide-block)
5652 ;; make the block accessible to isearch
5653 (org-overlay-put
5654 ov 'isearch-open-invisible
5655 (lambda (ov)
5656 (when (member ov org-hide-block-overlays)
5657 (setq org-hide-block-overlays
5658 (delq ov org-hide-block-overlays)))
5659 (when (eq (org-overlay-get ov 'invisible)
5660 'org-hide-block)
5661 (org-delete-overlay ov))))
5662 (push ov org-hide-block-overlays)))
5663 (error "Not looking at a source block"))))
5665 ;; org-tab-after-check-for-cycling-hook
5666 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5667 ;; Remove overlays when changing major mode
5668 (add-hook 'org-mode-hook
5669 (lambda () (org-add-hook 'change-major-mode-hook
5670 'org-show-block-all 'append 'local)))
5672 ;;; Org-goto
5674 (defvar org-goto-window-configuration nil)
5675 (defvar org-goto-marker nil)
5676 (defvar org-goto-map
5677 (let ((map (make-sparse-keymap)))
5678 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5679 (while (setq cmd (pop cmds))
5680 (substitute-key-definition cmd cmd map global-map)))
5681 (suppress-keymap map)
5682 (org-defkey map "\C-m" 'org-goto-ret)
5683 (org-defkey map [(return)] 'org-goto-ret)
5684 (org-defkey map [(left)] 'org-goto-left)
5685 (org-defkey map [(right)] 'org-goto-right)
5686 (org-defkey map [(control ?g)] 'org-goto-quit)
5687 (org-defkey map "\C-i" 'org-cycle)
5688 (org-defkey map [(tab)] 'org-cycle)
5689 (org-defkey map [(down)] 'outline-next-visible-heading)
5690 (org-defkey map [(up)] 'outline-previous-visible-heading)
5691 (if org-goto-auto-isearch
5692 (if (fboundp 'define-key-after)
5693 (define-key-after map [t] 'org-goto-local-auto-isearch)
5694 nil)
5695 (org-defkey map "q" 'org-goto-quit)
5696 (org-defkey map "n" 'outline-next-visible-heading)
5697 (org-defkey map "p" 'outline-previous-visible-heading)
5698 (org-defkey map "f" 'outline-forward-same-level)
5699 (org-defkey map "b" 'outline-backward-same-level)
5700 (org-defkey map "u" 'outline-up-heading))
5701 (org-defkey map "/" 'org-occur)
5702 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5703 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5704 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5705 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5706 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5707 map))
5709 (defconst org-goto-help
5710 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5711 RET=jump to location [Q]uit and return to previous location
5712 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5714 (defvar org-goto-start-pos) ; dynamically scoped parameter
5716 ;; FIXME: Docstring does not mention both interfaces
5717 (defun org-goto (&optional alternative-interface)
5718 "Look up a different location in the current file, keeping current visibility.
5720 When you want look-up or go to a different location in a document, the
5721 fastest way is often to fold the entire buffer and then dive into the tree.
5722 This method has the disadvantage, that the previous location will be folded,
5723 which may not be what you want.
5725 This command works around this by showing a copy of the current buffer
5726 in an indirect buffer, in overview mode. You can dive into the tree in
5727 that copy, use org-occur and incremental search to find a location.
5728 When pressing RET or `Q', the command returns to the original buffer in
5729 which the visibility is still unchanged. After RET is will also jump to
5730 the location selected in the indirect buffer and expose the
5731 the headline hierarchy above."
5732 (interactive "P")
5733 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5734 (org-refile-use-outline-path t)
5735 (org-refile-target-verify-function nil)
5736 (interface
5737 (if (not alternative-interface)
5738 org-goto-interface
5739 (if (eq org-goto-interface 'outline)
5740 'outline-path-completion
5741 'outline)))
5742 (org-goto-start-pos (point))
5743 (selected-point
5744 (if (eq interface 'outline)
5745 (car (org-get-location (current-buffer) org-goto-help))
5746 (nth 3 (org-refile-get-location "Goto: ")))))
5747 (if selected-point
5748 (progn
5749 (org-mark-ring-push org-goto-start-pos)
5750 (goto-char selected-point)
5751 (if (or (org-invisible-p) (org-invisible-p2))
5752 (org-show-context 'org-goto)))
5753 (message "Quit"))))
5755 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5756 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5757 (defvar org-goto-local-auto-isearch-map) ; defined below
5759 (defun org-get-location (buf help)
5760 "Let the user select a location in the Org-mode buffer BUF.
5761 This function uses a recursive edit. It returns the selected position
5762 or nil."
5763 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5764 (isearch-hide-immediately nil)
5765 (isearch-search-fun-function
5766 (lambda () 'org-goto-local-search-headings))
5767 (org-goto-selected-point org-goto-exit-command))
5768 (save-excursion
5769 (save-window-excursion
5770 (delete-other-windows)
5771 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5772 (switch-to-buffer
5773 (condition-case nil
5774 (make-indirect-buffer (current-buffer) "*org-goto*")
5775 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5776 (with-output-to-temp-buffer "*Help*"
5777 (princ help))
5778 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5779 (setq buffer-read-only nil)
5780 (let ((org-startup-truncated t)
5781 (org-startup-folded nil)
5782 (org-startup-align-all-tables nil))
5783 (org-mode)
5784 (org-overview))
5785 (setq buffer-read-only t)
5786 (if (and (boundp 'org-goto-start-pos)
5787 (integer-or-marker-p org-goto-start-pos))
5788 (let ((org-show-hierarchy-above t)
5789 (org-show-siblings t)
5790 (org-show-following-heading t))
5791 (goto-char org-goto-start-pos)
5792 (and (org-invisible-p) (org-show-context)))
5793 (goto-char (point-min)))
5794 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5795 (message "Select location and press RET")
5796 (use-local-map org-goto-map)
5797 (recursive-edit)
5799 (kill-buffer "*org-goto*")
5800 (cons org-goto-selected-point org-goto-exit-command)))
5802 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5803 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5804 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5805 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5807 (defun org-goto-local-search-headings (string bound noerror)
5808 "Search and make sure that any matches are in headlines."
5809 (catch 'return
5810 (while (if isearch-forward
5811 (search-forward string bound noerror)
5812 (search-backward string bound noerror))
5813 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5814 (and (member :headline context)
5815 (not (member :tags context))))
5816 (throw 'return (point))))))
5818 (defun org-goto-local-auto-isearch ()
5819 "Start isearch."
5820 (interactive)
5821 (goto-char (point-min))
5822 (let ((keys (this-command-keys)))
5823 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5824 (isearch-mode t)
5825 (isearch-process-search-char (string-to-char keys)))))
5827 (defun org-goto-ret (&optional arg)
5828 "Finish `org-goto' by going to the new location."
5829 (interactive "P")
5830 (setq org-goto-selected-point (point)
5831 org-goto-exit-command 'return)
5832 (throw 'exit nil))
5834 (defun org-goto-left ()
5835 "Finish `org-goto' by going to the new location."
5836 (interactive)
5837 (if (org-on-heading-p)
5838 (progn
5839 (beginning-of-line 1)
5840 (setq org-goto-selected-point (point)
5841 org-goto-exit-command 'left)
5842 (throw 'exit nil))
5843 (error "Not on a heading")))
5845 (defun org-goto-right ()
5846 "Finish `org-goto' by going to the new location."
5847 (interactive)
5848 (if (org-on-heading-p)
5849 (progn
5850 (setq org-goto-selected-point (point)
5851 org-goto-exit-command 'right)
5852 (throw 'exit nil))
5853 (error "Not on a heading")))
5855 (defun org-goto-quit ()
5856 "Finish `org-goto' without cursor motion."
5857 (interactive)
5858 (setq org-goto-selected-point nil)
5859 (setq org-goto-exit-command 'quit)
5860 (throw 'exit nil))
5862 ;;; Indirect buffer display of subtrees
5864 (defvar org-indirect-dedicated-frame nil
5865 "This is the frame being used for indirect tree display.")
5866 (defvar org-last-indirect-buffer nil)
5868 (defun org-tree-to-indirect-buffer (&optional arg)
5869 "Create indirect buffer and narrow it to current subtree.
5870 With numerical prefix ARG, go up to this level and then take that tree.
5871 If ARG is negative, go up that many levels.
5872 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5873 indirect buffer previously made with this command, to avoid proliferation of
5874 indirect buffers. However, when you call the command with a `C-u' prefix, or
5875 when `org-indirect-buffer-display' is `new-frame', the last buffer
5876 is kept so that you can work with several indirect buffers at the same time.
5877 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5878 requests that a new frame be made for the new buffer, so that the dedicated
5879 frame is not changed."
5880 (interactive "P")
5881 (let ((cbuf (current-buffer))
5882 (cwin (selected-window))
5883 (pos (point))
5884 beg end level heading ibuf)
5885 (save-excursion
5886 (org-back-to-heading t)
5887 (when (numberp arg)
5888 (setq level (org-outline-level))
5889 (if (< arg 0) (setq arg (+ level arg)))
5890 (while (> (setq level (org-outline-level)) arg)
5891 (outline-up-heading 1 t)))
5892 (setq beg (point)
5893 heading (org-get-heading))
5894 (org-end-of-subtree t t) (setq end (point)))
5895 (if (and (buffer-live-p org-last-indirect-buffer)
5896 (not (eq org-indirect-buffer-display 'new-frame))
5897 (not arg))
5898 (kill-buffer org-last-indirect-buffer))
5899 (setq ibuf (org-get-indirect-buffer cbuf)
5900 org-last-indirect-buffer ibuf)
5901 (cond
5902 ((or (eq org-indirect-buffer-display 'new-frame)
5903 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5904 (select-frame (make-frame))
5905 (delete-other-windows)
5906 (switch-to-buffer ibuf)
5907 (org-set-frame-title heading))
5908 ((eq org-indirect-buffer-display 'dedicated-frame)
5909 (raise-frame
5910 (select-frame (or (and org-indirect-dedicated-frame
5911 (frame-live-p org-indirect-dedicated-frame)
5912 org-indirect-dedicated-frame)
5913 (setq org-indirect-dedicated-frame (make-frame)))))
5914 (delete-other-windows)
5915 (switch-to-buffer ibuf)
5916 (org-set-frame-title (concat "Indirect: " heading)))
5917 ((eq org-indirect-buffer-display 'current-window)
5918 (switch-to-buffer ibuf))
5919 ((eq org-indirect-buffer-display 'other-window)
5920 (pop-to-buffer ibuf))
5921 (t (error "Invalid value")))
5922 (if (featurep 'xemacs)
5923 (save-excursion (org-mode) (turn-on-font-lock)))
5924 (narrow-to-region beg end)
5925 (show-all)
5926 (goto-char pos)
5927 (and (window-live-p cwin) (select-window cwin))))
5929 (defun org-get-indirect-buffer (&optional buffer)
5930 (setq buffer (or buffer (current-buffer)))
5931 (let ((n 1) (base (buffer-name buffer)) bname)
5932 (while (buffer-live-p
5933 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5934 (setq n (1+ n)))
5935 (condition-case nil
5936 (make-indirect-buffer buffer bname 'clone)
5937 (error (make-indirect-buffer buffer bname)))))
5939 (defun org-set-frame-title (title)
5940 "Set the title of the current frame to the string TITLE."
5941 ;; FIXME: how to name a single frame in XEmacs???
5942 (unless (featurep 'xemacs)
5943 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5945 ;;;; Structure editing
5947 ;;; Inserting headlines
5949 (defun org-previous-line-empty-p ()
5950 (save-excursion
5951 (and (not (bobp))
5952 (or (beginning-of-line 0) t)
5953 (save-match-data
5954 (looking-at "[ \t]*$")))))
5956 (defun org-insert-heading (&optional force-heading)
5957 "Insert a new heading or item with same depth at point.
5958 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5959 If point is at the beginning of a headline, insert a sibling before the
5960 current headline. If point is not at the beginning, do not split the line,
5961 but create the new headline after the current line."
5962 (interactive "P")
5963 (if (= (buffer-size) 0)
5964 (insert "\n* ")
5965 (when (or force-heading (not (org-insert-item)))
5966 (let* ((empty-line-p nil)
5967 (head (save-excursion
5968 (condition-case nil
5969 (progn
5970 (org-back-to-heading)
5971 (setq empty-line-p (org-previous-line-empty-p))
5972 (match-string 0))
5973 (error "*"))))
5974 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5975 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5976 pos hide-previous previous-pos)
5977 (cond
5978 ((and (org-on-heading-p) (bolp)
5979 (or (bobp)
5980 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5981 ;; insert before the current line
5982 (open-line (if blank 2 1)))
5983 ((and (bolp)
5984 (not org-insert-heading-respect-content)
5985 (or (bobp)
5986 (save-excursion
5987 (backward-char 1) (not (org-invisible-p)))))
5988 ;; insert right here
5989 nil)
5991 ;; somewhere in the line
5992 (save-excursion
5993 (setq previous-pos (point-at-bol))
5994 (end-of-line)
5995 (setq hide-previous (org-invisible-p)))
5996 (and org-insert-heading-respect-content (org-show-subtree))
5997 (let ((split
5998 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5999 (save-excursion
6000 (let ((p (point)))
6001 (goto-char (point-at-bol))
6002 (and (looking-at org-complex-heading-regexp)
6003 (> p (match-beginning 4)))))))
6004 tags pos)
6005 (cond
6006 (org-insert-heading-respect-content
6007 (org-end-of-subtree nil t)
6008 (or (bolp) (newline))
6009 (or (org-previous-line-empty-p)
6010 (and blank (newline)))
6011 (open-line 1))
6012 ((org-on-heading-p)
6013 (when hide-previous
6014 (show-children)
6015 (org-show-entry))
6016 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6017 (setq tags (and (match-end 2) (match-string 2)))
6018 (and (match-end 1)
6019 (delete-region (match-beginning 1) (match-end 1)))
6020 (setq pos (point-at-bol))
6021 (or split (end-of-line 1))
6022 (delete-horizontal-space)
6023 (newline (if blank 2 1))
6024 (when tags
6025 (save-excursion
6026 (goto-char pos)
6027 (end-of-line 1)
6028 (insert " " tags)
6029 (org-set-tags nil 'align))))
6031 (or split (end-of-line 1))
6032 (newline (if blank 2 1)))))))
6033 (insert head) (just-one-space)
6034 (setq pos (point))
6035 (end-of-line 1)
6036 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6037 (when (and org-insert-heading-respect-content hide-previous)
6038 (save-excursion
6039 (goto-char previous-pos)
6040 (hide-subtree)))
6041 (run-hooks 'org-insert-heading-hook)))))
6043 (defun org-get-heading (&optional no-tags)
6044 "Return the heading of the current entry, without the stars."
6045 (save-excursion
6046 (org-back-to-heading t)
6047 (if (looking-at
6048 (if no-tags
6049 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6050 "\\*+[ \t]+\\([^\r\n]*\\)"))
6051 (match-string 1) "")))
6053 (defun org-heading-components ()
6054 "Return the components of the current heading.
6055 This is a list with the following elements:
6056 - the level as an integer
6057 - the reduced level, different if `org-odd-levels-only' is set.
6058 - the TODO keyword, or nil
6059 - the priority character, like ?A, or nil if no priority is given
6060 - the headline text itself, or the tags string if no headline text
6061 - the tags string, or nil."
6062 (save-excursion
6063 (org-back-to-heading t)
6064 (if (looking-at org-complex-heading-regexp)
6065 (list (length (match-string 1))
6066 (org-reduced-level (length (match-string 1)))
6067 (org-match-string-no-properties 2)
6068 (and (match-end 3) (aref (match-string 3) 2))
6069 (org-match-string-no-properties 4)
6070 (org-match-string-no-properties 5)))))
6072 (defun org-get-entry ()
6073 "Get the entry text, after heading, entire subtree."
6074 (save-excursion
6075 (org-back-to-heading t)
6076 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6078 (defun org-insert-heading-after-current ()
6079 "Insert a new heading with same level as current, after current subtree."
6080 (interactive)
6081 (org-back-to-heading)
6082 (org-insert-heading)
6083 (org-move-subtree-down)
6084 (end-of-line 1))
6086 (defun org-insert-heading-respect-content ()
6087 (interactive)
6088 (let ((org-insert-heading-respect-content t))
6089 (org-insert-heading t)))
6091 (defun org-insert-todo-heading-respect-content (&optional force-state)
6092 (interactive "P")
6093 (let ((org-insert-heading-respect-content t))
6094 (org-insert-todo-heading force-state t)))
6096 (defun org-insert-todo-heading (arg &optional force-heading)
6097 "Insert a new heading with the same level and TODO state as current heading.
6098 If the heading has no TODO state, or if the state is DONE, use the first
6099 state (TODO by default). Also with prefix arg, force first state."
6100 (interactive "P")
6101 (when (or force-heading (not (org-insert-item 'checkbox)))
6102 (org-insert-heading force-heading)
6103 (save-excursion
6104 (org-back-to-heading)
6105 (outline-previous-heading)
6106 (looking-at org-todo-line-regexp))
6107 (let*
6108 ((new-mark-x
6109 (if (or arg
6110 (not (match-beginning 2))
6111 (member (match-string 2) org-done-keywords))
6112 (car org-todo-keywords-1)
6113 (match-string 2)))
6114 (new-mark
6116 (run-hook-with-args-until-success
6117 'org-todo-get-default-hook new-mark-x nil)
6118 new-mark-x)))
6119 (beginning-of-line 1)
6120 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6121 (if org-treat-insert-todo-heading-as-state-change
6122 (org-todo new-mark)
6123 (insert new-mark " "))))
6124 (when org-provide-todo-statistics
6125 (org-update-parent-todo-statistics))))
6127 (defun org-insert-subheading (arg)
6128 "Insert a new subheading and demote it.
6129 Works for outline headings and for plain lists alike."
6130 (interactive "P")
6131 (org-insert-heading arg)
6132 (cond
6133 ((org-on-heading-p) (org-do-demote))
6134 ((org-at-item-p) (org-indent-item 1))))
6136 (defun org-insert-todo-subheading (arg)
6137 "Insert a new subheading with TODO keyword or checkbox and demote it.
6138 Works for outline headings and for plain lists alike."
6139 (interactive "P")
6140 (org-insert-todo-heading arg)
6141 (cond
6142 ((org-on-heading-p) (org-do-demote))
6143 ((org-at-item-p) (org-indent-item 1))))
6145 ;;; Promotion and Demotion
6147 (defvar org-after-demote-entry-hook nil
6148 "Hook run after an entry has been demoted.
6149 The cursor will be at the beginning of the entry.
6150 When a subtree is being demoted, the hook will be called for each node.")
6152 (defvar org-after-promote-entry-hook nil
6153 "Hook run after an entry has been promoted.
6154 The cursor will be at the beginning of the entry.
6155 When a subtree is being promoted, the hook will be called for each node.")
6157 (defun org-promote-subtree ()
6158 "Promote the entire subtree.
6159 See also `org-promote'."
6160 (interactive)
6161 (save-excursion
6162 (org-map-tree 'org-promote))
6163 (org-fix-position-after-promote))
6165 (defun org-demote-subtree ()
6166 "Demote the entire subtree. See `org-demote'.
6167 See also `org-promote'."
6168 (interactive)
6169 (save-excursion
6170 (org-map-tree 'org-demote))
6171 (org-fix-position-after-promote))
6174 (defun org-do-promote ()
6175 "Promote the current heading higher up the tree.
6176 If the region is active in `transient-mark-mode', promote all headings
6177 in the region."
6178 (interactive)
6179 (save-excursion
6180 (if (org-region-active-p)
6181 (org-map-region 'org-promote (region-beginning) (region-end))
6182 (org-promote)))
6183 (org-fix-position-after-promote))
6185 (defun org-do-demote ()
6186 "Demote the current heading lower down the tree.
6187 If the region is active in `transient-mark-mode', demote all headings
6188 in the region."
6189 (interactive)
6190 (save-excursion
6191 (if (org-region-active-p)
6192 (org-map-region 'org-demote (region-beginning) (region-end))
6193 (org-demote)))
6194 (org-fix-position-after-promote))
6196 (defun org-fix-position-after-promote ()
6197 "Make sure that after pro/demotion cursor position is right."
6198 (let ((pos (point)))
6199 (when (save-excursion
6200 (beginning-of-line 1)
6201 (looking-at org-todo-line-regexp)
6202 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6203 (cond ((eobp) (insert " "))
6204 ((eolp) (insert " "))
6205 ((equal (char-after) ?\ ) (forward-char 1))))))
6207 (defun org-current-level ()
6208 "Return the level of the current entry, or nil if before the first headline.
6209 The level is the number of stars at the beginning of the headline."
6210 (save-excursion
6211 (condition-case nil
6212 (progn
6213 (org-back-to-heading t)
6214 (funcall outline-level))
6215 (error nil))))
6217 (defun org-reduced-level (l)
6218 "Compute the effective level of a heading.
6219 This takes into account the setting of `org-odd-levels-only'."
6220 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6222 (defun org-get-valid-level (level &optional change)
6223 "Rectify a level change under the influence of `org-odd-levels-only'
6224 LEVEL is a current level, CHANGE is by how much the level should be
6225 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6226 even level numbers will become the next higher odd number."
6227 (if org-odd-levels-only
6228 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6229 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6230 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6231 (max 1 (+ level (or change 0)))))
6233 (if (boundp 'define-obsolete-function-alias)
6234 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6235 (define-obsolete-function-alias 'org-get-legal-level
6236 'org-get-valid-level)
6237 (define-obsolete-function-alias 'org-get-legal-level
6238 'org-get-valid-level "23.1")))
6240 (defun org-promote ()
6241 "Promote the current heading higher up the tree.
6242 If the region is active in `transient-mark-mode', promote all headings
6243 in the region."
6244 (org-back-to-heading t)
6245 (let* ((level (save-match-data (funcall outline-level)))
6246 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6247 (diff (abs (- level (length up-head) -1))))
6248 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6249 (replace-match up-head nil t)
6250 ;; Fixup tag positioning
6251 (and org-auto-align-tags (org-set-tags nil t))
6252 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6253 (run-hooks 'org-after-promote-entry-hook)))
6255 (defun org-demote ()
6256 "Demote the current heading lower down the tree.
6257 If the region is active in `transient-mark-mode', demote all headings
6258 in the region."
6259 (org-back-to-heading t)
6260 (let* ((level (save-match-data (funcall outline-level)))
6261 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6262 (diff (abs (- level (length down-head) -1))))
6263 (replace-match down-head nil t)
6264 ;; Fixup tag positioning
6265 (and org-auto-align-tags (org-set-tags nil t))
6266 (if org-adapt-indentation (org-fixup-indentation diff))
6267 (run-hooks 'org-after-demote-entry-hook)))
6269 (defvar org-tab-ind-state nil)
6271 (defun org-cycle-level ()
6272 (let ((org-adapt-indentation nil))
6273 (when (and (looking-at "[ \t]*$")
6274 (looking-back
6275 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6276 (setq this-command 'org-cycle-level)
6277 (if (eq last-command 'org-cycle-level)
6278 (condition-case nil
6279 (progn (org-do-promote)
6280 (if (equal org-tab-ind-state (org-current-level))
6281 (org-do-promote)))
6282 (error
6283 (progn
6284 (save-excursion
6285 (beginning-of-line 1)
6286 (and (looking-at "\\*+")
6287 (replace-match
6288 (make-string org-tab-ind-state ?*))))
6289 (setq this-command 'org-cycle))))
6290 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6291 (org-do-demote))
6292 t)))
6294 (defun org-map-tree (fun)
6295 "Call FUN for every heading underneath the current one."
6296 (org-back-to-heading)
6297 (let ((level (funcall outline-level)))
6298 (save-excursion
6299 (funcall fun)
6300 (while (and (progn
6301 (outline-next-heading)
6302 (> (funcall outline-level) level))
6303 (not (eobp)))
6304 (funcall fun)))))
6306 (defun org-map-region (fun beg end)
6307 "Call FUN for every heading between BEG and END."
6308 (let ((org-ignore-region t))
6309 (save-excursion
6310 (setq end (copy-marker end))
6311 (goto-char beg)
6312 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6313 (< (point) end))
6314 (funcall fun))
6315 (while (and (progn
6316 (outline-next-heading)
6317 (< (point) end))
6318 (not (eobp)))
6319 (funcall fun)))))
6321 (defun org-fixup-indentation (diff)
6322 "Change the indentation in the current entry by DIFF
6323 However, if any line in the current entry has no indentation, or if it
6324 would end up with no indentation after the change, nothing at all is done."
6325 (save-excursion
6326 (let ((end (save-excursion (outline-next-heading)
6327 (point-marker)))
6328 (prohibit (if (> diff 0)
6329 "^\\S-"
6330 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6331 col)
6332 (unless (save-excursion (end-of-line 1)
6333 (re-search-forward prohibit end t))
6334 (while (and (< (point) end)
6335 (re-search-forward "^[ \t]+" end t))
6336 (goto-char (match-end 0))
6337 (setq col (current-column))
6338 (if (< diff 0) (replace-match ""))
6339 (org-indent-to-column (+ diff col))))
6340 (move-marker end nil))))
6342 (defun org-convert-to-odd-levels ()
6343 "Convert an org-mode file with all levels allowed to one with odd levels.
6344 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6345 level 5 etc."
6346 (interactive)
6347 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6348 (let ((outline-regexp org-outline-regexp)
6349 (outline-level 'org-outline-level)
6350 (org-odd-levels-only nil) n)
6351 (save-excursion
6352 (goto-char (point-min))
6353 (while (re-search-forward "^\\*\\*+ " nil t)
6354 (setq n (- (length (match-string 0)) 2))
6355 (while (>= (setq n (1- n)) 0)
6356 (org-demote))
6357 (end-of-line 1))))))
6359 (defun org-convert-to-oddeven-levels ()
6360 "Convert an org-mode file with only odd levels to one with odd and even levels.
6361 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6362 section with an even level, conversion would destroy the structure of the file. An error
6363 is signaled in this case."
6364 (interactive)
6365 (goto-char (point-min))
6366 ;; First check if there are no even levels
6367 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6368 (org-show-context t)
6369 (error "Not all levels are odd in this file. Conversion not possible"))
6370 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6371 (let ((outline-regexp org-outline-regexp)
6372 (outline-level 'org-outline-level)
6373 (org-odd-levels-only nil) n)
6374 (save-excursion
6375 (goto-char (point-min))
6376 (while (re-search-forward "^\\*\\*+ " nil t)
6377 (setq n (/ (1- (length (match-string 0))) 2))
6378 (while (>= (setq n (1- n)) 0)
6379 (org-promote))
6380 (end-of-line 1))))))
6382 (defun org-tr-level (n)
6383 "Make N odd if required."
6384 (if org-odd-levels-only (1+ (/ n 2)) n))
6386 ;;; Vertical tree motion, cutting and pasting of subtrees
6388 (defun org-move-subtree-up (&optional arg)
6389 "Move the current subtree up past ARG headlines of the same level."
6390 (interactive "p")
6391 (org-move-subtree-down (- (prefix-numeric-value arg))))
6393 (defun org-move-subtree-down (&optional arg)
6394 "Move the current subtree down past ARG headlines of the same level."
6395 (interactive "p")
6396 (setq arg (prefix-numeric-value arg))
6397 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6398 'org-get-last-sibling))
6399 (ins-point (make-marker))
6400 (cnt (abs arg))
6401 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6402 ;; Select the tree
6403 (org-back-to-heading)
6404 (setq beg0 (point))
6405 (save-excursion
6406 (setq ne-beg (org-back-over-empty-lines))
6407 (setq beg (point)))
6408 (save-match-data
6409 (save-excursion (outline-end-of-heading)
6410 (setq folded (org-invisible-p)))
6411 (outline-end-of-subtree))
6412 (outline-next-heading)
6413 (setq ne-end (org-back-over-empty-lines))
6414 (setq end (point))
6415 (goto-char beg0)
6416 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6417 ;; include less whitespace
6418 (save-excursion
6419 (goto-char beg)
6420 (forward-line (- ne-beg ne-end))
6421 (setq beg (point))))
6422 ;; Find insertion point, with error handling
6423 (while (> cnt 0)
6424 (or (and (funcall movfunc) (looking-at outline-regexp))
6425 (progn (goto-char beg0)
6426 (error "Cannot move past superior level or buffer limit")))
6427 (setq cnt (1- cnt)))
6428 (if (> arg 0)
6429 ;; Moving forward - still need to move over subtree
6430 (progn (org-end-of-subtree t t)
6431 (save-excursion
6432 (org-back-over-empty-lines)
6433 (or (bolp) (newline)))))
6434 (setq ne-ins (org-back-over-empty-lines))
6435 (move-marker ins-point (point))
6436 (setq txt (buffer-substring beg end))
6437 (org-save-markers-in-region beg end)
6438 (delete-region beg end)
6439 (org-remove-empty-overlays-at beg)
6440 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6441 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6442 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6443 (let ((bbb (point)))
6444 (insert-before-markers txt)
6445 (org-reinstall-markers-in-region bbb)
6446 (move-marker ins-point bbb))
6447 (or (bolp) (insert "\n"))
6448 (setq ins-end (point))
6449 (goto-char ins-point)
6450 (org-skip-whitespace)
6451 (when (and (< arg 0)
6452 (org-first-sibling-p)
6453 (> ne-ins ne-beg))
6454 ;; Move whitespace back to beginning
6455 (save-excursion
6456 (goto-char ins-end)
6457 (let ((kill-whole-line t))
6458 (kill-line (- ne-ins ne-beg)) (point)))
6459 (insert (make-string (- ne-ins ne-beg) ?\n)))
6460 (move-marker ins-point nil)
6461 (if folded
6462 (hide-subtree)
6463 (org-show-entry)
6464 (show-children)
6465 (org-cycle-hide-drawers 'children))
6466 (org-clean-visibility-after-subtree-move)))
6468 (defvar org-subtree-clip ""
6469 "Clipboard for cut and paste of subtrees.
6470 This is actually only a copy of the kill, because we use the normal kill
6471 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6473 (defvar org-subtree-clip-folded nil
6474 "Was the last copied subtree folded?
6475 This is used to fold the tree back after pasting.")
6477 (defun org-cut-subtree (&optional n)
6478 "Cut the current subtree into the clipboard.
6479 With prefix arg N, cut this many sequential subtrees.
6480 This is a short-hand for marking the subtree and then cutting it."
6481 (interactive "p")
6482 (org-copy-subtree n 'cut))
6484 (defun org-copy-subtree (&optional n cut force-store-markers)
6485 "Cut the current subtree into the clipboard.
6486 With prefix arg N, cut this many sequential subtrees.
6487 This is a short-hand for marking the subtree and then copying it.
6488 If CUT is non-nil, actually cut the subtree.
6489 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6490 of some markers in the region, even if CUT is non-nil. This is
6491 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6492 (interactive "p")
6493 (let (beg end folded (beg0 (point)))
6494 (if (interactive-p)
6495 (org-back-to-heading nil) ; take what looks like a subtree
6496 (org-back-to-heading t)) ; take what is really there
6497 (org-back-over-empty-lines)
6498 (setq beg (point))
6499 (skip-chars-forward " \t\r\n")
6500 (save-match-data
6501 (save-excursion (outline-end-of-heading)
6502 (setq folded (org-invisible-p)))
6503 (condition-case nil
6504 (org-forward-same-level (1- n) t)
6505 (error nil))
6506 (org-end-of-subtree t t))
6507 (org-back-over-empty-lines)
6508 (setq end (point))
6509 (goto-char beg0)
6510 (when (> end beg)
6511 (setq org-subtree-clip-folded folded)
6512 (when (or cut force-store-markers)
6513 (org-save-markers-in-region beg end))
6514 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6515 (setq org-subtree-clip (current-kill 0))
6516 (message "%s: Subtree(s) with %d characters"
6517 (if cut "Cut" "Copied")
6518 (length org-subtree-clip)))))
6520 (defun org-paste-subtree (&optional level tree for-yank)
6521 "Paste the clipboard as a subtree, with modification of headline level.
6522 The entire subtree is promoted or demoted in order to match a new headline
6523 level.
6525 If the cursor is at the beginning of a headline, the same level as
6526 that headline is used to paste the tree
6528 If not, the new level is derived from the *visible* headings
6529 before and after the insertion point, and taken to be the inferior headline
6530 level of the two. So if the previous visible heading is level 3 and the
6531 next is level 4 (or vice versa), level 4 will be used for insertion.
6532 This makes sure that the subtree remains an independent subtree and does
6533 not swallow low level entries.
6535 You can also force a different level, either by using a numeric prefix
6536 argument, or by inserting the heading marker by hand. For example, if the
6537 cursor is after \"*****\", then the tree will be shifted to level 5.
6539 If optional TREE is given, use this text instead of the kill ring.
6541 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6542 move back over whitespace before inserting, and move point to the end of
6543 the inserted text when done."
6544 (interactive "P")
6545 (setq tree (or tree (and kill-ring (current-kill 0))))
6546 (unless (org-kill-is-subtree-p tree)
6547 (error "%s"
6548 (substitute-command-keys
6549 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6550 (let* ((visp (not (org-invisible-p)))
6551 (txt tree)
6552 (^re (concat "^\\(" outline-regexp "\\)"))
6553 (re (concat "\\(" outline-regexp "\\)"))
6554 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6556 (old-level (if (string-match ^re txt)
6557 (- (match-end 0) (match-beginning 0) 1)
6558 -1))
6559 (force-level (cond (level (prefix-numeric-value level))
6560 ((and (looking-at "[ \t]*$")
6561 (string-match
6562 ^re_ (buffer-substring
6563 (point-at-bol) (point))))
6564 (- (match-end 1) (match-beginning 1)))
6565 ((and (bolp)
6566 (looking-at org-outline-regexp))
6567 (- (match-end 0) (point) 1))
6568 (t nil)))
6569 (previous-level (save-excursion
6570 (condition-case nil
6571 (progn
6572 (outline-previous-visible-heading 1)
6573 (if (looking-at re)
6574 (- (match-end 0) (match-beginning 0) 1)
6576 (error 1))))
6577 (next-level (save-excursion
6578 (condition-case nil
6579 (progn
6580 (or (looking-at outline-regexp)
6581 (outline-next-visible-heading 1))
6582 (if (looking-at re)
6583 (- (match-end 0) (match-beginning 0) 1)
6585 (error 1))))
6586 (new-level (or force-level (max previous-level next-level)))
6587 (shift (if (or (= old-level -1)
6588 (= new-level -1)
6589 (= old-level new-level))
6591 (- new-level old-level)))
6592 (delta (if (> shift 0) -1 1))
6593 (func (if (> shift 0) 'org-demote 'org-promote))
6594 (org-odd-levels-only nil)
6595 beg end newend)
6596 ;; Remove the forced level indicator
6597 (if force-level
6598 (delete-region (point-at-bol) (point)))
6599 ;; Paste
6600 (beginning-of-line 1)
6601 (unless for-yank (org-back-over-empty-lines))
6602 (setq beg (point))
6603 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6604 (insert-before-markers txt)
6605 (unless (string-match "\n\\'" txt) (insert "\n"))
6606 (setq newend (point))
6607 (org-reinstall-markers-in-region beg)
6608 (setq end (point))
6609 (goto-char beg)
6610 (skip-chars-forward " \t\n\r")
6611 (setq beg (point))
6612 (if (and (org-invisible-p) visp)
6613 (save-excursion (outline-show-heading)))
6614 ;; Shift if necessary
6615 (unless (= shift 0)
6616 (save-restriction
6617 (narrow-to-region beg end)
6618 (while (not (= shift 0))
6619 (org-map-region func (point-min) (point-max))
6620 (setq shift (+ delta shift)))
6621 (goto-char (point-min))
6622 (setq newend (point-max))))
6623 (when (or (interactive-p) for-yank)
6624 (message "Clipboard pasted as level %d subtree" new-level))
6625 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6626 kill-ring
6627 (eq org-subtree-clip (current-kill 0))
6628 org-subtree-clip-folded)
6629 ;; The tree was folded before it was killed/copied
6630 (hide-subtree))
6631 (and for-yank (goto-char newend))))
6633 (defun org-kill-is-subtree-p (&optional txt)
6634 "Check if the current kill is an outline subtree, or a set of trees.
6635 Returns nil if kill does not start with a headline, or if the first
6636 headline level is not the largest headline level in the tree.
6637 So this will actually accept several entries of equal levels as well,
6638 which is OK for `org-paste-subtree'.
6639 If optional TXT is given, check this string instead of the current kill."
6640 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6641 (start-level (and kill
6642 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6643 org-outline-regexp "\\)")
6644 kill)
6645 (- (match-end 2) (match-beginning 2) 1)))
6646 (re (concat "^" org-outline-regexp))
6647 (start (1+ (or (match-beginning 2) -1))))
6648 (if (not start-level)
6649 (progn
6650 nil) ;; does not even start with a heading
6651 (catch 'exit
6652 (while (setq start (string-match re kill (1+ start)))
6653 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6654 (throw 'exit nil)))
6655 t))))
6657 (defvar org-markers-to-move nil
6658 "Markers that should be moved with a cut-and-paste operation.
6659 Those markers are stored together with their positions relative to
6660 the start of the region.")
6662 (defun org-save-markers-in-region (beg end)
6663 "Check markers in region.
6664 If these markers are between BEG and END, record their position relative
6665 to BEG, so that after moving the block of text, we can put the markers back
6666 into place.
6667 This function gets called just before an entry or tree gets cut from the
6668 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6669 called immediately, to move the markers with the entries."
6670 (setq org-markers-to-move nil)
6671 (when (featurep 'org-clock)
6672 (org-clock-save-markers-for-cut-and-paste beg end))
6673 (when (featurep 'org-agenda)
6674 (org-agenda-save-markers-for-cut-and-paste beg end)))
6676 (defun org-check-and-save-marker (marker beg end)
6677 "Check if MARKER is between BEG and END.
6678 If yes, remember the marker and the distance to BEG."
6679 (when (and (marker-buffer marker)
6680 (equal (marker-buffer marker) (current-buffer)))
6681 (if (and (>= marker beg) (< marker end))
6682 (push (cons marker (- marker beg)) org-markers-to-move))))
6684 (defun org-reinstall-markers-in-region (beg)
6685 "Move all remembered markers to their position relative to BEG."
6686 (mapc (lambda (x)
6687 (move-marker (car x) (+ beg (cdr x))))
6688 org-markers-to-move)
6689 (setq org-markers-to-move nil))
6691 (defun org-narrow-to-subtree ()
6692 "Narrow buffer to the current subtree."
6693 (interactive)
6694 (save-excursion
6695 (save-match-data
6696 (narrow-to-region
6697 (progn (org-back-to-heading t) (point))
6698 (progn (org-end-of-subtree t t) (point))))))
6700 (defun org-clone-subtree-with-time-shift (n &optional shift)
6701 "Clone the task (subtree) at point N times.
6702 The clones will be inserted as siblings.
6704 In interactive use, the user will be prompted for the number of clones
6705 to be produced, and for a time SHIFT, which may be a repeater as used
6706 in time stamps, for example `+3d'.
6708 When a valid repeater is given and the entry contains any time stamps,
6709 the clones will become a sequence in time, with time stamps in the
6710 subtree shifted for each clone produced. If SHIFT is nil or the
6711 empty string, time stamps will be left alone.
6713 If the original subtree did contain time stamps with a repeater,
6714 the following will happen:
6715 - the repeater will be removed in each clone
6716 - an additional clone will be produced, with the current, unshifted
6717 date(s) in the entry.
6718 - the original entry will be placed *after* all the clones, with
6719 repeater intact.
6720 - the start days in the repeater in the original entry will be shifted
6721 to past the last clone.
6722 I this way you can spell out a number of instances of a repeating task,
6723 and still retain the repeater to cover future instances of the task."
6724 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6725 (let (beg end template task
6726 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6727 (if (not (and (integerp n) (> n 0)))
6728 (error "Invalid number of replications %s" n))
6729 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6730 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6731 shift)))
6732 (error "Invalid shift specification %s" shift))
6733 (when doshift
6734 (setq shift-n (string-to-number (match-string 1 shift))
6735 shift-what (cdr (assoc (match-string 2 shift)
6736 '(("d" . day) ("w" . week)
6737 ("m" . month) ("y" . year))))))
6738 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6739 (setq nmin 1 nmax n)
6740 (org-back-to-heading t)
6741 (setq beg (point))
6742 (org-end-of-subtree t t)
6743 (or (bolp) (insert "\n"))
6744 (setq end (point))
6745 (setq template (buffer-substring beg end))
6746 (when (and doshift
6747 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6748 (delete-region beg end)
6749 (setq end beg)
6750 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6751 (goto-char end)
6752 (loop for n from nmin to nmax do
6753 (if (not doshift)
6754 (setq task template)
6755 (with-temp-buffer
6756 (insert template)
6757 (org-mode)
6758 (goto-char (point-min))
6759 (while (re-search-forward org-ts-regexp-both nil t)
6760 (org-timestamp-change (* n shift-n) shift-what))
6761 (unless (= n n-no-remove)
6762 (goto-char (point-min))
6763 (while (re-search-forward org-ts-regexp nil t)
6764 (save-excursion
6765 (goto-char (match-beginning 0))
6766 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6767 (delete-region (match-beginning 1) (match-end 1))))))
6768 (setq task (buffer-string))))
6769 (insert task))
6770 (goto-char beg)))
6772 ;;; Outline Sorting
6774 (defun org-sort (with-case)
6775 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6776 Optional argument WITH-CASE means sort case-sensitively.
6777 With a double prefix argument, also remove duplicate entries."
6778 (interactive "P")
6779 (if (org-at-table-p)
6780 (org-call-with-arg 'org-table-sort-lines with-case)
6781 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6783 (defun org-sort-remove-invisible (s)
6784 (remove-text-properties 0 (length s) org-rm-props s)
6785 (while (string-match org-bracket-link-regexp s)
6786 (setq s (replace-match (if (match-end 2)
6787 (match-string 3 s)
6788 (match-string 1 s)) t t s)))
6791 (defvar org-priority-regexp) ; defined later in the file
6793 (defvar org-after-sorting-entries-or-items-hook nil
6794 "Hook that is run after a bunch of entries or items have been sorted.
6795 When children are sorted, the cursor is in the parent line when this
6796 hook gets called. When a region or a plain list is sorted, the cursor
6797 will be in the first entry of the sorted region/list.")
6799 (defun org-sort-entries-or-items
6800 (&optional with-case sorting-type getkey-func compare-func property)
6801 "Sort entries on a certain level of an outline tree, or plain list items.
6802 If there is an active region, the entries in the region are sorted.
6803 Else, if the cursor is before the first entry, sort the top-level items.
6804 Else, the children of the entry at point are sorted.
6805 If the cursor is at the first item in a plain list, the list items will be
6806 sorted.
6808 Sorting can be alphabetically, numerically, by date/time as given by
6809 a time stamp, by a property or by priority.
6811 The command prompts for the sorting type unless it has been given to the
6812 function through the SORTING-TYPE argument, which needs to a character,
6813 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6814 precise meaning of each character:
6816 n Numerically, by converting the beginning of the entry/item to a number.
6817 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6818 t By date/time, either the first active time stamp in the entry, or, if
6819 none exist, by the first inactive one.
6820 In items, only the first line will be checked.
6821 s By the scheduled date/time.
6822 d By deadline date/time.
6823 c By creation time, which is assumed to be the first inactive time stamp
6824 at the beginning of a line.
6825 p By priority according to the cookie.
6826 r By the value of a property.
6828 Capital letters will reverse the sort order.
6830 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6831 called with point at the beginning of the record. It must return either
6832 a string or a number that should serve as the sorting key for that record.
6834 Comparing entries ignores case by default. However, with an optional argument
6835 WITH-CASE, the sorting considers case as well."
6836 (interactive "P")
6837 (let ((case-func (if with-case 'identity 'downcase))
6838 start beg end stars re re2
6839 txt what tmp plain-list-p)
6840 ;; Find beginning and end of region to sort
6841 (cond
6842 ((org-region-active-p)
6843 ;; we will sort the region
6844 (setq end (region-end)
6845 what "region")
6846 (goto-char (region-beginning))
6847 (if (not (org-on-heading-p)) (outline-next-heading))
6848 (setq start (point)))
6849 ((org-at-item-p)
6850 ;; we will sort this plain list
6851 (org-beginning-of-item-list) (setq start (point))
6852 (org-end-of-item-list) (setq end (point))
6853 (goto-char start)
6854 (setq plain-list-p t
6855 what "plain list"))
6856 ((or (org-on-heading-p)
6857 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6858 ;; we will sort the children of the current headline
6859 (org-back-to-heading)
6860 (setq start (point)
6861 end (progn (org-end-of-subtree t t)
6862 (org-back-over-empty-lines)
6863 (point))
6864 what "children")
6865 (goto-char start)
6866 (show-subtree)
6867 (outline-next-heading))
6869 ;; we will sort the top-level entries in this file
6870 (goto-char (point-min))
6871 (or (org-on-heading-p) (outline-next-heading))
6872 (setq start (point) end (point-max) what "top-level")
6873 (goto-char start)
6874 (show-all)))
6876 (setq beg (point))
6877 (if (>= beg end) (error "Nothing to sort"))
6879 (unless plain-list-p
6880 (looking-at "\\(\\*+\\)")
6881 (setq stars (match-string 1)
6882 re (concat "^" (regexp-quote stars) " +")
6883 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6884 txt (buffer-substring beg end))
6885 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6886 (if (and (not (equal stars "*")) (string-match re2 txt))
6887 (error "Region to sort contains a level above the first entry")))
6889 (unless sorting-type
6890 (message
6891 (if plain-list-p
6892 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6893 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6894 [t]ime [s]cheduled [d]eadline [c]reated
6895 A/N/T/S/D/C/P/O/F means reversed:")
6896 what)
6897 (setq sorting-type (read-char-exclusive))
6899 (and (= (downcase sorting-type) ?f)
6900 (setq getkey-func
6901 (org-icompleting-read "Sort using function: "
6902 obarray 'fboundp t nil nil))
6903 (setq getkey-func (intern getkey-func)))
6905 (and (= (downcase sorting-type) ?r)
6906 (setq property
6907 (org-icompleting-read "Property: "
6908 (mapcar 'list (org-buffer-property-keys t))
6909 nil t))))
6911 (message "Sorting entries...")
6913 (save-restriction
6914 (narrow-to-region start end)
6916 (let ((dcst (downcase sorting-type))
6917 (case-fold-search nil)
6918 (now (current-time)))
6919 (sort-subr
6920 (/= dcst sorting-type)
6921 ;; This function moves to the beginning character of the "record" to
6922 ;; be sorted.
6923 (if plain-list-p
6924 (lambda nil
6925 (if (org-at-item-p) t (goto-char (point-max))))
6926 (lambda nil
6927 (if (re-search-forward re nil t)
6928 (goto-char (match-beginning 0))
6929 (goto-char (point-max)))))
6930 ;; This function moves to the last character of the "record" being
6931 ;; sorted.
6932 (if plain-list-p
6933 'org-end-of-item
6934 (lambda nil
6935 (save-match-data
6936 (condition-case nil
6937 (outline-forward-same-level 1)
6938 (error
6939 (goto-char (point-max)))))))
6941 ;; This function returns the value that gets sorted against.
6942 (if plain-list-p
6943 (lambda nil
6944 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6945 (cond
6946 ((= dcst ?n)
6947 (string-to-number (buffer-substring (match-end 0)
6948 (point-at-eol))))
6949 ((= dcst ?a)
6950 (buffer-substring (match-end 0) (point-at-eol)))
6951 ((= dcst ?t)
6952 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6953 (re-search-forward org-ts-regexp-both
6954 (point-at-eol) t))
6955 (org-time-string-to-seconds (match-string 0))
6956 (org-float-time now)))
6957 ((= dcst ?f)
6958 (if getkey-func
6959 (progn
6960 (setq tmp (funcall getkey-func))
6961 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6962 tmp)
6963 (error "Invalid key function `%s'" getkey-func)))
6964 (t (error "Invalid sorting type `%c'" sorting-type)))))
6965 (lambda nil
6966 (cond
6967 ((= dcst ?n)
6968 (if (looking-at org-complex-heading-regexp)
6969 (string-to-number (match-string 4))
6970 nil))
6971 ((= dcst ?a)
6972 (if (looking-at org-complex-heading-regexp)
6973 (funcall case-func (match-string 4))
6974 nil))
6975 ((= dcst ?t)
6976 (let ((end (save-excursion (outline-next-heading) (point))))
6977 (if (or (re-search-forward org-ts-regexp end t)
6978 (re-search-forward org-ts-regexp-both end t))
6979 (org-time-string-to-seconds (match-string 0))
6980 (org-float-time now))))
6981 ((= dcst ?c)
6982 (let ((end (save-excursion (outline-next-heading) (point))))
6983 (if (re-search-forward
6984 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6985 end t)
6986 (org-time-string-to-seconds (match-string 0))
6987 (org-float-time now))))
6988 ((= dcst ?s)
6989 (let ((end (save-excursion (outline-next-heading) (point))))
6990 (if (re-search-forward org-scheduled-time-regexp end t)
6991 (org-time-string-to-seconds (match-string 1))
6992 (org-float-time now))))
6993 ((= dcst ?d)
6994 (let ((end (save-excursion (outline-next-heading) (point))))
6995 (if (re-search-forward org-deadline-time-regexp end t)
6996 (org-time-string-to-seconds (match-string 1))
6997 (org-float-time now))))
6998 ((= dcst ?p)
6999 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7000 (string-to-char (match-string 2))
7001 org-default-priority))
7002 ((= dcst ?r)
7003 (or (org-entry-get nil property) ""))
7004 ((= dcst ?o)
7005 (if (looking-at org-complex-heading-regexp)
7006 (- 9999 (length (member (match-string 2)
7007 org-todo-keywords-1)))))
7008 ((= dcst ?f)
7009 (if getkey-func
7010 (progn
7011 (setq tmp (funcall getkey-func))
7012 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7013 tmp)
7014 (error "Invalid key function `%s'" getkey-func)))
7015 (t (error "Invalid sorting type `%c'" sorting-type)))))
7017 (cond
7018 ((= dcst ?a) 'string<)
7019 ((= dcst ?f) compare-func)
7020 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7021 (t nil)))))
7022 (run-hooks 'org-after-sorting-entries-or-items-hook)
7023 (message "Sorting entries...done")))
7025 (defun org-do-sort (table what &optional with-case sorting-type)
7026 "Sort TABLE of WHAT according to SORTING-TYPE.
7027 The user will be prompted for the SORTING-TYPE if the call to this
7028 function does not specify it. WHAT is only for the prompt, to indicate
7029 what is being sorted. The sorting key will be extracted from
7030 the car of the elements of the table.
7031 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7032 (unless sorting-type
7033 (message
7034 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7035 what)
7036 (setq sorting-type (read-char-exclusive)))
7037 (let ((dcst (downcase sorting-type))
7038 extractfun comparefun)
7039 ;; Define the appropriate functions
7040 (cond
7041 ((= dcst ?n)
7042 (setq extractfun 'string-to-number
7043 comparefun (if (= dcst sorting-type) '< '>)))
7044 ((= dcst ?a)
7045 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7046 (lambda(x) (downcase (org-sort-remove-invisible x))))
7047 comparefun (if (= dcst sorting-type)
7048 'string<
7049 (lambda (a b) (and (not (string< a b))
7050 (not (string= a b)))))))
7051 ((= dcst ?t)
7052 (setq extractfun
7053 (lambda (x)
7054 (if (or (string-match org-ts-regexp x)
7055 (string-match org-ts-regexp-both x))
7056 (org-float-time
7057 (org-time-string-to-time (match-string 0 x)))
7059 comparefun (if (= dcst sorting-type) '< '>)))
7060 (t (error "Invalid sorting type `%c'" sorting-type)))
7062 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7063 table)
7064 (lambda (a b) (funcall comparefun (car a) (car b))))))
7067 ;;; The orgstruct minor mode
7069 ;; Define a minor mode which can be used in other modes in order to
7070 ;; integrate the org-mode structure editing commands.
7072 ;; This is really a hack, because the org-mode structure commands use
7073 ;; keys which normally belong to the major mode. Here is how it
7074 ;; works: The minor mode defines all the keys necessary to operate the
7075 ;; structure commands, but wraps the commands into a function which
7076 ;; tests if the cursor is currently at a headline or a plain list
7077 ;; item. If that is the case, the structure command is used,
7078 ;; temporarily setting many Org-mode variables like regular
7079 ;; expressions for filling etc. However, when any of those keys is
7080 ;; used at a different location, function uses `key-binding' to look
7081 ;; up if the key has an associated command in another currently active
7082 ;; keymap (minor modes, major mode, global), and executes that
7083 ;; command. There might be problems if any of the keys is otherwise
7084 ;; used as a prefix key.
7086 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7087 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7088 ;; addresses this by checking explicitly for both bindings.
7090 (defvar orgstruct-mode-map (make-sparse-keymap)
7091 "Keymap for the minor `orgstruct-mode'.")
7093 (defvar org-local-vars nil
7094 "List of local variables, for use by `orgstruct-mode'")
7096 ;;;###autoload
7097 (define-minor-mode orgstruct-mode
7098 "Toggle the minor more `orgstruct-mode'.
7099 This mode is for using Org-mode structure commands in other modes.
7100 The following key behave as if Org-mode was active, if the cursor
7101 is on a headline, or on a plain list item (both in the definition
7102 of Org-mode).
7104 M-up Move entry/item up
7105 M-down Move entry/item down
7106 M-left Promote
7107 M-right Demote
7108 M-S-up Move entry/item up
7109 M-S-down Move entry/item down
7110 M-S-left Promote subtree
7111 M-S-right Demote subtree
7112 M-q Fill paragraph and items like in Org-mode
7113 C-c ^ Sort entries
7114 C-c - Cycle list bullet
7115 TAB Cycle item visibility
7116 M-RET Insert new heading/item
7117 S-M-RET Insert new TODO heading / Checkbox item
7118 C-c C-c Set tags / toggle checkbox"
7119 nil " OrgStruct" nil
7120 (org-load-modules-maybe)
7121 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7123 ;;;###autoload
7124 (defun turn-on-orgstruct ()
7125 "Unconditionally turn on `orgstruct-mode'."
7126 (orgstruct-mode 1))
7128 (defun orgstruct++-mode (&optional arg)
7129 "Toggle `orgstruct-mode', the enhanced version of it.
7130 In addition to setting orgstruct-mode, this also exports all indentation
7131 and autofilling variables from org-mode into the buffer. It will also
7132 recognize item context in multiline items.
7133 Note that turning off orgstruct-mode will *not* remove the
7134 indentation/paragraph settings. This can only be done by refreshing the
7135 major mode, for example with \\[normal-mode]."
7136 (interactive "P")
7137 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7138 (if (< arg 1)
7139 (orgstruct-mode -1)
7140 (orgstruct-mode 1)
7141 (let (var val)
7142 (mapc
7143 (lambda (x)
7144 (when (string-match
7145 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7146 (symbol-name (car x)))
7147 (setq var (car x) val (nth 1 x))
7148 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7149 org-local-vars)
7150 (org-set-local 'orgstruct-is-++ t))))
7152 (defvar orgstruct-is-++ nil
7153 "Is orgstruct-mode in ++ version in the current-buffer?")
7154 (make-variable-buffer-local 'orgstruct-is-++)
7156 ;;;###autoload
7157 (defun turn-on-orgstruct++ ()
7158 "Unconditionally turn on `orgstruct++-mode'."
7159 (orgstruct++-mode 1))
7161 (defun orgstruct-error ()
7162 "Error when there is no default binding for a structure key."
7163 (interactive)
7164 (error "This key has no function outside structure elements"))
7166 (defun orgstruct-setup ()
7167 "Setup orgstruct keymaps."
7168 (let ((nfunc 0)
7169 (bindings
7170 (list
7171 '([(meta up)] org-metaup)
7172 '([(meta down)] org-metadown)
7173 '([(meta left)] org-metaleft)
7174 '([(meta right)] org-metaright)
7175 '([(meta shift up)] org-shiftmetaup)
7176 '([(meta shift down)] org-shiftmetadown)
7177 '([(meta shift left)] org-shiftmetaleft)
7178 '([(meta shift right)] org-shiftmetaright)
7179 '([?\e (up)] org-metaup)
7180 '([?\e (down)] org-metadown)
7181 '([?\e (left)] org-metaleft)
7182 '([?\e (right)] org-metaright)
7183 '([?\e (shift up)] org-shiftmetaup)
7184 '([?\e (shift down)] org-shiftmetadown)
7185 '([?\e (shift left)] org-shiftmetaleft)
7186 '([?\e (shift right)] org-shiftmetaright)
7187 '([(shift up)] org-shiftup)
7188 '([(shift down)] org-shiftdown)
7189 '([(shift left)] org-shiftleft)
7190 '([(shift right)] org-shiftright)
7191 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7192 '("\M-q" fill-paragraph)
7193 '("\C-c^" org-sort)
7194 '("\C-c-" org-cycle-list-bullet)))
7195 elt key fun cmd)
7196 (while (setq elt (pop bindings))
7197 (setq nfunc (1+ nfunc))
7198 (setq key (org-key (car elt))
7199 fun (nth 1 elt)
7200 cmd (orgstruct-make-binding fun nfunc key))
7201 (org-defkey orgstruct-mode-map key cmd))
7203 ;; Special treatment needed for TAB and RET
7204 (org-defkey orgstruct-mode-map [(tab)]
7205 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7206 (org-defkey orgstruct-mode-map "\C-i"
7207 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7209 (org-defkey orgstruct-mode-map "\M-\C-m"
7210 (orgstruct-make-binding 'org-insert-heading 105
7211 "\M-\C-m" [(meta return)]))
7212 (org-defkey orgstruct-mode-map [(meta return)]
7213 (orgstruct-make-binding 'org-insert-heading 106
7214 [(meta return)] "\M-\C-m"))
7216 (org-defkey orgstruct-mode-map [(shift meta return)]
7217 (orgstruct-make-binding 'org-insert-todo-heading 107
7218 [(meta return)] "\M-\C-m"))
7220 (org-defkey orgstruct-mode-map "\e\C-m"
7221 (orgstruct-make-binding 'org-insert-heading 108
7222 "\e\C-m" [?\e (return)]))
7223 (org-defkey orgstruct-mode-map [?\e (return)]
7224 (orgstruct-make-binding 'org-insert-heading 109
7225 [?\e (return)] "\e\C-m"))
7226 (org-defkey orgstruct-mode-map [?\e (shift return)]
7227 (orgstruct-make-binding 'org-insert-todo-heading 110
7228 [?\e (return)] "\e\C-m"))
7230 (unless org-local-vars
7231 (setq org-local-vars (org-get-local-variables)))
7235 (defun orgstruct-make-binding (fun n &rest keys)
7236 "Create a function for binding in the structure minor mode.
7237 FUN is the command to call inside a table. N is used to create a unique
7238 command name. KEYS are keys that should be checked in for a command
7239 to execute outside of tables."
7240 (eval
7241 (list 'defun
7242 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7243 '(arg)
7244 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7245 "Outside of structure, run the binding of `"
7246 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7247 "'.")
7248 '(interactive "p")
7249 (list 'if
7250 `(org-context-p 'headline 'item
7251 (and orgstruct-is-++
7252 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7253 'item-body))
7254 (list 'org-run-like-in-org-mode (list 'quote fun))
7255 (list 'let '(orgstruct-mode)
7256 (list 'call-interactively
7257 (append '(or)
7258 (mapcar (lambda (k)
7259 (list 'key-binding k))
7260 keys)
7261 '('orgstruct-error))))))))
7263 (defun org-context-p (&rest contexts)
7264 "Check if local context is any of CONTEXTS.
7265 Possible values in the list of contexts are `table', `headline', and `item'."
7266 (let ((pos (point)))
7267 (goto-char (point-at-bol))
7268 (prog1 (or (and (memq 'table contexts)
7269 (looking-at "[ \t]*|"))
7270 (and (memq 'headline contexts)
7271 ;;????????? (looking-at "\\*+"))
7272 (looking-at outline-regexp))
7273 (and (memq 'item contexts)
7274 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7275 (and (memq 'item-body contexts)
7276 (org-in-item-p)))
7277 (goto-char pos))))
7279 (defun org-get-local-variables ()
7280 "Return a list of all local variables in an org-mode buffer."
7281 (let (varlist)
7282 (with-current-buffer (get-buffer-create "*Org tmp*")
7283 (erase-buffer)
7284 (org-mode)
7285 (setq varlist (buffer-local-variables)))
7286 (kill-buffer "*Org tmp*")
7287 (delq nil
7288 (mapcar
7289 (lambda (x)
7290 (setq x
7291 (if (symbolp x)
7292 (list x)
7293 (list (car x) (list 'quote (cdr x)))))
7294 (if (string-match
7295 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7296 (symbol-name (car x)))
7297 x nil))
7298 varlist))))
7300 ;;;###autoload
7301 (defun org-run-like-in-org-mode (cmd)
7302 "Run a command, pretending that the current buffer is in Org-mode.
7303 This will temporarily bind local variables that are typically bound in
7304 Org-mode to the values they have in Org-mode, and then interactively
7305 call CMD."
7306 (org-load-modules-maybe)
7307 (unless org-local-vars
7308 (setq org-local-vars (org-get-local-variables)))
7309 (eval (list 'let org-local-vars
7310 (list 'call-interactively (list 'quote cmd)))))
7312 ;;;; Archiving
7314 (defun org-get-category (&optional pos)
7315 "Get the category applying to position POS."
7316 (get-text-property (or pos (point)) 'org-category))
7318 (defun org-refresh-category-properties ()
7319 "Refresh category text properties in the buffer."
7320 (let ((def-cat (cond
7321 ((null org-category)
7322 (if buffer-file-name
7323 (file-name-sans-extension
7324 (file-name-nondirectory buffer-file-name))
7325 "???"))
7326 ((symbolp org-category) (symbol-name org-category))
7327 (t org-category)))
7328 beg end cat pos optionp)
7329 (org-unmodified
7330 (save-excursion
7331 (save-restriction
7332 (widen)
7333 (goto-char (point-min))
7334 (put-text-property (point) (point-max) 'org-category def-cat)
7335 (while (re-search-forward
7336 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7337 (setq pos (match-end 0)
7338 optionp (equal (char-after (match-beginning 0)) ?#)
7339 cat (org-trim (match-string 2)))
7340 (if optionp
7341 (setq beg (point-at-bol) end (point-max))
7342 (org-back-to-heading t)
7343 (setq beg (point) end (org-end-of-subtree t t)))
7344 (put-text-property beg end 'org-category cat)
7345 (goto-char pos)))))))
7348 ;;;; Link Stuff
7350 ;;; Link abbreviations
7352 (defun org-link-expand-abbrev (link)
7353 "Apply replacements as defined in `org-link-abbrev-alist."
7354 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7355 (let* ((key (match-string 1 link))
7356 (as (or (assoc key org-link-abbrev-alist-local)
7357 (assoc key org-link-abbrev-alist)))
7358 (tag (and (match-end 2) (match-string 3 link)))
7359 rpl)
7360 (if (not as)
7361 link
7362 (setq rpl (cdr as))
7363 (cond
7364 ((symbolp rpl) (funcall rpl tag))
7365 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7366 ((string-match "%h" rpl)
7367 (replace-match (url-hexify-string (or tag "")) t t rpl))
7368 (t (concat rpl tag)))))
7369 link))
7371 ;;; Storing and inserting links
7373 (defvar org-insert-link-history nil
7374 "Minibuffer history for links inserted with `org-insert-link'.")
7376 (defvar org-stored-links nil
7377 "Contains the links stored with `org-store-link'.")
7379 (defvar org-store-link-plist nil
7380 "Plist with info about the most recently link created with `org-store-link'.")
7382 (defvar org-link-protocols nil
7383 "Link protocols added to Org-mode using `org-add-link-type'.")
7385 (defvar org-store-link-functions nil
7386 "List of functions that are called to create and store a link.
7387 Each function will be called in turn until one returns a non-nil
7388 value. Each function should check if it is responsible for creating
7389 this link (for example by looking at the major mode).
7390 If not, it must exit and return nil.
7391 If yes, it should return a non-nil value after a calling
7392 `org-store-link-props' with a list of properties and values.
7393 Special properties are:
7395 :type The link prefix. like \"http\". This must be given.
7396 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7397 This is obligatory as well.
7398 :description Optional default description for the second pair
7399 of brackets in an Org-mode link. The user can still change
7400 this when inserting this link into an Org-mode buffer.
7402 In addition to these, any additional properties can be specified
7403 and then used in remember templates.")
7405 (defun org-add-link-type (type &optional follow export)
7406 "Add TYPE to the list of `org-link-types'.
7407 Re-compute all regular expressions depending on `org-link-types'
7409 FOLLOW and EXPORT are two functions.
7411 FOLLOW should take the link path as the single argument and do whatever
7412 is necessary to follow the link, for example find a file or display
7413 a mail message.
7415 EXPORT should format the link path for export to one of the export formats.
7416 It should be a function accepting three arguments:
7418 path the path of the link, the text after the prefix (like \"http:\")
7419 desc the description of the link, if any, nil if there was no description
7420 format the export format, a symbol like `html' or `latex'.
7422 The function may use the FORMAT information to return different values
7423 depending on the format. The return value will be put literally into
7424 the exported file.
7425 Org-mode has a built-in default for exporting links. If you are happy with
7426 this default, there is no need to define an export function for the link
7427 type. For a simple example of an export function, see `org-bbdb.el'."
7428 (add-to-list 'org-link-types type t)
7429 (org-make-link-regexps)
7430 (if (assoc type org-link-protocols)
7431 (setcdr (assoc type org-link-protocols) (list follow export))
7432 (push (list type follow export) org-link-protocols)))
7434 (defvar org-agenda-buffer-name)
7436 ;;;###autoload
7437 (defun org-store-link (arg)
7438 "\\<org-mode-map>Store an org-link to the current location.
7439 This link is added to `org-stored-links' and can later be inserted
7440 into an org-buffer with \\[org-insert-link].
7442 For some link types, a prefix arg is interpreted:
7443 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7444 For file links, arg negates `org-context-in-file-links'."
7445 (interactive "P")
7446 (org-load-modules-maybe)
7447 (setq org-store-link-plist nil) ; reset
7448 (let ((outline-regexp (org-get-limited-outline-regexp))
7449 link cpltxt desc description search txt custom-id)
7450 (cond
7452 ((run-hook-with-args-until-success 'org-store-link-functions)
7453 (setq link (plist-get org-store-link-plist :link)
7454 desc (or (plist-get org-store-link-plist :description) link)))
7456 ((equal (buffer-name) "*Org Edit Src Example*")
7457 (let (label gc)
7458 (while (or (not label)
7459 (save-excursion
7460 (save-restriction
7461 (widen)
7462 (goto-char (point-min))
7463 (re-search-forward
7464 (regexp-quote (format org-coderef-label-format label))
7465 nil t))))
7466 (when label (message "Label exists already") (sit-for 2))
7467 (setq label (read-string "Code line label: " label)))
7468 (end-of-line 1)
7469 (setq link (format org-coderef-label-format label))
7470 (setq gc (- 79 (length link)))
7471 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7472 (insert link)
7473 (setq link (concat "(" label ")") desc nil)))
7475 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7476 ;; We are in the agenda, link to referenced location
7477 (let ((m (or (get-text-property (point) 'org-hd-marker)
7478 (get-text-property (point) 'org-marker))))
7479 (when m
7480 (org-with-point-at m
7481 (call-interactively 'org-store-link)))))
7483 ((eq major-mode 'calendar-mode)
7484 (let ((cd (calendar-cursor-to-date)))
7485 (setq link
7486 (format-time-string
7487 (car org-time-stamp-formats)
7488 (apply 'encode-time
7489 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7490 nil nil nil))))
7491 (org-store-link-props :type "calendar" :date cd)))
7493 ((eq major-mode 'w3-mode)
7494 (setq cpltxt (if (and (buffer-name)
7495 (not (string-match "Untitled" (buffer-name))))
7496 (buffer-name)
7497 (url-view-url t))
7498 link (org-make-link (url-view-url t)))
7499 (org-store-link-props :type "w3" :url (url-view-url t)))
7501 ((eq major-mode 'w3m-mode)
7502 (setq cpltxt (or w3m-current-title w3m-current-url)
7503 link (org-make-link w3m-current-url))
7504 (org-store-link-props :type "w3m" :url (url-view-url t)))
7506 ((setq search (run-hook-with-args-until-success
7507 'org-create-file-search-functions))
7508 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7509 "::" search))
7510 (setq cpltxt (or description link)))
7512 ((eq major-mode 'image-mode)
7513 (setq cpltxt (concat "file:"
7514 (abbreviate-file-name buffer-file-name))
7515 link (org-make-link cpltxt))
7516 (org-store-link-props :type "image" :file buffer-file-name))
7518 ((eq major-mode 'dired-mode)
7519 ;; link to the file in the current line
7520 (setq cpltxt (concat "file:"
7521 (abbreviate-file-name
7522 (expand-file-name
7523 (dired-get-filename nil t))))
7524 link (org-make-link cpltxt)))
7526 ((and buffer-file-name (org-mode-p))
7527 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7528 (cond
7529 ((org-in-regexp "<<\\(.*?\\)>>")
7530 (setq cpltxt
7531 (concat "file:"
7532 (abbreviate-file-name buffer-file-name)
7533 "::" (match-string 1))
7534 link (org-make-link cpltxt)))
7535 ((and (featurep 'org-id)
7536 (or (eq org-link-to-org-use-id t)
7537 (and (eq org-link-to-org-use-id 'create-if-interactive)
7538 (interactive-p))
7539 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7540 (interactive-p)
7541 (not custom-id))
7542 (and org-link-to-org-use-id
7543 (condition-case nil
7544 (org-entry-get nil "ID")
7545 (error nil)))))
7546 ;; We can make a link using the ID.
7547 (setq link (condition-case nil
7548 (prog1 (org-id-store-link)
7549 (setq desc (plist-get org-store-link-plist
7550 :description)))
7551 (error
7552 ;; probably before first headline, link to file only
7553 (concat "file:"
7554 (abbreviate-file-name buffer-file-name))))))
7556 ;; Just link to current headline
7557 (setq cpltxt (concat "file:"
7558 (abbreviate-file-name buffer-file-name)))
7559 ;; Add a context search string
7560 (when (org-xor org-context-in-file-links arg)
7561 (setq txt (cond
7562 ((org-on-heading-p) nil)
7563 ((org-region-active-p)
7564 (buffer-substring (region-beginning) (region-end)))
7565 (t nil)))
7566 (when (or (null txt) (string-match "\\S-" txt))
7567 (setq cpltxt
7568 (concat cpltxt "::"
7569 (condition-case nil
7570 (org-make-org-heading-search-string txt)
7571 (error "")))
7572 desc (or (nth 4 (ignore-errors
7573 (org-heading-components))) "NONE"))))
7574 (if (string-match "::\\'" cpltxt)
7575 (setq cpltxt (substring cpltxt 0 -2)))
7576 (setq link (org-make-link cpltxt)))))
7578 ((buffer-file-name (buffer-base-buffer))
7579 ;; Just link to this file here.
7580 (setq cpltxt (concat "file:"
7581 (abbreviate-file-name
7582 (buffer-file-name (buffer-base-buffer)))))
7583 ;; Add a context string
7584 (when (org-xor org-context-in-file-links arg)
7585 (setq txt (if (org-region-active-p)
7586 (buffer-substring (region-beginning) (region-end))
7587 (buffer-substring (point-at-bol) (point-at-eol))))
7588 ;; Only use search option if there is some text.
7589 (when (string-match "\\S-" txt)
7590 (setq cpltxt
7591 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7592 desc "NONE")))
7593 (setq link (org-make-link cpltxt)))
7595 ((interactive-p)
7596 (error "Cannot link to a buffer which is not visiting a file"))
7598 (t (setq link nil)))
7600 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7601 (setq link (or link cpltxt)
7602 desc (or desc cpltxt))
7603 (if (equal desc "NONE") (setq desc nil))
7605 (if (and (or (interactive-p) executing-kbd-macro) link)
7606 (progn
7607 (setq org-stored-links
7608 (cons (list link desc) org-stored-links))
7609 (message "Stored: %s" (or desc link))
7610 (when custom-id
7611 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7612 "::#" custom-id))
7613 (setq org-stored-links
7614 (cons (list link desc) org-stored-links))))
7615 (and link (org-make-link-string link desc)))))
7617 (defun org-store-link-props (&rest plist)
7618 "Store link properties, extract names and addresses."
7619 (let (x adr)
7620 (when (setq x (plist-get plist :from))
7621 (setq adr (mail-extract-address-components x))
7622 (setq plist (plist-put plist :fromname (car adr)))
7623 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7624 (when (setq x (plist-get plist :to))
7625 (setq adr (mail-extract-address-components x))
7626 (setq plist (plist-put plist :toname (car adr)))
7627 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7628 (let ((from (plist-get plist :from))
7629 (to (plist-get plist :to)))
7630 (when (and from to org-from-is-user-regexp)
7631 (setq plist
7632 (plist-put plist :fromto
7633 (if (string-match org-from-is-user-regexp from)
7634 (concat "to %t")
7635 (concat "from %f"))))))
7636 (setq org-store-link-plist plist))
7638 (defun org-add-link-props (&rest plist)
7639 "Add these properties to the link property list."
7640 (let (key value)
7641 (while plist
7642 (setq key (pop plist) value (pop plist))
7643 (setq org-store-link-plist
7644 (plist-put org-store-link-plist key value)))))
7646 (defun org-email-link-description (&optional fmt)
7647 "Return the description part of an email link.
7648 This takes information from `org-store-link-plist' and formats it
7649 according to FMT (default from `org-email-link-description-format')."
7650 (setq fmt (or fmt org-email-link-description-format))
7651 (let* ((p org-store-link-plist)
7652 (to (plist-get p :toaddress))
7653 (from (plist-get p :fromaddress))
7654 (table
7655 (list
7656 (cons "%c" (plist-get p :fromto))
7657 (cons "%F" (plist-get p :from))
7658 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7659 (cons "%T" (plist-get p :to))
7660 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7661 (cons "%s" (plist-get p :subject))
7662 (cons "%m" (plist-get p :message-id)))))
7663 (when (string-match "%c" fmt)
7664 ;; Check if the user wrote this message
7665 (if (and org-from-is-user-regexp from to
7666 (save-match-data (string-match org-from-is-user-regexp from)))
7667 (setq fmt (replace-match "to %t" t t fmt))
7668 (setq fmt (replace-match "from %f" t t fmt))))
7669 (org-replace-escapes fmt table)))
7671 (defun org-make-org-heading-search-string (&optional string heading)
7672 "Make search string for STRING or current headline."
7673 (interactive)
7674 (let ((s (or string (org-get-heading))))
7675 (unless (and string (not heading))
7676 ;; We are using a headline, clean up garbage in there.
7677 (if (string-match org-todo-regexp s)
7678 (setq s (replace-match "" t t s)))
7679 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7680 (setq s (replace-match "" t t s)))
7681 (setq s (org-trim s))
7682 (if (string-match (concat "^\\(" org-quote-string "\\|"
7683 org-comment-string "\\)") s)
7684 (setq s (replace-match "" t t s)))
7685 (while (string-match org-ts-regexp s)
7686 (setq s (replace-match "" t t s))))
7687 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7688 (setq s (replace-match " " t t s)))
7689 (or string (setq s (concat "*" s))) ; Add * for headlines
7690 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7692 (defun org-make-link (&rest strings)
7693 "Concatenate STRINGS."
7694 (apply 'concat strings))
7696 (defun org-make-link-string (link &optional description)
7697 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7698 (unless (string-match "\\S-" link)
7699 (error "Empty link"))
7700 (when (stringp description)
7701 ;; Remove brackets from the description, they are fatal.
7702 (while (string-match "\\[" description)
7703 (setq description (replace-match "{" t t description)))
7704 (while (string-match "\\]" description)
7705 (setq description (replace-match "}" t t description))))
7706 (when (equal (org-link-escape link) description)
7707 ;; No description needed, it is identical
7708 (setq description nil))
7709 (when (and (not description)
7710 (not (equal link (org-link-escape link))))
7711 (setq description (org-extract-attributes link)))
7712 (concat "[[" (org-link-escape link) "]"
7713 (if description (concat "[" description "]") "")
7714 "]"))
7716 (defconst org-link-escape-chars
7717 '((?\ . "%20")
7718 (?\[ . "%5B")
7719 (?\] . "%5D")
7720 (?\340 . "%E0") ; `a
7721 (?\342 . "%E2") ; ^a
7722 (?\347 . "%E7") ; ,c
7723 (?\350 . "%E8") ; `e
7724 (?\351 . "%E9") ; 'e
7725 (?\352 . "%EA") ; ^e
7726 (?\356 . "%EE") ; ^i
7727 (?\364 . "%F4") ; ^o
7728 (?\371 . "%F9") ; `u
7729 (?\373 . "%FB") ; ^u
7730 (?\; . "%3B")
7731 (?? . "%3F")
7732 (?= . "%3D")
7733 (?+ . "%2B")
7735 "Association list of escapes for some characters problematic in links.
7736 This is the list that is used for internal purposes.")
7738 (defvar org-url-encoding-use-url-hexify nil)
7740 (defconst org-link-escape-chars-browser
7741 '((?\ . "%20")) ; 32 for the SPC char
7742 "Association list of escapes for some characters problematic in links.
7743 This is the list that is used before handing over to the browser.")
7745 (defun org-link-escape (text &optional table)
7746 "Escape characters in TEXT that are problematic for links."
7747 (if org-url-encoding-use-url-hexify
7748 (url-hexify-string text)
7749 (setq table (or table org-link-escape-chars))
7750 (when text
7751 (let ((re (mapconcat (lambda (x) (regexp-quote
7752 (char-to-string (car x))))
7753 table "\\|")))
7754 (while (string-match re text)
7755 (setq text
7756 (replace-match
7757 (cdr (assoc (string-to-char (match-string 0 text))
7758 table))
7759 t t text)))
7760 text))))
7762 (defun org-link-unescape (text &optional table)
7763 "Reverse the action of `org-link-escape'."
7764 (if org-url-encoding-use-url-hexify
7765 (url-unhex-string text)
7766 (setq table (or table org-link-escape-chars))
7767 (when text
7768 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7769 table "\\|")))
7770 (while (string-match re text)
7771 (setq text
7772 (replace-match
7773 (char-to-string (car (rassoc (match-string 0 text) table)))
7774 t t text)))
7775 text))))
7777 (defun org-xor (a b)
7778 "Exclusive or."
7779 (if a (not b) b))
7781 (defun org-fixup-message-id-for-http (s)
7782 "Replace special characters in a message id, so it can be used in an http query."
7783 (while (string-match "<" s)
7784 (setq s (replace-match "%3C" t t s)))
7785 (while (string-match ">" s)
7786 (setq s (replace-match "%3E" t t s)))
7787 (while (string-match "@" s)
7788 (setq s (replace-match "%40" t t s)))
7791 ;;;###autoload
7792 (defun org-insert-link-global ()
7793 "Insert a link like Org-mode does.
7794 This command can be called in any mode to insert a link in Org-mode syntax."
7795 (interactive)
7796 (org-load-modules-maybe)
7797 (org-run-like-in-org-mode 'org-insert-link))
7799 (defun org-insert-link (&optional complete-file link-location)
7800 "Insert a link. At the prompt, enter the link.
7802 Completion can be used to insert any of the link protocol prefixes like
7803 http or ftp in use.
7805 The history can be used to select a link previously stored with
7806 `org-store-link'. When the empty string is entered (i.e. if you just
7807 press RET at the prompt), the link defaults to the most recently
7808 stored link. As SPC triggers completion in the minibuffer, you need to
7809 use M-SPC or C-q SPC to force the insertion of a space character.
7811 You will also be prompted for a description, and if one is given, it will
7812 be displayed in the buffer instead of the link.
7814 If there is already a link at point, this command will allow you to edit link
7815 and description parts.
7817 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7818 be selected using completion. The path to the file will be relative to the
7819 current directory if the file is in the current directory or a subdirectory.
7820 Otherwise, the link will be the absolute path as completed in the minibuffer
7821 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7822 option `org-link-file-path-type'.
7824 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7825 the current directory or below.
7827 With three \\[universal-argument] prefixes, negate the meaning of
7828 `org-keep-stored-link-after-insertion'.
7830 If `org-make-link-description-function' is non-nil, this function will be
7831 called with the link target, and the result will be the default
7832 link description.
7834 If the LINK-LOCATION parameter is non-nil, this value will be
7835 used as the link location instead of reading one interactively."
7836 (interactive "P")
7837 (let* ((wcf (current-window-configuration))
7838 (region (if (org-region-active-p)
7839 (buffer-substring (region-beginning) (region-end))))
7840 (remove (and region (list (region-beginning) (region-end))))
7841 (desc region)
7842 tmphist ; byte-compile incorrectly complains about this
7843 (link link-location)
7844 entry file all-prefixes)
7845 (cond
7846 (link-location) ; specified by arg, just use it.
7847 ((org-in-regexp org-bracket-link-regexp 1)
7848 ;; We do have a link at point, and we are going to edit it.
7849 (setq remove (list (match-beginning 0) (match-end 0)))
7850 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7851 (setq link (read-string "Link: "
7852 (org-link-unescape
7853 (org-match-string-no-properties 1)))))
7854 ((or (org-in-regexp org-angle-link-re)
7855 (org-in-regexp org-plain-link-re))
7856 ;; Convert to bracket link
7857 (setq remove (list (match-beginning 0) (match-end 0))
7858 link (read-string "Link: "
7859 (org-remove-angle-brackets (match-string 0)))))
7860 ((member complete-file '((4) (16)))
7861 ;; Completing read for file names.
7862 (setq link (org-file-complete-link complete-file)))
7864 ;; Read link, with completion for stored links.
7865 (with-output-to-temp-buffer "*Org Links*"
7866 (princ "Insert a link.
7867 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7868 (when org-stored-links
7869 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7870 (princ (mapconcat
7871 (lambda (x)
7872 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7873 (reverse org-stored-links) "\n"))))
7874 (let ((cw (selected-window)))
7875 (select-window (get-buffer-window "*Org Links*"))
7876 (setq truncate-lines t)
7877 (unless (pos-visible-in-window-p (point-max))
7878 (org-fit-window-to-buffer))
7879 (and (window-live-p cw) (select-window cw)))
7880 ;; Fake a link history, containing the stored links.
7881 (setq tmphist (append (mapcar 'car org-stored-links)
7882 org-insert-link-history))
7883 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7884 (mapcar 'car org-link-abbrev-alist)
7885 org-link-types))
7886 (unwind-protect
7887 (progn
7888 (setq link
7889 (let ((org-completion-use-ido nil)
7890 (org-completion-use-iswitchb nil))
7891 (org-completing-read
7892 "Link: "
7893 (append
7894 (mapcar (lambda (x) (list (concat x ":")))
7895 all-prefixes)
7896 (mapcar 'car org-stored-links))
7897 nil nil nil
7898 'tmphist
7899 (car (car org-stored-links)))))
7900 (if (or (member link all-prefixes)
7901 (and (equal ":" (substring link -1))
7902 (member (substring link 0 -1) all-prefixes)
7903 (setq link (substring link 0 -1))))
7904 (setq link (org-link-try-special-completion link))))
7905 (set-window-configuration wcf)
7906 (kill-buffer "*Org Links*"))
7907 (setq entry (assoc link org-stored-links))
7908 (or entry (push link org-insert-link-history))
7909 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7910 (not org-keep-stored-link-after-insertion))
7911 (setq org-stored-links (delq (assoc link org-stored-links)
7912 org-stored-links)))
7913 (setq desc (or desc (nth 1 entry)))))
7915 (if (string-match org-plain-link-re link)
7916 ;; URL-like link, normalize the use of angular brackets.
7917 (setq link (org-make-link (org-remove-angle-brackets link))))
7919 ;; Check if we are linking to the current file with a search option
7920 ;; If yes, simplify the link by using only the search option.
7921 (when (and buffer-file-name
7922 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7923 (let* ((path (match-string 1 link))
7924 (case-fold-search nil)
7925 (search (match-string 2 link)))
7926 (save-match-data
7927 (if (equal (file-truename buffer-file-name) (file-truename path))
7928 ;; We are linking to this same file, with a search option
7929 (setq link search)))))
7931 ;; Check if we can/should use a relative path. If yes, simplify the link
7932 (when (string-match "^file:\\(.*\\)" link)
7933 (let* ((path (match-string 1 link))
7934 (origpath path)
7935 (case-fold-search nil))
7936 (cond
7937 ((or (eq org-link-file-path-type 'absolute)
7938 (equal complete-file '(16)))
7939 (setq path (abbreviate-file-name (expand-file-name path))))
7940 ((eq org-link-file-path-type 'noabbrev)
7941 (setq path (expand-file-name path)))
7942 ((eq org-link-file-path-type 'relative)
7943 (setq path (file-relative-name path)))
7945 (save-match-data
7946 (if (string-match (concat "^" (regexp-quote
7947 (file-name-as-directory
7948 (expand-file-name "."))))
7949 (expand-file-name path))
7950 ;; We are linking a file with relative path name.
7951 (setq path (substring (expand-file-name path)
7952 (match-end 0)))
7953 (setq path (abbreviate-file-name (expand-file-name path)))))))
7954 (setq link (concat "file:" path))
7955 (if (equal desc origpath)
7956 (setq desc path))))
7958 (if org-make-link-description-function
7959 (setq desc (funcall org-make-link-description-function link desc)))
7961 (setq desc (read-string "Description: " desc))
7962 (unless (string-match "\\S-" desc) (setq desc nil))
7963 (if remove (apply 'delete-region remove))
7964 (insert (org-make-link-string link desc))))
7966 (defun org-link-try-special-completion (type)
7967 "If there is completion support for link type TYPE, offer it."
7968 (let ((fun (intern (concat "org-" type "-complete-link"))))
7969 (if (functionp fun)
7970 (funcall fun)
7971 (read-string "Link (no completion support): " (concat type ":")))))
7973 (defun org-file-complete-link (&optional arg)
7974 "Create a file link using completion."
7975 (let (file link)
7976 (setq file (read-file-name "File: "))
7977 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7978 (pwd1 (file-name-as-directory (abbreviate-file-name
7979 (expand-file-name ".")))))
7980 (cond
7981 ((equal arg '(16))
7982 (setq link (org-make-link
7983 "file:"
7984 (abbreviate-file-name (expand-file-name file)))))
7985 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7986 (setq link (org-make-link "file:" (match-string 1 file))))
7987 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7988 (expand-file-name file))
7989 (setq link (org-make-link
7990 "file:" (match-string 1 (expand-file-name file)))))
7991 (t (setq link (org-make-link "file:" file)))))
7992 link))
7994 (defun org-completing-read (&rest args)
7995 "Completing-read with SPACE being a normal character."
7996 (let ((minibuffer-local-completion-map
7997 (copy-keymap minibuffer-local-completion-map)))
7998 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7999 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8000 (apply 'org-icompleting-read args)))
8002 (defun org-completing-read-no-i (&rest args)
8003 (let (org-completion-use-ido org-completion-use-iswitchb)
8004 (apply 'org-completing-read args)))
8006 (defun org-iswitchb-completing-read (prompt choices &rest args)
8007 "Use iswitch as a completing-read replacement to choose from choices.
8008 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8009 from."
8010 (let* ((iswitchb-use-virtual-buffers nil)
8011 (iswitchb-make-buflist-hook
8012 (lambda ()
8013 (setq iswitchb-temp-buflist choices))))
8014 (iswitchb-read-buffer prompt)))
8016 (defun org-icompleting-read (&rest args)
8017 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8018 (org-without-partial-completion
8019 (if (and org-completion-use-ido
8020 (fboundp 'ido-completing-read)
8021 (boundp 'ido-mode) ido-mode
8022 (listp (second args)))
8023 (let ((ido-enter-matching-directory nil))
8024 (apply 'ido-completing-read (concat (car args))
8025 (if (consp (car (nth 1 args)))
8026 (mapcar (lambda (x) (car x)) (nth 1 args))
8027 (nth 1 args))
8028 (cddr args)))
8029 (if (and org-completion-use-iswitchb
8030 (boundp 'iswitchb-mode) iswitchb-mode
8031 (listp (second args)))
8032 (apply 'org-iswitchb-completing-read (concat (car args))
8033 (if (consp (car (nth 1 args)))
8034 (mapcar (lambda (x) (car x)) (nth 1 args))
8035 (nth 1 args))
8036 (cddr args))
8037 (apply 'completing-read args)))))
8039 (defun org-extract-attributes (s)
8040 "Extract the attributes cookie from a string and set as text property."
8041 (let (a attr (start 0) key value)
8042 (save-match-data
8043 (when (string-match "{{\\([^}]+\\)}}$" s)
8044 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8045 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8046 (setq key (match-string 1 a) value (match-string 2 a)
8047 start (match-end 0)
8048 attr (plist-put attr (intern key) value))))
8049 (org-add-props s nil 'org-attr attr))
8052 (defun org-extract-attributes-from-string (tag)
8053 (let (key value attr)
8054 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8055 (setq key (match-string 1 tag) value (match-string 2 tag)
8056 tag (replace-match "" t t tag)
8057 attr (plist-put attr (intern key) value)))
8058 (cons tag attr)))
8060 (defun org-attributes-to-string (plist)
8061 "Format a property list into an HTML attribute list."
8062 (let ((s "") key value)
8063 (while plist
8064 (setq key (pop plist) value (pop plist))
8065 (and value
8066 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8069 ;;; Opening/following a link
8071 (defvar org-link-search-failed nil)
8073 (defun org-next-link ()
8074 "Move forward to the next link.
8075 If the link is in hidden text, expose it."
8076 (interactive)
8077 (when (and org-link-search-failed (eq this-command last-command))
8078 (goto-char (point-min))
8079 (message "Link search wrapped back to beginning of buffer"))
8080 (setq org-link-search-failed nil)
8081 (let* ((pos (point))
8082 (ct (org-context))
8083 (a (assoc :link ct)))
8084 (if a (goto-char (nth 2 a)))
8085 (if (re-search-forward org-any-link-re nil t)
8086 (progn
8087 (goto-char (match-beginning 0))
8088 (if (org-invisible-p) (org-show-context)))
8089 (goto-char pos)
8090 (setq org-link-search-failed t)
8091 (error "No further link found"))))
8093 (defun org-previous-link ()
8094 "Move backward to the previous link.
8095 If the link is in hidden text, expose it."
8096 (interactive)
8097 (when (and org-link-search-failed (eq this-command last-command))
8098 (goto-char (point-max))
8099 (message "Link search wrapped back to end of buffer"))
8100 (setq org-link-search-failed nil)
8101 (let* ((pos (point))
8102 (ct (org-context))
8103 (a (assoc :link ct)))
8104 (if a (goto-char (nth 1 a)))
8105 (if (re-search-backward org-any-link-re nil t)
8106 (progn
8107 (goto-char (match-beginning 0))
8108 (if (org-invisible-p) (org-show-context)))
8109 (goto-char pos)
8110 (setq org-link-search-failed t)
8111 (error "No further link found"))))
8113 (defun org-translate-link (s)
8114 "Translate a link string if a translation function has been defined."
8115 (if (and org-link-translation-function
8116 (fboundp org-link-translation-function)
8117 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8118 (progn
8119 (setq s (funcall org-link-translation-function
8120 (match-string 1) (match-string 2)))
8121 (concat (car s) ":" (cdr s)))
8124 (defun org-translate-link-from-planner (type path)
8125 "Translate a link from Emacs Planner syntax so that Org can follow it.
8126 This is still an experimental function, your mileage may vary."
8127 (cond
8128 ((member type '("http" "https" "news" "ftp"))
8129 ;; standard Internet links are the same.
8130 nil)
8131 ((and (equal type "irc") (string-match "^//" path))
8132 ;; Planner has two / at the beginning of an irc link, we have 1.
8133 ;; We should have zero, actually....
8134 (setq path (substring path 1)))
8135 ((and (equal type "lisp") (string-match "^/" path))
8136 ;; Planner has a slash, we do not.
8137 (setq type "elisp" path (substring path 1)))
8138 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8139 ;; A typical message link. Planner has the id after the final slash,
8140 ;; we separate it with a hash mark
8141 (setq path (concat (match-string 1 path) "#"
8142 (org-remove-angle-brackets (match-string 2 path)))))
8144 (cons type path))
8146 (defun org-find-file-at-mouse (ev)
8147 "Open file link or URL at mouse."
8148 (interactive "e")
8149 (mouse-set-point ev)
8150 (org-open-at-point 'in-emacs))
8152 (defun org-open-at-mouse (ev)
8153 "Open file link or URL at mouse."
8154 (interactive "e")
8155 (mouse-set-point ev)
8156 (if (eq major-mode 'org-agenda-mode)
8157 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8158 (org-open-at-point))
8160 (defvar org-window-config-before-follow-link nil
8161 "The window configuration before following a link.
8162 This is saved in case the need arises to restore it.")
8164 (defvar org-open-link-marker (make-marker)
8165 "Marker pointing to the location where `org-open-at-point; was called.")
8167 ;;;###autoload
8168 (defun org-open-at-point-global ()
8169 "Follow a link like Org-mode does.
8170 This command can be called in any mode to follow a link that has
8171 Org-mode syntax."
8172 (interactive)
8173 (org-run-like-in-org-mode 'org-open-at-point))
8175 ;;;###autoload
8176 (defun org-open-link-from-string (s &optional arg reference-buffer)
8177 "Open a link in the string S, as if it was in Org-mode."
8178 (interactive "sLink: \nP")
8179 (let ((reference-buffer (or reference-buffer (current-buffer))))
8180 (with-temp-buffer
8181 (let ((org-inhibit-startup t))
8182 (org-mode)
8183 (insert s)
8184 (goto-char (point-min))
8185 (org-open-at-point arg reference-buffer)))))
8187 (defun org-open-at-point (&optional in-emacs reference-buffer)
8188 "Open link at or after point.
8189 If there is no link at point, this function will search forward up to
8190 the end of the current line.
8191 Normally, files will be opened by an appropriate application. If the
8192 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8193 With a double prefix argument, try to open outside of Emacs, in the
8194 application the system uses for this file type."
8195 (interactive "P")
8196 (org-load-modules-maybe)
8197 (move-marker org-open-link-marker (point))
8198 (setq org-window-config-before-follow-link (current-window-configuration))
8199 (org-remove-occur-highlights nil nil t)
8200 (cond
8201 ((and (org-on-heading-p)
8202 (not (org-in-regexp
8203 (concat org-plain-link-re "\\|"
8204 org-bracket-link-regexp "\\|"
8205 org-angle-link-re "\\|"
8206 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8207 (or (org-offer-links-in-entry in-emacs)
8208 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8209 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8210 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8211 (org-footnote-action))
8213 (let (type path link line search (pos (point)))
8214 (catch 'match
8215 (save-excursion
8216 (skip-chars-forward "^]\n\r")
8217 (when (org-in-regexp org-bracket-link-regexp)
8218 (setq link (org-extract-attributes
8219 (org-link-unescape (org-match-string-no-properties 1))))
8220 (while (string-match " *\n *" link)
8221 (setq link (replace-match " " t t link)))
8222 (setq link (org-link-expand-abbrev link))
8223 (cond
8224 ((or (file-name-absolute-p link)
8225 (string-match "^\\.\\.?/" link))
8226 (setq type "file" path link))
8227 ((string-match org-link-re-with-space3 link)
8228 (setq type (match-string 1 link) path (match-string 2 link)))
8229 (t (setq type "thisfile" path link)))
8230 (throw 'match t)))
8232 (when (get-text-property (point) 'org-linked-text)
8233 (setq type "thisfile"
8234 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8235 (1+ (point)) (point))
8236 path (buffer-substring
8237 (previous-single-property-change pos 'org-linked-text)
8238 (next-single-property-change pos 'org-linked-text)))
8239 (throw 'match t))
8241 (save-excursion
8242 (when (or (org-in-regexp org-angle-link-re)
8243 (org-in-regexp org-plain-link-re))
8244 (setq type (match-string 1) path (match-string 2))
8245 (throw 'match t)))
8246 (save-excursion
8247 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8248 (setq type "tags"
8249 path (match-string 1))
8250 (while (string-match ":" path)
8251 (setq path (replace-match "+" t t path)))
8252 (throw 'match t)))
8253 (when (org-in-regexp "<\\([^><\n]+\\)>")
8254 (setq type "tree-match"
8255 path (match-string 1))
8256 (throw 'match t)))
8257 (unless path
8258 (error "No link found"))
8260 ;; switch back to reference buffer
8261 ;; needed when if called in a temporary buffer through
8262 ;; org-open-link-from-string
8263 (with-current-buffer (or reference-buffer (current-buffer))
8265 ;; Remove any trailing spaces in path
8266 (if (string-match " +\\'" path)
8267 (setq path (replace-match "" t t path)))
8268 (if (and org-link-translation-function
8269 (fboundp org-link-translation-function))
8270 ;; Check if we need to translate the link
8271 (let ((tmp (funcall org-link-translation-function type path)))
8272 (setq type (car tmp) path (cdr tmp))))
8274 (cond
8276 ((assoc type org-link-protocols)
8277 (funcall (nth 1 (assoc type org-link-protocols)) path))
8279 ((equal type "mailto")
8280 (let ((cmd (car org-link-mailto-program))
8281 (args (cdr org-link-mailto-program)) args1
8282 (address path) (subject "") a)
8283 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8284 (setq address (match-string 1 path)
8285 subject (org-link-escape (match-string 2 path))))
8286 (while args
8287 (cond
8288 ((not (stringp (car args))) (push (pop args) args1))
8289 (t (setq a (pop args))
8290 (if (string-match "%a" a)
8291 (setq a (replace-match address t t a)))
8292 (if (string-match "%s" a)
8293 (setq a (replace-match subject t t a)))
8294 (push a args1))))
8295 (apply cmd (nreverse args1))))
8297 ((member type '("http" "https" "ftp" "news"))
8298 (browse-url (concat type ":" (org-link-escape
8299 path org-link-escape-chars-browser))))
8301 ((member type '("message"))
8302 (browse-url (concat type ":" path)))
8304 ((string= type "tags")
8305 (org-tags-view in-emacs path))
8306 ((string= type "thisfile")
8307 (if in-emacs
8308 (switch-to-buffer-other-window
8309 (org-get-buffer-for-internal-link (current-buffer)))
8310 (org-mark-ring-push))
8311 (let ((cmd `(org-link-search
8312 ,path
8313 ,(cond ((equal in-emacs '(4)) 'occur)
8314 ((equal in-emacs '(16)) 'org-occur)
8315 (t nil))
8316 ,pos)))
8317 (condition-case nil (eval cmd)
8318 (error (progn (widen) (eval cmd))))))
8320 ((string= type "tree-match")
8321 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8323 ((string= type "file")
8324 (if (string-match "::\\([0-9]+\\)\\'" path)
8325 (setq line (string-to-number (match-string 1 path))
8326 path (substring path 0 (match-beginning 0)))
8327 (if (string-match "::\\(.+\\)\\'" path)
8328 (setq search (match-string 1 path)
8329 path (substring path 0 (match-beginning 0)))))
8330 (if (string-match "[*?{]" (file-name-nondirectory path))
8331 (dired path)
8332 (org-open-file path in-emacs line search)))
8334 ((string= type "news")
8335 (require 'org-gnus)
8336 (org-gnus-follow-link path))
8338 ((string= type "shell")
8339 (let ((cmd path))
8340 (if (or (not org-confirm-shell-link-function)
8341 (funcall org-confirm-shell-link-function
8342 (format "Execute \"%s\" in shell? "
8343 (org-add-props cmd nil
8344 'face 'org-warning))))
8345 (progn
8346 (message "Executing %s" cmd)
8347 (shell-command cmd))
8348 (error "Abort"))))
8350 ((string= type "elisp")
8351 (let ((cmd path))
8352 (if (or (not org-confirm-elisp-link-function)
8353 (funcall org-confirm-elisp-link-function
8354 (format "Execute \"%s\" as elisp? "
8355 (org-add-props cmd nil
8356 'face 'org-warning))))
8357 (message "%s => %s" cmd
8358 (if (equal (string-to-char cmd) ?\()
8359 (eval (read cmd))
8360 (call-interactively (read cmd))))
8361 (error "Abort"))))
8364 (browse-url-at-point)))))))
8365 (move-marker org-open-link-marker nil)
8366 (run-hook-with-args 'org-follow-link-hook))
8368 (defun org-offer-links-in-entry (&optional nth zero)
8369 "Offer links in the current entry and follow the selected link.
8370 If there is only one link, follow it immediately as well.
8371 If NTH is an integer, immediately pick the NTH link found.
8372 If ZERO is a string, check also this string for a link, and if
8373 there is one, offer it as link number zero."
8374 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8375 "\\(" org-angle-link-re "\\)\\|"
8376 "\\(" org-plain-link-re "\\)"))
8377 (cnt ?0)
8378 (in-emacs (if (integerp nth) nil nth))
8379 have-zero end links link c)
8380 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8381 (push (match-string 0 zero) links)
8382 (setq cnt (1- cnt) have-zero t))
8383 (save-excursion
8384 (org-back-to-heading t)
8385 (setq end (save-excursion (outline-next-heading) (point)))
8386 (while (re-search-forward re end t)
8387 (push (match-string 0) links))
8388 (setq links (org-uniquify (reverse links))))
8390 (cond
8391 ((null links)
8392 (message "No links"))
8393 ((equal (length links) 1)
8394 (setq link (car links)))
8395 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8396 (setq link (nth (if have-zero nth (1- nth)) links)))
8397 (t ; we have to select a link
8398 (save-excursion
8399 (save-window-excursion
8400 (delete-other-windows)
8401 (with-output-to-temp-buffer "*Select Link*"
8402 (mapc (lambda (l)
8403 (if (not (string-match org-bracket-link-regexp l))
8404 (princ (format "[%c] %s\n" (incf cnt)
8405 (org-remove-angle-brackets l)))
8406 (if (match-end 3)
8407 (princ (format "[%c] %s (%s)\n" (incf cnt)
8408 (match-string 3 l) (match-string 1 l)))
8409 (princ (format "[%c] %s\n" (incf cnt)
8410 (match-string 1 l))))))
8411 links))
8412 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8413 (message "Select link to open:")
8414 (setq c (read-char-exclusive))
8415 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8416 (when (equal c ?q) (error "Abort"))
8417 (setq nth (- c ?0))
8418 (if have-zero (setq nth (1+ nth)))
8419 (unless (and (integerp nth) (>= (length links) nth))
8420 (error "Invalid link selection"))
8421 (setq link (nth (1- nth) links))))
8422 (if link
8423 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8424 nil)))
8426 ;;;; Time estimates
8428 (defun org-get-effort (&optional pom)
8429 "Get the effort estimate for the current entry."
8430 (org-entry-get pom org-effort-property))
8432 ;;; File search
8434 (defvar org-create-file-search-functions nil
8435 "List of functions to construct the right search string for a file link.
8436 These functions are called in turn with point at the location to
8437 which the link should point.
8439 A function in the hook should first test if it would like to
8440 handle this file type, for example by checking the major-mode or
8441 the file extension. If it decides not to handle this file, it
8442 should just return nil to give other functions a chance. If it
8443 does handle the file, it must return the search string to be used
8444 when following the link. The search string will be part of the
8445 file link, given after a double colon, and `org-open-at-point'
8446 will automatically search for it. If special measures must be
8447 taken to make the search successful, another function should be
8448 added to the companion hook `org-execute-file-search-functions',
8449 which see.
8451 A function in this hook may also use `setq' to set the variable
8452 `description' to provide a suggestion for the descriptive text to
8453 be used for this link when it gets inserted into an Org-mode
8454 buffer with \\[org-insert-link].")
8456 (defvar org-execute-file-search-functions nil
8457 "List of functions to execute a file search triggered by a link.
8459 Functions added to this hook must accept a single argument, the
8460 search string that was part of the file link, the part after the
8461 double colon. The function must first check if it would like to
8462 handle this search, for example by checking the major-mode or the
8463 file extension. If it decides not to handle this search, it
8464 should just return nil to give other functions a chance. If it
8465 does handle the search, it must return a non-nil value to keep
8466 other functions from trying.
8468 Each function can access the current prefix argument through the
8469 variable `current-prefix-argument'. Note that a single prefix is
8470 used to force opening a link in Emacs, so it may be good to only
8471 use a numeric or double prefix to guide the search function.
8473 In case this is needed, a function in this hook can also restore
8474 the window configuration before `org-open-at-point' was called using:
8476 (set-window-configuration org-window-config-before-follow-link)")
8478 (defun org-link-search (s &optional type avoid-pos)
8479 "Search for a link search option.
8480 If S is surrounded by forward slashes, it is interpreted as a
8481 regular expression. In org-mode files, this will create an `org-occur'
8482 sparse tree. In ordinary files, `occur' will be used to list matches.
8483 If the current buffer is in `dired-mode', grep will be used to search
8484 in all files. If AVOID-POS is given, ignore matches near that position."
8485 (let ((case-fold-search t)
8486 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8487 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8488 (append '(("") (" ") ("\t") ("\n"))
8489 org-emphasis-alist)
8490 "\\|") "\\)"))
8491 (pos (point))
8492 (pre nil) (post nil)
8493 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8494 (cond
8495 ;; First check if there are any special
8496 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8497 ;; Now try the builtin stuff
8498 ((and (equal (string-to-char s0) ?#)
8499 (> (length s0) 1)
8500 (save-excursion
8501 (goto-char (point-min))
8502 (and
8503 (re-search-forward
8504 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8505 (setq type 'dedicated
8506 pos (match-beginning 0))))
8507 ;; There is an exact target for this
8508 (goto-char pos)
8509 (org-back-to-heading t)))
8510 ((save-excursion
8511 (goto-char (point-min))
8512 (and
8513 (re-search-forward
8514 (concat "<<" (regexp-quote s0) ">>") nil t)
8515 (setq type 'dedicated
8516 pos (match-beginning 0))))
8517 ;; There is an exact target for this
8518 (goto-char pos))
8519 ((and (string-match "^(\\(.*\\))$" s0)
8520 (save-excursion
8521 (goto-char (point-min))
8522 (and
8523 (re-search-forward
8524 (concat "[^[]" (regexp-quote
8525 (format org-coderef-label-format
8526 (match-string 1 s0))))
8527 nil t)
8528 (setq type 'dedicated
8529 pos (1+ (match-beginning 0))))))
8530 ;; There is a coderef target for this
8531 (goto-char pos))
8532 ((string-match "^/\\(.*\\)/$" s)
8533 ;; A regular expression
8534 (cond
8535 ((org-mode-p)
8536 (org-occur (match-string 1 s)))
8537 ;;((eq major-mode 'dired-mode)
8538 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8539 (t (org-do-occur (match-string 1 s)))))
8541 ;; A normal search strings
8542 (when (equal (string-to-char s) ?*)
8543 ;; Anchor on headlines, post may include tags.
8544 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8545 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8546 s (substring s 1)))
8547 (remove-text-properties
8548 0 (length s)
8549 '(face nil mouse-face nil keymap nil fontified nil) s)
8550 ;; Make a series of regular expressions to find a match
8551 (setq words (org-split-string s "[ \n\r\t]+")
8553 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8554 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8555 "\\)" markers)
8556 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8557 re2a (concat "[ \t\r\n]" re2a_)
8558 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8559 re4 (concat "[^a-zA-Z_]" re4_)
8561 re1 (concat pre re2 post)
8562 re3 (concat pre (if pre re4_ re4) post)
8563 re5 (concat pre ".*" re4)
8564 re2 (concat pre re2)
8565 re2a (concat pre (if pre re2a_ re2a))
8566 re4 (concat pre (if pre re4_ re4))
8567 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8568 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8569 re5 "\\)"
8571 (cond
8572 ((eq type 'org-occur) (org-occur reall))
8573 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8574 (t (goto-char (point-min))
8575 (setq type 'fuzzy)
8576 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8577 (org-search-not-self 1 re1 nil t)
8578 (org-search-not-self 1 re2 nil t)
8579 (org-search-not-self 1 re2a nil t)
8580 (org-search-not-self 1 re3 nil t)
8581 (org-search-not-self 1 re4 nil t)
8582 (org-search-not-self 1 re5 nil t)
8584 (goto-char (match-beginning 1))
8585 (goto-char pos)
8586 (error "No match")))))
8588 ;; Normal string-search
8589 (goto-char (point-min))
8590 (if (search-forward s nil t)
8591 (goto-char (match-beginning 0))
8592 (error "No match"))))
8593 (and (org-mode-p) (org-show-context 'link-search))
8594 type))
8596 (defun org-search-not-self (group &rest args)
8597 "Execute `re-search-forward', but only accept matches that do not
8598 enclose the position of `org-open-link-marker'."
8599 (let ((m org-open-link-marker))
8600 (catch 'exit
8601 (while (apply 're-search-forward args)
8602 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8603 (goto-char (match-end group))
8604 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8605 (> (match-beginning 0) (marker-position m))
8606 (< (match-end 0) (marker-position m)))
8607 (save-match-data
8608 (or (not (org-in-regexp
8609 org-bracket-link-analytic-regexp 1))
8610 (not (match-end 4)) ; no description
8611 (and (<= (match-beginning 4) (point))
8612 (>= (match-end 4) (point))))))
8613 (throw 'exit (point))))))))
8615 (defun org-get-buffer-for-internal-link (buffer)
8616 "Return a buffer to be used for displaying the link target of internal links."
8617 (cond
8618 ((not org-display-internal-link-with-indirect-buffer)
8619 buffer)
8620 ((string-match "(Clone)$" (buffer-name buffer))
8621 (message "Buffer is already a clone, not making another one")
8622 ;; we also do not modify visibility in this case
8623 buffer)
8624 (t ; make a new indirect buffer for displaying the link
8625 (let* ((bn (buffer-name buffer))
8626 (ibn (concat bn "(Clone)"))
8627 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8628 (with-current-buffer ib (org-overview))
8629 ib))))
8631 (defun org-do-occur (regexp &optional cleanup)
8632 "Call the Emacs command `occur'.
8633 If CLEANUP is non-nil, remove the printout of the regular expression
8634 in the *Occur* buffer. This is useful if the regex is long and not useful
8635 to read."
8636 (occur regexp)
8637 (when cleanup
8638 (let ((cwin (selected-window)) win beg end)
8639 (when (setq win (get-buffer-window "*Occur*"))
8640 (select-window win))
8641 (goto-char (point-min))
8642 (when (re-search-forward "match[a-z]+" nil t)
8643 (setq beg (match-end 0))
8644 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8645 (setq end (1- (match-beginning 0)))))
8646 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8647 (goto-char (point-min))
8648 (select-window cwin))))
8650 ;;; The mark ring for links jumps
8652 (defvar org-mark-ring nil
8653 "Mark ring for positions before jumps in Org-mode.")
8654 (defvar org-mark-ring-last-goto nil
8655 "Last position in the mark ring used to go back.")
8656 ;; Fill and close the ring
8657 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8658 (loop for i from 1 to org-mark-ring-length do
8659 (push (make-marker) org-mark-ring))
8660 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8661 org-mark-ring)
8663 (defun org-mark-ring-push (&optional pos buffer)
8664 "Put the current position or POS into the mark ring and rotate it."
8665 (interactive)
8666 (setq pos (or pos (point)))
8667 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8668 (move-marker (car org-mark-ring)
8669 (or pos (point))
8670 (or buffer (current-buffer)))
8671 (message "%s"
8672 (substitute-command-keys
8673 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8675 (defun org-mark-ring-goto (&optional n)
8676 "Jump to the previous position in the mark ring.
8677 With prefix arg N, jump back that many stored positions. When
8678 called several times in succession, walk through the entire ring.
8679 Org-mode commands jumping to a different position in the current file,
8680 or to another Org-mode file, automatically push the old position
8681 onto the ring."
8682 (interactive "p")
8683 (let (p m)
8684 (if (eq last-command this-command)
8685 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8686 (setq p org-mark-ring))
8687 (setq org-mark-ring-last-goto p)
8688 (setq m (car p))
8689 (switch-to-buffer (marker-buffer m))
8690 (goto-char m)
8691 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8693 (defun org-remove-angle-brackets (s)
8694 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8695 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8697 (defun org-add-angle-brackets (s)
8698 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8699 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8701 (defun org-remove-double-quotes (s)
8702 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8703 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8706 ;;; Following specific links
8708 (defun org-follow-timestamp-link ()
8709 (cond
8710 ((org-at-date-range-p t)
8711 (let ((org-agenda-start-on-weekday)
8712 (t1 (match-string 1))
8713 (t2 (match-string 2)))
8714 (setq t1 (time-to-days (org-time-string-to-time t1))
8715 t2 (time-to-days (org-time-string-to-time t2)))
8716 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8717 ((org-at-timestamp-p t)
8718 (org-agenda-list nil (time-to-days (org-time-string-to-time
8719 (substring (match-string 1) 0 10)))
8721 (t (error "This should not happen"))))
8724 ;;; Following file links
8725 (defvar org-wait nil)
8726 (defun org-open-file (path &optional in-emacs line search)
8727 "Open the file at PATH.
8728 First, this expands any special file name abbreviations. Then the
8729 configuration variable `org-file-apps' is checked if it contains an
8730 entry for this file type, and if yes, the corresponding command is launched.
8732 If no application is found, Emacs simply visits the file.
8734 With optional prefix argument IN-EMACS, Emacs will visit the file.
8735 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8736 and o use an external application to visit the file.
8738 Optional LINE specifies a line to go to, optional SEARCH a string to
8739 search for. If LINE or SEARCH is given, the file will always be
8740 opened in Emacs.
8741 If the file does not exist, an error is thrown."
8742 (setq in-emacs (or in-emacs line search))
8743 (let* ((file (if (equal path "")
8744 buffer-file-name
8745 (substitute-in-file-name (expand-file-name path))))
8746 (apps (append org-file-apps (org-default-apps)))
8747 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8748 (dirp (if remp nil (file-directory-p file)))
8749 (file (if (and dirp org-open-directory-means-index-dot-org)
8750 (concat (file-name-as-directory file) "index.org")
8751 file))
8752 (a-m-a-p (assq 'auto-mode apps))
8753 (dfile (downcase file))
8754 (old-buffer (current-buffer))
8755 (old-pos (point))
8756 (old-mode major-mode)
8757 ext cmd)
8758 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8759 (setq ext (match-string 1 dfile))
8760 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8761 (setq ext (match-string 1 dfile))))
8762 (cond
8763 ((equal in-emacs '(16))
8764 (setq cmd (cdr (assoc 'system apps))))
8765 (in-emacs (setq cmd 'emacs))
8767 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8768 (and dirp (cdr (assoc 'directory apps)))
8769 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8770 'string-match)
8771 (cdr (assoc ext apps))
8772 (cdr (assoc t apps))))))
8773 (when (eq cmd 'system)
8774 (setq cmd (cdr (assoc 'system apps))))
8775 (when (eq cmd 'default)
8776 (setq cmd (cdr (assoc t apps))))
8777 (when (eq cmd 'mailcap)
8778 (require 'mailcap)
8779 (mailcap-parse-mailcaps)
8780 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8781 (command (mailcap-mime-info mime-type)))
8782 (if (stringp command)
8783 (setq cmd command)
8784 (setq cmd 'emacs))))
8785 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8786 (not (file-exists-p file))
8787 (not org-open-non-existing-files))
8788 (error "No such file: %s" file))
8789 (cond
8790 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8791 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8792 (while (string-match "['\"]%s['\"]" cmd)
8793 (setq cmd (replace-match "%s" t t cmd)))
8794 (while (string-match "%s" cmd)
8795 (setq cmd (replace-match
8796 (save-match-data
8797 (shell-quote-argument
8798 (convert-standard-filename file)))
8799 t t cmd)))
8800 (save-window-excursion
8801 (start-process-shell-command cmd nil cmd)
8802 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8804 ((or (stringp cmd)
8805 (eq cmd 'emacs))
8806 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8807 (widen)
8808 (if line (org-goto-line line)
8809 (if search (org-link-search search))))
8810 ((consp cmd)
8811 (let ((file (convert-standard-filename file)))
8812 (eval cmd)))
8813 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8814 (and (org-mode-p) (eq old-mode 'org-mode)
8815 (or (not (equal old-buffer (current-buffer)))
8816 (not (equal old-pos (point))))
8817 (org-mark-ring-push old-pos old-buffer))))
8819 (defun org-default-apps ()
8820 "Return the default applications for this operating system."
8821 (cond
8822 ((eq system-type 'darwin)
8823 org-file-apps-defaults-macosx)
8824 ((eq system-type 'windows-nt)
8825 org-file-apps-defaults-windowsnt)
8826 (t org-file-apps-defaults-gnu)))
8828 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8829 "Convert extensions to regular expressions in the cars of LIST.
8830 Also, weed out any non-string entries, because the return value is used
8831 only for regexp matching.
8832 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8833 point to the symbol `emacs', indicating that the file should
8834 be opened in Emacs."
8835 (append
8836 (delq nil
8837 (mapcar (lambda (x)
8838 (if (not (stringp (car x)))
8840 (if (string-match "\\W" (car x))
8842 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8843 list))
8844 (if add-auto-mode
8845 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8847 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8848 (defun org-file-remote-p (file)
8849 "Test whether FILE specifies a location on a remote system.
8850 Return non-nil if the location is indeed remote.
8852 For example, the filename \"/user@host:/foo\" specifies a location
8853 on the system \"/user@host:\"."
8854 (cond ((fboundp 'file-remote-p)
8855 (file-remote-p file))
8856 ((fboundp 'tramp-handle-file-remote-p)
8857 (tramp-handle-file-remote-p file))
8858 ((and (boundp 'ange-ftp-name-format)
8859 (string-match (car ange-ftp-name-format) file))
8861 (t nil)))
8864 ;;;; Refiling
8866 (defun org-get-org-file ()
8867 "Read a filename, with default directory `org-directory'."
8868 (let ((default (or org-default-notes-file remember-data-file)))
8869 (read-file-name (format "File name [%s]: " default)
8870 (file-name-as-directory org-directory)
8871 default)))
8873 (defun org-notes-order-reversed-p ()
8874 "Check if the current file should receive notes in reversed order."
8875 (cond
8876 ((not org-reverse-note-order) nil)
8877 ((eq t org-reverse-note-order) t)
8878 ((not (listp org-reverse-note-order)) nil)
8879 (t (catch 'exit
8880 (let ((all org-reverse-note-order)
8881 entry)
8882 (while (setq entry (pop all))
8883 (if (string-match (car entry) buffer-file-name)
8884 (throw 'exit (cdr entry))))
8885 nil)))))
8887 (defvar org-refile-target-table nil
8888 "The list of refile targets, created by `org-refile'.")
8890 (defvar org-agenda-new-buffers nil
8891 "Buffers created to visit agenda files.")
8893 (defun org-get-refile-targets (&optional default-buffer)
8894 "Produce a table with refile targets."
8895 (let ((case-fold-search nil)
8896 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8897 (entries (or org-refile-targets '((nil . (:level . 1)))))
8898 targets txt re files f desc descre fast-path-p level pos0)
8899 (message "Getting targets...")
8900 (with-current-buffer (or default-buffer (current-buffer))
8901 (while (setq entry (pop entries))
8902 (setq files (car entry) desc (cdr entry))
8903 (setq fast-path-p nil)
8904 (cond
8905 ((null files) (setq files (list (current-buffer))))
8906 ((eq files 'org-agenda-files)
8907 (setq files (org-agenda-files 'unrestricted)))
8908 ((and (symbolp files) (fboundp files))
8909 (setq files (funcall files)))
8910 ((and (symbolp files) (boundp files))
8911 (setq files (symbol-value files))))
8912 (if (stringp files) (setq files (list files)))
8913 (cond
8914 ((eq (car desc) :tag)
8915 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8916 ((eq (car desc) :todo)
8917 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8918 ((eq (car desc) :regexp)
8919 (setq descre (cdr desc)))
8920 ((eq (car desc) :level)
8921 (setq descre (concat "^\\*\\{" (number-to-string
8922 (if org-odd-levels-only
8923 (1- (* 2 (cdr desc)))
8924 (cdr desc)))
8925 "\\}[ \t]")))
8926 ((eq (car desc) :maxlevel)
8927 (setq fast-path-p t)
8928 (setq descre (concat "^\\*\\{1," (number-to-string
8929 (if org-odd-levels-only
8930 (1- (* 2 (cdr desc)))
8931 (cdr desc)))
8932 "\\}[ \t]")))
8933 (t (error "Bad refiling target description %s" desc)))
8934 (while (setq f (pop files))
8935 (with-current-buffer
8936 (if (bufferp f) f (org-get-agenda-file-buffer f))
8937 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8938 (setq f (expand-file-name f))
8939 (if (eq org-refile-use-outline-path 'file)
8940 (push (list (file-name-nondirectory f) f nil nil) targets))
8941 (save-excursion
8942 (save-restriction
8943 (widen)
8944 (goto-char (point-min))
8945 (while (re-search-forward descre nil t)
8946 (goto-char (setq pos0 (point-at-bol)))
8947 (catch 'next
8948 (when org-refile-target-verify-function
8949 (save-match-data
8950 (or (funcall org-refile-target-verify-function)
8951 (throw 'next t))))
8952 (when (looking-at org-complex-heading-regexp)
8953 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8954 txt (org-link-display-format (match-string 4))
8955 re (concat "^" (regexp-quote
8956 (buffer-substring (match-beginning 1)
8957 (match-end 4)))))
8958 (if (match-end 5) (setq re (concat re "[ \t]+"
8959 (regexp-quote
8960 (match-string 5)))))
8961 (setq re (concat re "[ \t]*$"))
8962 (when org-refile-use-outline-path
8963 (setq txt (mapconcat 'org-protect-slash
8964 (append
8965 (if (eq org-refile-use-outline-path 'file)
8966 (list (file-name-nondirectory
8967 (buffer-file-name (buffer-base-buffer))))
8968 (if (eq org-refile-use-outline-path 'full-file-path)
8969 (list (buffer-file-name (buffer-base-buffer)))))
8970 (org-get-outline-path fast-path-p level txt)
8971 (list txt))
8972 "/")))
8973 (push (list txt f re (point)) targets)))
8974 (when (= (point) pos0)
8975 ;; verification function has not moved point
8976 (goto-char (point-at-eol))))))))))
8977 (message "Getting targets...done")
8978 (nreverse targets)))
8980 (defun org-protect-slash (s)
8981 (while (string-match "/" s)
8982 (setq s (replace-match "\\" t t s)))
8985 (defvar org-olpa (make-vector 20 nil))
8987 (defun org-get-outline-path (&optional fastp level heading)
8988 "Return the outline path to the current entry, as a list.
8989 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
8990 routine which makes outline path derivations for an entire file,
8991 avoiding backtracing."
8992 (if fastp
8993 (progn
8994 (if (> level 19)
8995 (error "Outline path failure, more than 19 levels."))
8996 (loop for i from level upto 19 do
8997 (aset org-olpa i nil))
8998 (prog1
8999 (delq nil (append org-olpa nil))
9000 (aset org-olpa level heading)))
9001 (let (rtn)
9002 (save-excursion
9003 (while (org-up-heading-safe)
9004 (when (looking-at org-complex-heading-regexp)
9005 (push (org-match-string-no-properties 4) rtn)))
9006 rtn))))
9008 (defun org-format-outline-path (path &optional width prefix)
9009 "Format the outlie path PATH for display.
9010 Width is the maximum number of characters that is available.
9011 Prefix is a prefix to be included in the returned string,
9012 such as the file name."
9013 (setq width (or width 79))
9014 (if prefix (setq width (- width (length prefix))))
9015 (if (not path)
9016 (or prefix "")
9017 (let* ((nsteps (length path))
9018 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9019 (maxwidth (if (<= total-width width)
9020 10000 ;; everything fits
9021 ;; we need to shorten the level headings
9022 (/ (- width nsteps) nsteps)))
9023 (org-odd-levels-only nil)
9024 (n 0)
9025 (total (1+ (length prefix))))
9026 (setq maxwidth (max maxwidth 10))
9027 (concat prefix
9028 (mapconcat
9029 (lambda (h)
9030 (setq n (1+ n))
9031 (if (and (= n nsteps) (< maxwidth 10000))
9032 (setq maxwidth (- total-width total)))
9033 (if (< (length h) maxwidth)
9034 (progn (setq total (+ total (length h) 1)) h)
9035 (setq h (substring h 0 (- maxwidth 2))
9036 total (+ total maxwidth 1))
9037 (if (string-match "[ \t]+\\'" h)
9038 (setq h (substring h 0 (match-beginning 0))))
9039 (setq h (concat h "..")))
9040 (org-add-props h nil 'face
9041 (nth (% (1- n) org-n-level-faces)
9042 org-level-faces))
9044 path "/")))))
9046 (defun org-display-outline-path (&optional file current)
9047 "Display the current outline path in the echo area."
9048 (interactive "P")
9049 (let ((bfn (buffer-file-name (buffer-base-buffer)))
9050 (path (and (org-mode-p) (org-get-outline-path))))
9051 (if current (setq path (append path
9052 (save-excursion
9053 (org-back-to-heading t)
9054 (if (looking-at org-complex-heading-regexp)
9055 (list (match-string 4)))))))
9056 (message (org-format-outline-path
9057 path
9058 (1- (frame-width))
9059 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9061 (defvar org-refile-history nil
9062 "History for refiling operations.")
9064 (defvar org-after-refile-insert-hook nil
9065 "Hook run after `org-refile' has inserted its stuff at the new location.
9066 Note that this is still *before* the stuff will be removed from
9067 the *old* location.")
9069 (defun org-refile (&optional goto default-buffer rfloc)
9070 "Move the entry at point to another heading.
9071 The list of target headings is compiled using the information in
9072 `org-refile-targets', which see. This list is created before each use
9073 and will therefore always be up-to-date.
9075 At the target location, the entry is filed as a subitem of the target heading.
9076 Depending on `org-reverse-note-order', the new subitem will either be the
9077 first or the last subitem.
9079 If there is an active region, all entries in that region will be moved.
9080 However, the region must fulfil the requirement that the first heading
9081 is the first one sets the top-level of the moved text - at most siblings
9082 below it are allowed.
9084 With prefix arg GOTO, the command will only visit the target location,
9085 not actually move anything.
9086 With a double prefix `C-u C-u', go to the location where the last refiling
9087 operation has put the subtree.
9088 With a prefix argument of `2', refile to the running clock.
9090 RFLOC can be a refile location obtained in a different way.
9092 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9093 (interactive "P")
9094 (let* ((cbuf (current-buffer))
9095 (regionp (org-region-active-p))
9096 (region-start (and regionp (region-beginning)))
9097 (region-end (and regionp (region-end)))
9098 (region-length (and regionp (- region-end region-start)))
9099 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9100 pos it nbuf file re level reversed)
9101 (setq last-command nil)
9102 (when regionp
9103 (goto-char region-start)
9104 (or (bolp) (goto-char (point-at-bol)))
9105 (setq region-start (point))
9106 (unless (org-kill-is-subtree-p
9107 (buffer-substring region-start region-end))
9108 (error "The region is not a (sequence of) subtree(s)")))
9109 (if (equal goto '(16))
9110 (org-refile-goto-last-stored)
9111 (when (or
9112 (and (equal goto 2)
9113 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9114 (prog1
9115 (setq it (list (or org-clock-heading "running clock")
9116 (buffer-file-name
9117 (marker-buffer org-clock-hd-marker))
9119 (marker-position org-clock-hd-marker)))
9120 (setq goto nil)))
9121 (setq it (or rfloc
9122 (save-excursion
9123 (org-refile-get-location
9124 (if goto "Goto: " "Refile to: ") default-buffer
9125 org-refile-allow-creating-parent-nodes)))))
9126 (setq file (nth 1 it)
9127 re (nth 2 it)
9128 pos (nth 3 it))
9129 (if (and (not goto)
9131 (equal (buffer-file-name) file)
9132 (if regionp
9133 (and (>= pos region-start)
9134 (<= pos region-end))
9135 (and (>= pos (point))
9136 (< pos (save-excursion
9137 (org-end-of-subtree t t))))))
9138 (error "Cannot refile to position inside the tree or region"))
9140 (setq nbuf (or (find-buffer-visiting file)
9141 (find-file-noselect file)))
9142 (if goto
9143 (progn
9144 (switch-to-buffer nbuf)
9145 (goto-char pos)
9146 (org-show-context 'org-goto))
9147 (if regionp
9148 (progn
9149 (org-kill-new (buffer-substring region-start region-end))
9150 (org-save-markers-in-region region-start region-end))
9151 (org-copy-subtree 1 nil t))
9152 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9153 (find-file-noselect file)))
9154 (setq reversed (org-notes-order-reversed-p))
9155 (save-excursion
9156 (save-restriction
9157 (widen)
9158 (if pos
9159 (progn
9160 (goto-char pos)
9161 (looking-at outline-regexp)
9162 (setq level (org-get-valid-level (funcall outline-level) 1))
9163 (goto-char
9164 (if reversed
9165 (or (outline-next-heading) (point-max))
9166 (or (save-excursion (org-get-next-sibling))
9167 (org-end-of-subtree t t)
9168 (point-max)))))
9169 (setq level 1)
9170 (if (not reversed)
9171 (goto-char (point-max))
9172 (goto-char (point-min))
9173 (or (outline-next-heading) (goto-char (point-max)))))
9174 (if (not (bolp)) (newline))
9175 (bookmark-set "org-refile-last-stored")
9176 (org-paste-subtree level)
9177 (if (fboundp 'deactivate-mark) (deactivate-mark))
9178 (run-hooks 'org-after-refile-insert-hook))))
9179 (if regionp
9180 (delete-region (point) (+ (point) region-length))
9181 (org-cut-subtree))
9182 (when (featurep 'org-inlinetask)
9183 (org-inlinetask-remove-END-maybe))
9184 (setq org-markers-to-move nil)
9185 (message "Refiled to \"%s\"" (car it))))))
9186 (org-reveal))
9188 (defun org-refile-goto-last-stored ()
9189 "Go to the location where the last refile was stored."
9190 (interactive)
9191 (bookmark-jump "org-refile-last-stored")
9192 (message "This is the location of the last refile"))
9194 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9195 "Prompt the user for a refile location, using PROMPT."
9196 (let ((org-refile-targets org-refile-targets)
9197 (org-refile-use-outline-path org-refile-use-outline-path))
9198 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9199 (unless org-refile-target-table
9200 (error "No refile targets"))
9201 (let* ((cbuf (current-buffer))
9202 (partial-completion-mode nil)
9203 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9204 (cfunc (if (and org-refile-use-outline-path
9205 org-outline-path-complete-in-steps)
9206 'org-olpath-completing-read
9207 'org-icompleting-read))
9208 (extra (if org-refile-use-outline-path "/" ""))
9209 (filename (and cfn (expand-file-name cfn)))
9210 (tbl (mapcar
9211 (lambda (x)
9212 (if (and (not (member org-refile-use-outline-path
9213 '(file full-file-path)))
9214 (not (equal filename (nth 1 x))))
9215 (cons (concat (car x) extra " ("
9216 (file-name-nondirectory (nth 1 x)) ")")
9217 (cdr x))
9218 (cons (concat (car x) extra) (cdr x))))
9219 org-refile-target-table))
9220 (completion-ignore-case t)
9221 pa answ parent-target child parent old-hist)
9222 (setq old-hist org-refile-history)
9223 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9224 nil 'org-refile-history))
9225 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9226 (if pa
9227 (progn
9228 (when (or (not org-refile-history)
9229 (not (eq old-hist org-refile-history))
9230 (not (equal (car pa) (car org-refile-history))))
9231 (setq org-refile-history
9232 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9233 org-refile-history
9234 (cdr org-refile-history))))
9235 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9236 (pop org-refile-history)))
9238 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9239 (setq parent (match-string 1 answ)
9240 child (match-string 2 answ))
9241 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9242 (when (and parent-target
9243 (or (eq new-nodes t)
9244 (and (eq new-nodes 'confirm)
9245 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9246 (org-refile-new-child parent-target child))))))
9248 (defun org-refile-new-child (parent-target child)
9249 "Use refile target PARENT-TARGET to add new CHILD below it."
9250 (unless parent-target
9251 (error "Cannot find parent for new node"))
9252 (let ((file (nth 1 parent-target))
9253 (pos (nth 3 parent-target))
9254 level)
9255 (with-current-buffer (or (find-buffer-visiting file)
9256 (find-file-noselect file))
9257 (save-excursion
9258 (save-restriction
9259 (widen)
9260 (if pos
9261 (goto-char pos)
9262 (goto-char (point-max))
9263 (if (not (bolp)) (newline)))
9264 (when (looking-at outline-regexp)
9265 (setq level (funcall outline-level))
9266 (org-end-of-subtree t t))
9267 (org-back-over-empty-lines)
9268 (insert "\n" (make-string
9269 (if pos (org-get-valid-level level 1) 1) ?*)
9270 " " child "\n")
9271 (beginning-of-line 0)
9272 (list (concat (car parent-target) "/" child) file "" (point)))))))
9274 (defun org-olpath-completing-read (prompt collection &rest args)
9275 "Read an outline path like a file name."
9276 (let ((thetable collection)
9277 (org-completion-use-ido nil) ; does not work with ido.
9278 (org-completion-use-iswitchb nil)) ; or iswitchb
9279 (apply
9280 'org-icompleting-read prompt
9281 (lambda (string predicate &optional flag)
9282 (let (rtn r f (l (length string)))
9283 (cond
9284 ((eq flag nil)
9285 ;; try completion
9286 (try-completion string thetable))
9287 ((eq flag t)
9288 ;; all-completions
9289 (setq rtn (all-completions string thetable predicate))
9290 (mapcar
9291 (lambda (x)
9292 (setq r (substring x l))
9293 (if (string-match " ([^)]*)$" x)
9294 (setq f (match-string 0 x))
9295 (setq f ""))
9296 (if (string-match "/" r)
9297 (concat string (substring r 0 (match-end 0)) f)
9299 rtn))
9300 ((eq flag 'lambda)
9301 ;; exact match?
9302 (assoc string thetable)))
9304 args)))
9306 ;;;; Dynamic blocks
9308 (defun org-find-dblock (name)
9309 "Find the first dynamic block with name NAME in the buffer.
9310 If not found, stay at current position and return nil."
9311 (let (pos)
9312 (save-excursion
9313 (goto-char (point-min))
9314 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9315 nil t)
9316 (match-beginning 0))))
9317 (if pos (goto-char pos))
9318 pos))
9320 (defconst org-dblock-start-re
9321 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9322 "Matches the start line of a dynamic block, with parameters.")
9324 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9325 "Matches the end of a dynamic block.")
9327 (defun org-create-dblock (plist)
9328 "Create a dynamic block section, with parameters taken from PLIST.
9329 PLIST must contain a :name entry which is used as name of the block."
9330 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9331 (end-of-line 1)
9332 (newline))
9333 (let ((col (current-column))
9334 (name (plist-get plist :name)))
9335 (insert "#+BEGIN: " name)
9336 (while plist
9337 (if (eq (car plist) :name)
9338 (setq plist (cddr plist))
9339 (insert " " (prin1-to-string (pop plist)))))
9340 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9341 (beginning-of-line -2)))
9343 (defun org-prepare-dblock ()
9344 "Prepare dynamic block for refresh.
9345 This empties the block, puts the cursor at the insert position and returns
9346 the property list including an extra property :name with the block name."
9347 (unless (looking-at org-dblock-start-re)
9348 (error "Not at a dynamic block"))
9349 (let* ((begdel (1+ (match-end 0)))
9350 (name (org-no-properties (match-string 1)))
9351 (params (append (list :name name)
9352 (read (concat "(" (match-string 3) ")")))))
9353 (save-excursion
9354 (beginning-of-line 1)
9355 (skip-chars-forward " \t")
9356 (setq params (plist-put params :indentation-column (current-column))))
9357 (unless (re-search-forward org-dblock-end-re nil t)
9358 (error "Dynamic block not terminated"))
9359 (setq params
9360 (append params
9361 (list :content (buffer-substring
9362 begdel (match-beginning 0)))))
9363 (delete-region begdel (match-beginning 0))
9364 (goto-char begdel)
9365 (open-line 1)
9366 params))
9368 (defun org-map-dblocks (&optional command)
9369 "Apply COMMAND to all dynamic blocks in the current buffer.
9370 If COMMAND is not given, use `org-update-dblock'."
9371 (let ((cmd (or command 'org-update-dblock))
9372 pos)
9373 (save-excursion
9374 (goto-char (point-min))
9375 (while (re-search-forward org-dblock-start-re nil t)
9376 (goto-char (setq pos (match-beginning 0)))
9377 (condition-case nil
9378 (funcall cmd)
9379 (error (message "Error during update of dynamic block")))
9380 (goto-char pos)
9381 (unless (re-search-forward org-dblock-end-re nil t)
9382 (error "Dynamic block not terminated"))))))
9384 (defun org-dblock-update (&optional arg)
9385 "User command for updating dynamic blocks.
9386 Update the dynamic block at point. With prefix ARG, update all dynamic
9387 blocks in the buffer."
9388 (interactive "P")
9389 (if arg
9390 (org-update-all-dblocks)
9391 (or (looking-at org-dblock-start-re)
9392 (org-beginning-of-dblock))
9393 (org-update-dblock)))
9395 (defun org-update-dblock ()
9396 "Update the dynamic block at point
9397 This means to empty the block, parse for parameters and then call
9398 the correct writing function."
9399 (save-window-excursion
9400 (let* ((pos (point))
9401 (line (org-current-line))
9402 (params (org-prepare-dblock))
9403 (name (plist-get params :name))
9404 (indent (plist-get params :indentation-column))
9405 (cmd (intern (concat "org-dblock-write:" name))))
9406 (message "Updating dynamic block `%s' at line %d..." name line)
9407 (funcall cmd params)
9408 (message "Updating dynamic block `%s' at line %d...done" name line)
9409 (goto-char pos)
9410 (when (and indent (> indent 0))
9411 (setq indent (make-string indent ?\ ))
9412 (save-excursion
9413 (org-beginning-of-dblock)
9414 (forward-line 1)
9415 (while (not (looking-at org-dblock-end-re))
9416 (insert indent)
9417 (beginning-of-line 2))
9418 (when (looking-at org-dblock-end-re)
9419 (and (looking-at "[ \t]+")
9420 (replace-match ""))
9421 (insert indent)))))))
9423 (defun org-beginning-of-dblock ()
9424 "Find the beginning of the dynamic block at point.
9425 Error if there is no such block at point."
9426 (let ((pos (point))
9427 beg)
9428 (end-of-line 1)
9429 (if (and (re-search-backward org-dblock-start-re nil t)
9430 (setq beg (match-beginning 0))
9431 (re-search-forward org-dblock-end-re nil t)
9432 (> (match-end 0) pos))
9433 (goto-char beg)
9434 (goto-char pos)
9435 (error "Not in a dynamic block"))))
9437 (defun org-update-all-dblocks ()
9438 "Update all dynamic blocks in the buffer.
9439 This function can be used in a hook."
9440 (when (org-mode-p)
9441 (org-map-dblocks 'org-update-dblock)))
9444 ;;;; Completion
9446 (defconst org-additional-option-like-keywords
9447 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9448 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9449 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "LATEX_CLASS:" "ATTR_LaTeX"
9450 "BEGIN:" "END:"
9451 "ORGTBL" "TBLFM:" "TBLNAME:"
9452 "BEGIN_EXAMPLE" "END_EXAMPLE"
9453 "BEGIN_QUOTE" "END_QUOTE"
9454 "BEGIN_VERSE" "END_VERSE"
9455 "BEGIN_CENTER" "END_CENTER"
9456 "BEGIN_SRC" "END_SRC"
9457 "CATEGORY" "COLUMNS"
9458 "CAPTION" "LABEL"
9459 "SETUPFILE"
9460 "BIND"
9461 "MACRO"))
9463 (defcustom org-structure-template-alist
9465 ("s" "#+begin_src ?\n\n#+end_src"
9466 "<src lang=\"?\">\n\n</src>")
9467 ("e" "#+begin_example\n?\n#+end_example"
9468 "<example>\n?\n</example>")
9469 ("q" "#+begin_quote\n?\n#+end_quote"
9470 "<quote>\n?\n</quote>")
9471 ("v" "#+begin_verse\n?\n#+end_verse"
9472 "<verse>\n?\n/verse>")
9473 ("c" "#+begin_center\n?\n#+end_center"
9474 "<center>\n?\n/center>")
9475 ("l" "#+begin_latex\n?\n#+end_latex"
9476 "<literal style=\"latex\">\n?\n</literal>")
9477 ("L" "#+latex: "
9478 "<literal style=\"latex\">?</literal>")
9479 ("h" "#+begin_html\n?\n#+end_html"
9480 "<literal style=\"html\">\n?\n</literal>")
9481 ("H" "#+html: "
9482 "<literal style=\"html\">?</literal>")
9483 ("a" "#+begin_ascii\n?\n#+end_ascii")
9484 ("A" "#+ascii: ")
9485 ("i" "#+include %file ?"
9486 "<include file=%file markup=\"?\">")
9488 "Structure completion elements.
9489 This is a list of abbreviation keys and values. The value gets inserted
9490 it you type @samp{.} followed by the key and then the completion key,
9491 usually `M-TAB'. %file will be replaced by a file name after prompting
9492 for the file using completion.
9493 There are two templates for each key, the first uses the original Org syntax,
9494 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9495 the default when the /org-mtags.el/ module has been loaded. See also the
9496 variable `org-mtags-prefer-muse-templates'.
9497 This is an experimental feature, it is undecided if it is going to stay in."
9498 :group 'org-completion
9499 :type '(repeat
9500 (string :tag "Key")
9501 (string :tag "Template")
9502 (string :tag "Muse Template")))
9504 (defun org-try-structure-completion ()
9505 "Try to complete a structure template before point.
9506 This looks for strings like \"<e\" on an otherwise empty line and
9507 expands them."
9508 (let ((l (buffer-substring (point-at-bol) (point)))
9510 (when (and (looking-at "[ \t]*$")
9511 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9512 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9513 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9514 (match-beginning 1)) a)
9515 t)))
9517 (defun org-complete-expand-structure-template (start cell)
9518 "Expand a structure template."
9519 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9520 (rpl (nth (if musep 2 1) cell))
9521 (ind ""))
9522 (delete-region start (point))
9523 (when (string-match "\\`#\\+" rpl)
9524 (cond
9525 ((bolp))
9526 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9527 (setq ind (buffer-substring (point-at-bol) (point))))
9528 (t (newline))))
9529 (setq start (point))
9530 (if (string-match "%file" rpl)
9531 (setq rpl (replace-match
9532 (concat
9533 "\""
9534 (save-match-data
9535 (abbreviate-file-name (read-file-name "Include file: ")))
9536 "\"")
9537 t t rpl)))
9538 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9539 (concat "\n" ind)))
9540 (insert rpl)
9541 (if (re-search-backward "\\?" start t) (delete-char 1))))
9544 (defun org-complete (&optional arg)
9545 "Perform completion on word at point.
9546 At the beginning of a headline, this completes TODO keywords as given in
9547 `org-todo-keywords'.
9548 If the current word is preceded by a backslash, completes the TeX symbols
9549 that are supported for HTML support.
9550 If the current word is preceded by \"#+\", completes special words for
9551 setting file options.
9552 In the line after \"#+STARTUP:, complete valid keywords.\"
9553 At all other locations, this simply calls the value of
9554 `org-completion-fallback-command'."
9555 (interactive "P")
9556 (org-without-partial-completion
9557 (catch 'exit
9558 (let* ((a nil)
9559 (end (point))
9560 (beg1 (save-excursion
9561 (skip-chars-backward (org-re "[:alnum:]_@"))
9562 (point)))
9563 (beg (save-excursion
9564 (skip-chars-backward "a-zA-Z0-9_:$")
9565 (point)))
9566 (confirm (lambda (x) (stringp (car x))))
9567 (searchhead (equal (char-before beg) ?*))
9568 (struct
9569 (when (and (member (char-before beg1) '(?. ?<))
9570 (setq a (assoc (buffer-substring beg1 (point))
9571 org-structure-template-alist)))
9572 (org-complete-expand-structure-template (1- beg1) a)
9573 (throw 'exit t)))
9574 (tag (and (equal (char-before beg1) ?:)
9575 (equal (char-after (point-at-bol)) ?*)))
9576 (prop (and (equal (char-before beg1) ?:)
9577 (not (equal (char-after (point-at-bol)) ?*))))
9578 (texp (equal (char-before beg) ?\\))
9579 (link (equal (char-before beg) ?\[))
9580 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9581 beg)
9582 "#+"))
9583 (startup (string-match "^#\\+STARTUP:.*"
9584 (buffer-substring (point-at-bol) (point))))
9585 (completion-ignore-case opt)
9586 (type nil)
9587 (tbl nil)
9588 (table (cond
9589 (opt
9590 (setq type :opt)
9591 (require 'org-exp)
9592 (append
9593 (delq nil
9594 (mapcar
9595 (lambda (x)
9596 (if (string-match
9597 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9598 (cons (match-string 2 x)
9599 (match-string 1 x))))
9600 (org-split-string (org-get-current-options) "\n")))
9601 (mapcar 'list org-additional-option-like-keywords)))
9602 (startup
9603 (setq type :startup)
9604 org-startup-options)
9605 (link (append org-link-abbrev-alist-local
9606 org-link-abbrev-alist))
9607 (texp
9608 (setq type :tex)
9609 org-html-entities)
9610 ((string-match "\\`\\*+[ \t]+\\'"
9611 (buffer-substring (point-at-bol) beg))
9612 (setq type :todo)
9613 (mapcar 'list org-todo-keywords-1))
9614 (searchhead
9615 (setq type :searchhead)
9616 (save-excursion
9617 (goto-char (point-min))
9618 (while (re-search-forward org-todo-line-regexp nil t)
9619 (push (list
9620 (org-make-org-heading-search-string
9621 (match-string 3) t))
9622 tbl)))
9623 tbl)
9624 (tag (setq type :tag beg beg1)
9625 (or org-tag-alist (org-get-buffer-tags)))
9626 (prop (setq type :prop beg beg1)
9627 (mapcar 'list (org-buffer-property-keys nil t t)))
9628 (t (progn
9629 (call-interactively org-completion-fallback-command)
9630 (throw 'exit nil)))))
9631 (pattern (buffer-substring-no-properties beg end))
9632 (completion (try-completion pattern table confirm)))
9633 (cond ((eq completion t)
9634 (if (not (assoc (upcase pattern) table))
9635 (message "Already complete")
9636 (if (and (equal type :opt)
9637 (not (member (car (assoc (upcase pattern) table))
9638 org-additional-option-like-keywords)))
9639 (insert (substring (cdr (assoc (upcase pattern) table))
9640 (length pattern)))
9641 (if (memq type '(:tag :prop)) (insert ":")))))
9642 ((null completion)
9643 (message "Can't find completion for \"%s\"" pattern)
9644 (ding))
9645 ((not (string= pattern completion))
9646 (delete-region beg end)
9647 (if (string-match " +$" completion)
9648 (setq completion (replace-match "" t t completion)))
9649 (insert completion)
9650 (if (get-buffer-window "*Completions*")
9651 (delete-window (get-buffer-window "*Completions*")))
9652 (if (assoc completion table)
9653 (if (eq type :todo) (insert " ")
9654 (if (memq type '(:tag :prop)) (insert ":"))))
9655 (if (and (equal type :opt) (assoc completion table))
9656 (message "%s" (substitute-command-keys
9657 "Press \\[org-complete] again to insert example settings"))))
9659 (message "Making completion list...")
9660 (let ((list (sort (all-completions pattern table confirm)
9661 'string<)))
9662 (with-output-to-temp-buffer "*Completions*"
9663 (condition-case nil
9664 ;; Protection needed for XEmacs and emacs 21
9665 (display-completion-list list pattern)
9666 (error (display-completion-list list)))))
9667 (message "Making completion list...%s" "done")))))))
9669 ;;;; TODO, DEADLINE, Comments
9671 (defun org-toggle-comment ()
9672 "Change the COMMENT state of an entry."
9673 (interactive)
9674 (save-excursion
9675 (org-back-to-heading)
9676 (let (case-fold-search)
9677 (if (looking-at (concat outline-regexp
9678 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9679 (replace-match "" t t nil 1)
9680 (if (looking-at outline-regexp)
9681 (progn
9682 (goto-char (match-end 0))
9683 (insert org-comment-string " ")))))))
9685 (defvar org-last-todo-state-is-todo nil
9686 "This is non-nil when the last TODO state change led to a TODO state.
9687 If the last change removed the TODO tag or switched to DONE, then
9688 this is nil.")
9690 (defvar org-setting-tags nil) ; dynamically skipped
9692 (defun org-parse-local-options (string var)
9693 "Parse STRING for startup setting relevant for variable VAR."
9694 (let ((rtn (symbol-value var))
9695 e opts)
9696 (save-match-data
9697 (if (or (not string) (not (string-match "\\S-" string)))
9699 (setq opts (delq nil (mapcar (lambda (x)
9700 (setq e (assoc x org-startup-options))
9701 (if (eq (nth 1 e) var) e nil))
9702 (org-split-string string "[ \t]+"))))
9703 (if (not opts)
9705 (setq rtn nil)
9706 (while (setq e (pop opts))
9707 (if (not (nth 3 e))
9708 (setq rtn (nth 2 e))
9709 (if (not (listp rtn)) (setq rtn nil))
9710 (push (nth 2 e) rtn)))
9711 rtn)))))
9713 (defvar org-todo-setup-filter-hook nil
9714 "Hook for functions that pre-filter todo specs.
9716 Each function takes a todo spec and returns either `nil' or the spec
9717 transformed into canonical form." )
9719 (defvar org-todo-get-default-hook nil
9720 "Hook for functions that get a default item for todo.
9722 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9723 `nil' or a string to be used for the todo mark." )
9725 (defvar org-agenda-headline-snapshot-before-repeat)
9727 (defun org-todo (&optional arg)
9728 "Change the TODO state of an item.
9729 The state of an item is given by a keyword at the start of the heading,
9730 like
9731 *** TODO Write paper
9732 *** DONE Call mom
9734 The different keywords are specified in the variable `org-todo-keywords'.
9735 By default the available states are \"TODO\" and \"DONE\".
9736 So for this example: when the item starts with TODO, it is changed to DONE.
9737 When it starts with DONE, the DONE is removed. And when neither TODO nor
9738 DONE are present, add TODO at the beginning of the heading.
9740 With C-u prefix arg, use completion to determine the new state.
9741 With numeric prefix arg, switch to that state.
9742 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9743 With a triple C-u prefix, circumvent any state blocking.
9745 For calling through lisp, arg is also interpreted in the following way:
9746 'none -> empty state
9747 \"\"(empty string) -> switch to empty state
9748 'done -> switch to DONE
9749 'nextset -> switch to the next set of keywords
9750 'previousset -> switch to the previous set of keywords
9751 \"WAITING\" -> switch to the specified keyword, but only if it
9752 really is a member of `org-todo-keywords'."
9753 (interactive "P")
9754 (if (equal arg '(16)) (setq arg 'nextset))
9755 (let ((org-blocker-hook org-blocker-hook)
9756 (case-fold-search nil))
9757 (when (equal arg '(64))
9758 (setq arg nil org-blocker-hook nil))
9759 (when (and org-blocker-hook
9760 (or org-inhibit-blocking
9761 (org-entry-get nil "NOBLOCKING")))
9762 (setq org-blocker-hook nil))
9763 (save-excursion
9764 (catch 'exit
9765 (org-back-to-heading t)
9766 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9767 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9768 (looking-at " *"))
9769 (let* ((match-data (match-data))
9770 (startpos (point-at-bol))
9771 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9772 (org-log-done org-log-done)
9773 (org-log-repeat org-log-repeat)
9774 (org-todo-log-states org-todo-log-states)
9775 (this (match-string 1))
9776 (hl-pos (match-beginning 0))
9777 (head (org-get-todo-sequence-head this))
9778 (ass (assoc head org-todo-kwd-alist))
9779 (interpret (nth 1 ass))
9780 (done-word (nth 3 ass))
9781 (final-done-word (nth 4 ass))
9782 (last-state (or this ""))
9783 (completion-ignore-case t)
9784 (member (member this org-todo-keywords-1))
9785 (tail (cdr member))
9786 (state (cond
9787 ((and org-todo-key-trigger
9788 (or (and (equal arg '(4))
9789 (eq org-use-fast-todo-selection 'prefix))
9790 (and (not arg) org-use-fast-todo-selection
9791 (not (eq org-use-fast-todo-selection
9792 'prefix)))))
9793 ;; Use fast selection
9794 (org-fast-todo-selection))
9795 ((and (equal arg '(4))
9796 (or (not org-use-fast-todo-selection)
9797 (not org-todo-key-trigger)))
9798 ;; Read a state with completion
9799 (org-icompleting-read
9800 "State: " (mapcar (lambda(x) (list x))
9801 org-todo-keywords-1)
9802 nil t))
9803 ((eq arg 'right)
9804 (if this
9805 (if tail (car tail) nil)
9806 (car org-todo-keywords-1)))
9807 ((eq arg 'left)
9808 (if (equal member org-todo-keywords-1)
9810 (if this
9811 (nth (- (length org-todo-keywords-1)
9812 (length tail) 2)
9813 org-todo-keywords-1)
9814 (org-last org-todo-keywords-1))))
9815 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9816 (setq arg nil))) ; hack to fall back to cycling
9817 (arg
9818 ;; user or caller requests a specific state
9819 (cond
9820 ((equal arg "") nil)
9821 ((eq arg 'none) nil)
9822 ((eq arg 'done) (or done-word (car org-done-keywords)))
9823 ((eq arg 'nextset)
9824 (or (car (cdr (member head org-todo-heads)))
9825 (car org-todo-heads)))
9826 ((eq arg 'previousset)
9827 (let ((org-todo-heads (reverse org-todo-heads)))
9828 (or (car (cdr (member head org-todo-heads)))
9829 (car org-todo-heads))))
9830 ((car (member arg org-todo-keywords-1)))
9831 ((stringp arg)
9832 (error "State `%s' not valid in this file" arg))
9833 ((nth (1- (prefix-numeric-value arg))
9834 org-todo-keywords-1))))
9835 ((null member) (or head (car org-todo-keywords-1)))
9836 ((equal this final-done-word) nil) ;; -> make empty
9837 ((null tail) nil) ;; -> first entry
9838 ((memq interpret '(type priority))
9839 (if (eq this-command last-command)
9840 (car tail)
9841 (if (> (length tail) 0)
9842 (or done-word (car org-done-keywords))
9843 nil)))
9845 (car tail))))
9846 (state (or
9847 (run-hook-with-args-until-success
9848 'org-todo-get-default-hook state last-state)
9849 state))
9850 (next (if state (concat " " state " ") " "))
9851 (change-plist (list :type 'todo-state-change :from this :to state
9852 :position startpos))
9853 dolog now-done-p)
9854 (when org-blocker-hook
9855 (setq org-last-todo-state-is-todo
9856 (not (member this org-done-keywords)))
9857 (unless (save-excursion
9858 (save-match-data
9859 (run-hook-with-args-until-failure
9860 'org-blocker-hook change-plist)))
9861 (if (interactive-p)
9862 (error "TODO state change from %s to %s blocked" this state)
9863 ;; fail silently
9864 (message "TODO state change from %s to %s blocked" this state)
9865 (throw 'exit nil))))
9866 (store-match-data match-data)
9867 (replace-match next t t)
9868 (unless (pos-visible-in-window-p hl-pos)
9869 (message "TODO state changed to %s" (org-trim next)))
9870 (unless head
9871 (setq head (org-get-todo-sequence-head state)
9872 ass (assoc head org-todo-kwd-alist)
9873 interpret (nth 1 ass)
9874 done-word (nth 3 ass)
9875 final-done-word (nth 4 ass)))
9876 (when (memq arg '(nextset previousset))
9877 (message "Keyword-Set %d/%d: %s"
9878 (- (length org-todo-sets) -1
9879 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9880 (length org-todo-sets)
9881 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9882 (setq org-last-todo-state-is-todo
9883 (not (member state org-done-keywords)))
9884 (setq now-done-p (and (member state org-done-keywords)
9885 (not (member this org-done-keywords))))
9886 (and logging (org-local-logging logging))
9887 (when (and (or org-todo-log-states org-log-done)
9888 (not (eq org-inhibit-logging t))
9889 (not (memq arg '(nextset previousset))))
9890 ;; we need to look at recording a time and note
9891 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9892 (nth 2 (assoc this org-todo-log-states))))
9893 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9894 (setq dolog 'time))
9895 (when (and state
9896 (member state org-not-done-keywords)
9897 (not (member this org-not-done-keywords)))
9898 ;; This is now a todo state and was not one before
9899 ;; If there was a CLOSED time stamp, get rid of it.
9900 (org-add-planning-info nil nil 'closed))
9901 (when (and now-done-p org-log-done)
9902 ;; It is now done, and it was not done before
9903 (org-add-planning-info 'closed (org-current-time))
9904 (if (and (not dolog) (eq 'note org-log-done))
9905 (org-add-log-setup 'done state this 'findpos 'note)))
9906 (when (and state dolog)
9907 ;; This is a non-nil state, and we need to log it
9908 (org-add-log-setup 'state state this 'findpos dolog)))
9909 ;; Fixup tag positioning
9910 (org-todo-trigger-tag-changes state)
9911 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9912 (when org-provide-todo-statistics
9913 (org-update-parent-todo-statistics))
9914 (run-hooks 'org-after-todo-state-change-hook)
9915 (if (and arg (not (member state org-done-keywords)))
9916 (setq head (org-get-todo-sequence-head state)))
9917 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9918 ;; Do we need to trigger a repeat?
9919 (when now-done-p
9920 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9921 ;; This is for the agenda, take a snapshot of the headline.
9922 (save-match-data
9923 (setq org-agenda-headline-snapshot-before-repeat
9924 (org-get-heading))))
9925 (org-auto-repeat-maybe state))
9926 ;; Fixup cursor location if close to the keyword
9927 (if (and (outline-on-heading-p)
9928 (not (bolp))
9929 (save-excursion (beginning-of-line 1)
9930 (looking-at org-todo-line-regexp))
9931 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9932 (progn
9933 (goto-char (or (match-end 2) (match-end 1)))
9934 (and (looking-at " ") (just-one-space))))
9935 (when org-trigger-hook
9936 (save-excursion
9937 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9939 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9940 "Block turning an entry into a TODO, using the hierarchy.
9941 This checks whether the current task should be blocked from state
9942 changes. Such blocking occurs when:
9944 1. The task has children which are not all in a completed state.
9946 2. A task has a parent with the property :ORDERED:, and there
9947 are siblings prior to the current task with incomplete
9948 status.
9950 3. The parent of the task is blocked because it has siblings that should
9951 be done first, or is child of a block grandparent TODO entry."
9953 (catch 'dont-block
9954 ;; If this is not a todo state change, or if this entry is already DONE,
9955 ;; do not block
9956 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9957 (member (plist-get change-plist :from)
9958 (cons 'done org-done-keywords))
9959 (member (plist-get change-plist :to)
9960 (cons 'todo org-not-done-keywords))
9961 (not (plist-get change-plist :to)))
9962 (throw 'dont-block t))
9963 ;; If this task has children, and any are undone, it's blocked
9964 (save-excursion
9965 (org-back-to-heading t)
9966 (let ((this-level (funcall outline-level)))
9967 (outline-next-heading)
9968 (let ((child-level (funcall outline-level)))
9969 (while (and (not (eobp))
9970 (> child-level this-level))
9971 ;; this todo has children, check whether they are all
9972 ;; completed
9973 (if (and (not (org-entry-is-done-p))
9974 (org-entry-is-todo-p))
9975 (throw 'dont-block nil))
9976 (outline-next-heading)
9977 (setq child-level (funcall outline-level))))))
9978 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9979 ;; any previous siblings are undone, it's blocked
9980 (save-excursion
9981 (org-back-to-heading t)
9982 (let* ((pos (point))
9983 (parent-pos (and (org-up-heading-safe) (point))))
9984 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9985 (when (and (org-entry-get (point) "ORDERED")
9986 (forward-line 1)
9987 (re-search-forward org-not-done-heading-regexp pos t))
9988 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9989 ;; Search further up the hierarchy, to see if an anchestor is blocked
9990 (while t
9991 (goto-char parent-pos)
9992 (if (not (looking-at org-not-done-heading-regexp))
9993 (throw 'dont-block t)) ; do not block, parent is not a TODO
9994 (setq pos (point))
9995 (setq parent-pos (and (org-up-heading-safe) (point)))
9996 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9997 (when (and (org-entry-get (point) "ORDERED")
9998 (forward-line 1)
9999 (re-search-forward org-not-done-heading-regexp pos t))
10000 (throw 'dont-block nil))))))) ; block, older sibling not done.
10002 (defcustom org-track-ordered-property-with-tag nil
10003 "Should the ORDERED property also be shown as a tag?
10004 The ORDERED property decides if an entry should require subtasks to be
10005 completed in sequence. Since a property is not very visible, setting
10006 this option means that toggling the ORDERED property with the command
10007 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10008 not relevant for the behavior, but it makes things more visible.
10010 Note that toggling the tag with tags commands will not change the property
10011 and therefore not influence behavior!
10013 This can be t, meaning the tag ORDERED should be used, It can also be a
10014 string to select a different tag for this task."
10015 :group 'org-todo
10016 :type '(choice
10017 (const :tag "No tracking" nil)
10018 (const :tag "Track with ORDERED tag" t)
10019 (string :tag "Use other tag")))
10021 (defun org-toggle-ordered-property ()
10022 "Toggle the ORDERED property of the current entry.
10023 For better visibility, you can track the value of this property with a tag.
10024 See variable `org-track-ordered-property-with-tag'."
10025 (interactive)
10026 (let* ((t1 org-track-ordered-property-with-tag)
10027 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10028 (save-excursion
10029 (org-back-to-heading)
10030 (if (org-entry-get nil "ORDERED")
10031 (progn
10032 (org-delete-property "ORDERED")
10033 (and tag (org-toggle-tag tag 'off))
10034 (message "Subtasks can be completed in arbitrary order"))
10035 (org-entry-put nil "ORDERED" "t")
10036 (and tag (org-toggle-tag tag 'on))
10037 (message "Subtasks must be completed in sequence")))))
10039 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10040 (defun org-block-todo-from-checkboxes (change-plist)
10041 "Block turning an entry into a TODO, using checkboxes.
10042 This checks whether the current task should be blocked from state
10043 changes because there are unchecked boxes in this entry."
10044 (catch 'dont-block
10045 ;; If this is not a todo state change, or if this entry is already DONE,
10046 ;; do not block
10047 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10048 (member (plist-get change-plist :from)
10049 (cons 'done org-done-keywords))
10050 (member (plist-get change-plist :to)
10051 (cons 'todo org-not-done-keywords))
10052 (not (plist-get change-plist :to)))
10053 (throw 'dont-block t))
10054 ;; If this task has checkboxes that are not checked, it's blocked
10055 (save-excursion
10056 (org-back-to-heading t)
10057 (let ((beg (point)) end)
10058 (outline-next-heading)
10059 (setq end (point))
10060 (goto-char beg)
10061 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10062 end t)
10063 (progn
10064 (if (boundp 'org-blocked-by-checkboxes)
10065 (setq org-blocked-by-checkboxes t))
10066 (throw 'dont-block nil)))))
10067 t)) ; do not block
10069 (defun org-update-statistics-cookies (all)
10070 "Update the statistics cookie, either from TODO or from checkboxes.
10071 This should be called with the cursor in a line with a statistics cookie."
10072 (interactive "P")
10073 (if all
10074 (progn
10075 (org-update-checkbox-count 'all)
10076 (org-map-entries 'org-update-parent-todo-statistics))
10077 (if (not (org-on-heading-p))
10078 (org-update-checkbox-count)
10079 (let ((pos (move-marker (make-marker) (point)))
10080 end l1 l2)
10081 (ignore-errors (org-back-to-heading t))
10082 (if (not (org-on-heading-p))
10083 (org-update-checkbox-count)
10084 (setq l1 (org-outline-level))
10085 (setq end (save-excursion
10086 (outline-next-heading)
10087 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10088 (point)))
10089 (if (and (save-excursion (re-search-forward
10090 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10091 (not (save-excursion (re-search-forward
10092 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10093 (org-update-checkbox-count)
10094 (if (and l2 (> l2 l1))
10095 (progn
10096 (goto-char end)
10097 (org-update-parent-todo-statistics))
10098 (error "No data for statistics cookie"))))
10099 (goto-char pos)
10100 (move-marker pos nil)))))
10102 (defvar org-entry-property-inherited-from) ;; defined below
10103 (defun org-update-parent-todo-statistics ()
10104 "Update any statistics cookie in the parent of the current headline.
10105 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10106 the entire subtree and this will travel up the hierarchy and update
10107 statistics everywhere."
10108 (interactive)
10109 (let* ((lim 0) prop
10110 (recursive (or (not org-hierarchical-todo-statistics)
10111 (string-match
10112 "\\<recursive\\>"
10113 (or (setq prop (org-entry-get
10114 nil "COOKIE_DATA" 'inherit)) ""))))
10115 (lim (or (and prop (marker-position
10116 org-entry-property-inherited-from))
10117 lim))
10118 (first t)
10119 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10120 level ltoggle l1 new ndel
10121 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10122 (catch 'exit
10123 (save-excursion
10124 (beginning-of-line 1)
10125 (if (org-at-heading-p)
10126 (setq ltoggle (funcall outline-level))
10127 (error "This should not happen"))
10128 (while (and (setq level (org-up-heading-safe))
10129 (or recursive first)
10130 (>= (point) lim))
10131 (setq first nil cookie-present nil)
10132 (unless (and level
10133 (not (string-match
10134 "\\<checkbox\\>"
10135 (downcase
10136 (or (org-entry-get
10137 nil "COOKIE_DATA")
10138 "")))))
10139 (throw 'exit nil))
10140 (while (re-search-forward box-re (point-at-eol) t)
10141 (setq cnt-all 0 cnt-done 0 cookie-present t)
10142 (setq is-percent (match-end 2))
10143 (save-match-data
10144 (unless (outline-next-heading) (throw 'exit nil))
10145 (while (and (looking-at org-complex-heading-regexp)
10146 (> (setq l1 (length (match-string 1))) level))
10147 (setq kwd (and (or recursive (= l1 ltoggle))
10148 (match-string 2)))
10149 (if (or (eq org-provide-todo-statistics 'all-headlines)
10150 (and (listp org-provide-todo-statistics)
10151 (or (member kwd org-provide-todo-statistics)
10152 (member kwd org-done-keywords))))
10153 (setq cnt-all (1+ cnt-all))
10154 (if (eq org-provide-todo-statistics t)
10155 (and kwd (setq cnt-all (1+ cnt-all)))))
10156 (and (member kwd org-done-keywords)
10157 (setq cnt-done (1+ cnt-done)))
10158 (outline-next-heading)))
10159 (setq new
10160 (if is-percent
10161 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10162 (format "[%d/%d]" cnt-done cnt-all))
10163 ndel (- (match-end 0) (match-beginning 0)))
10164 (goto-char (match-beginning 0))
10165 (insert new)
10166 (delete-region (point) (+ (point) ndel)))
10167 (when cookie-present
10168 (run-hook-with-args 'org-after-todo-statistics-hook
10169 cnt-done (- cnt-all cnt-done))))))
10170 (run-hooks 'org-todo-statistics-hook)))
10172 (defvar org-after-todo-statistics-hook nil
10173 "Hook that is called after a TODO statistics cookie has been updated.
10174 Each function is called with two arguments: the number of not-done entries
10175 and the number of done entries.
10177 For example, the following function, when added to this hook, will switch
10178 an entry to DONE when all children are done, and back to TODO when new
10179 entries are set to a TODO status. Note that this hook is only called
10180 when there is a statistics cookie in the headline!
10182 (defun org-summary-todo (n-done n-not-done)
10183 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10184 (let (org-log-done org-log-states) ; turn off logging
10185 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10188 (defvar org-todo-statistics-hook nil
10189 "Hook that is run whenever Org thinks TODO statistics should be updated.
10190 This hook runs even if there is no statistics cookie present, in which case
10191 `org-after-todo-statistics-hook' would not run.")
10193 (defun org-todo-trigger-tag-changes (state)
10194 "Apply the changes defined in `org-todo-state-tags-triggers'."
10195 (let ((l org-todo-state-tags-triggers)
10196 changes)
10197 (when (or (not state) (equal state ""))
10198 (setq changes (append changes (cdr (assoc "" l)))))
10199 (when (and (stringp state) (> (length state) 0))
10200 (setq changes (append changes (cdr (assoc state l)))))
10201 (when (member state org-not-done-keywords)
10202 (setq changes (append changes (cdr (assoc 'todo l)))))
10203 (when (member state org-done-keywords)
10204 (setq changes (append changes (cdr (assoc 'done l)))))
10205 (dolist (c changes)
10206 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10208 (defun org-local-logging (value)
10209 "Get logging settings from a property VALUE."
10210 (let* (words w a)
10211 ;; directly set the variables, they are already local.
10212 (setq org-log-done nil
10213 org-log-repeat nil
10214 org-todo-log-states nil)
10215 (setq words (org-split-string value))
10216 (while (setq w (pop words))
10217 (cond
10218 ((setq a (assoc w org-startup-options))
10219 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10220 (set (nth 1 a) (nth 2 a))))
10221 ((setq a (org-extract-log-state-settings w))
10222 (and (member (car a) org-todo-keywords-1)
10223 (push a org-todo-log-states)))))))
10225 (defun org-get-todo-sequence-head (kwd)
10226 "Return the head of the TODO sequence to which KWD belongs.
10227 If KWD is not set, check if there is a text property remembering the
10228 right sequence."
10229 (let (p)
10230 (cond
10231 ((not kwd)
10232 (or (get-text-property (point-at-bol) 'org-todo-head)
10233 (progn
10234 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10235 nil (point-at-eol)))
10236 (get-text-property p 'org-todo-head))))
10237 ((not (member kwd org-todo-keywords-1))
10238 (car org-todo-keywords-1))
10239 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10241 (defun org-fast-todo-selection ()
10242 "Fast TODO keyword selection with single keys.
10243 Returns the new TODO keyword, or nil if no state change should occur."
10244 (let* ((fulltable org-todo-key-alist)
10245 (done-keywords org-done-keywords) ;; needed for the faces.
10246 (maxlen (apply 'max (mapcar
10247 (lambda (x)
10248 (if (stringp (car x)) (string-width (car x)) 0))
10249 fulltable)))
10250 (expert nil)
10251 (fwidth (+ maxlen 3 1 3))
10252 (ncol (/ (- (window-width) 4) fwidth))
10253 tg cnt e c tbl
10254 groups ingroup)
10255 (save-excursion
10256 (save-window-excursion
10257 (if expert
10258 (set-buffer (get-buffer-create " *Org todo*"))
10259 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10260 (erase-buffer)
10261 (org-set-local 'org-done-keywords done-keywords)
10262 (setq tbl fulltable cnt 0)
10263 (while (setq e (pop tbl))
10264 (cond
10265 ((equal e '(:startgroup))
10266 (push '() groups) (setq ingroup t)
10267 (when (not (= cnt 0))
10268 (setq cnt 0)
10269 (insert "\n"))
10270 (insert "{ "))
10271 ((equal e '(:endgroup))
10272 (setq ingroup nil cnt 0)
10273 (insert "}\n"))
10274 ((equal e '(:newline))
10275 (when (not (= cnt 0))
10276 (setq cnt 0)
10277 (insert "\n")
10278 (setq e (car tbl))
10279 (while (equal (car tbl) '(:newline))
10280 (insert "\n")
10281 (setq tbl (cdr tbl)))))
10283 (setq tg (car e) c (cdr e))
10284 (if ingroup (push tg (car groups)))
10285 (setq tg (org-add-props tg nil 'face
10286 (org-get-todo-face tg)))
10287 (if (and (= cnt 0) (not ingroup)) (insert " "))
10288 (insert "[" c "] " tg (make-string
10289 (- fwidth 4 (length tg)) ?\ ))
10290 (when (= (setq cnt (1+ cnt)) ncol)
10291 (insert "\n")
10292 (if ingroup (insert " "))
10293 (setq cnt 0)))))
10294 (insert "\n")
10295 (goto-char (point-min))
10296 (if (not expert) (org-fit-window-to-buffer))
10297 (message "[a-z..]:Set [SPC]:clear")
10298 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10299 (cond
10300 ((or (= c ?\C-g)
10301 (and (= c ?q) (not (rassoc c fulltable))))
10302 (setq quit-flag t))
10303 ((= c ?\ ) nil)
10304 ((setq e (rassoc c fulltable) tg (car e))
10306 (t (setq quit-flag t)))))))
10308 (defun org-entry-is-todo-p ()
10309 (member (org-get-todo-state) org-not-done-keywords))
10311 (defun org-entry-is-done-p ()
10312 (member (org-get-todo-state) org-done-keywords))
10314 (defun org-get-todo-state ()
10315 (save-excursion
10316 (org-back-to-heading t)
10317 (and (looking-at org-todo-line-regexp)
10318 (match-end 2)
10319 (match-string 2))))
10321 (defun org-at-date-range-p (&optional inactive-ok)
10322 "Is the cursor inside a date range?"
10323 (interactive)
10324 (save-excursion
10325 (catch 'exit
10326 (let ((pos (point)))
10327 (skip-chars-backward "^[<\r\n")
10328 (skip-chars-backward "<[")
10329 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10330 (>= (match-end 0) pos)
10331 (throw 'exit t))
10332 (skip-chars-backward "^<[\r\n")
10333 (skip-chars-backward "<[")
10334 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10335 (>= (match-end 0) pos)
10336 (throw 'exit t)))
10337 nil)))
10339 (defun org-get-repeat (&optional tagline)
10340 "Check if there is a deadline/schedule with repeater in this entry."
10341 (save-match-data
10342 (save-excursion
10343 (org-back-to-heading t)
10344 (and (re-search-forward (if tagline
10345 (concat tagline "\\s-*" org-repeat-re)
10346 org-repeat-re)
10347 (org-entry-end-position) t)
10348 (match-string-no-properties 1)))))
10350 (defvar org-last-changed-timestamp)
10351 (defvar org-last-inserted-timestamp)
10352 (defvar org-log-post-message)
10353 (defvar org-log-note-purpose)
10354 (defvar org-log-note-how)
10355 (defvar org-log-note-extra)
10356 (defun org-auto-repeat-maybe (done-word)
10357 "Check if the current headline contains a repeated deadline/schedule.
10358 If yes, set TODO state back to what it was and change the base date
10359 of repeating deadline/scheduled time stamps to new date.
10360 This function is run automatically after each state change to a DONE state."
10361 ;; last-state is dynamically scoped into this function
10362 (let* ((repeat (org-get-repeat))
10363 (aa (assoc last-state org-todo-kwd-alist))
10364 (interpret (nth 1 aa))
10365 (head (nth 2 aa))
10366 (whata '(("d" . day) ("m" . month) ("y" . year)))
10367 (msg "Entry repeats: ")
10368 (org-log-done nil)
10369 (org-todo-log-states nil)
10370 (nshiftmax 10) (nshift 0)
10371 re type n what ts time)
10372 (when repeat
10373 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10374 (org-todo (if (eq interpret 'type) last-state head))
10375 (org-entry-put nil "LAST_REPEAT" (format-time-string
10376 (org-time-stamp-format t t)))
10377 (when org-log-repeat
10378 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10379 (memq 'org-add-log-note post-command-hook))
10380 ;; OK, we are already setup for some record
10381 (if (eq org-log-repeat 'note)
10382 ;; make sure we take a note, not only a time stamp
10383 (setq org-log-note-how 'note))
10384 ;; Set up for taking a record
10385 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10386 last-state
10387 'findpos org-log-repeat)))
10388 (org-back-to-heading t)
10389 (org-add-planning-info nil nil 'closed)
10390 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10391 org-deadline-time-regexp "\\)\\|\\("
10392 org-ts-regexp "\\)"))
10393 (while (re-search-forward
10394 re (save-excursion (outline-next-heading) (point)) t)
10395 (setq type (if (match-end 1) org-scheduled-string
10396 (if (match-end 3) org-deadline-string "Plain:"))
10397 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10398 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10399 (setq n (string-to-number (match-string 2 ts))
10400 what (match-string 3 ts))
10401 (if (equal what "w") (setq n (* n 7) what "d"))
10402 ;; Preparation, see if we need to modify the start date for the change
10403 (when (match-end 1)
10404 (setq time (save-match-data (org-time-string-to-time ts)))
10405 (cond
10406 ((equal (match-string 1 ts) ".")
10407 ;; Shift starting date to today
10408 (org-timestamp-change
10409 (- (time-to-days (current-time)) (time-to-days time))
10410 'day))
10411 ((equal (match-string 1 ts) "+")
10412 (while (or (= nshift 0)
10413 (<= (time-to-days time) (time-to-days (current-time))))
10414 (when (= (incf nshift) nshiftmax)
10415 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10416 (error "Abort")))
10417 (org-timestamp-change n (cdr (assoc what whata)))
10418 (org-at-timestamp-p t)
10419 (setq ts (match-string 1))
10420 (setq time (save-match-data (org-time-string-to-time ts))))
10421 (org-timestamp-change (- n) (cdr (assoc what whata)))
10422 ;; rematch, so that we have everything in place for the real shift
10423 (org-at-timestamp-p t)
10424 (setq ts (match-string 1))
10425 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10426 (org-timestamp-change n (cdr (assoc what whata)))
10427 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10428 (setq org-log-post-message msg)
10429 (message "%s" msg))))
10431 (defun org-show-todo-tree (arg)
10432 "Make a compact tree which shows all headlines marked with TODO.
10433 The tree will show the lines where the regexp matches, and all higher
10434 headlines above the match.
10435 With a \\[universal-argument] prefix, prompt for a regexp to match.
10436 With a numeric prefix N, construct a sparse tree for the Nth element
10437 of `org-todo-keywords-1'."
10438 (interactive "P")
10439 (let ((case-fold-search nil)
10440 (kwd-re
10441 (cond ((null arg) org-not-done-regexp)
10442 ((equal arg '(4))
10443 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10444 (mapcar 'list org-todo-keywords-1))))
10445 (concat "\\("
10446 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10447 "\\)\\>")))
10448 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10449 (regexp-quote (nth (1- (prefix-numeric-value arg))
10450 org-todo-keywords-1)))
10451 (t (error "Invalid prefix argument: %s" arg)))))
10452 (message "%d TODO entries found"
10453 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10455 (defun org-deadline (&optional remove time)
10456 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10457 With argument REMOVE, remove any deadline from the item.
10458 When TIME is set, it should be an internal time specification, and the
10459 scheduling will use the corresponding date."
10460 (interactive "P")
10461 (let ((old-date (org-entry-get nil "DEADLINE")))
10462 (if remove
10463 (progn
10464 (org-remove-timestamp-with-keyword org-deadline-string)
10465 (message "Item no longer has a deadline."))
10466 (if (org-get-repeat)
10467 (error "Cannot change deadline on task with repeater, please do that by hand")
10468 (org-add-planning-info 'deadline time 'closed)
10469 (when (and old-date org-log-redeadline
10470 (not (equal old-date
10471 (substring org-last-inserted-timestamp 1 -1))))
10472 (org-add-log-setup 'redeadline nil old-date 'findpos
10473 org-log-redeadline))
10474 (message "Deadline on %s" org-last-inserted-timestamp)))))
10476 (defun org-schedule (&optional remove time)
10477 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10478 With argument REMOVE, remove any scheduling date from the item.
10479 When TIME is set, it should be an internal time specification, and the
10480 scheduling will use the corresponding date."
10481 (interactive "P")
10482 (let ((old-date (org-entry-get nil "SCHEDULED")))
10483 (if remove
10484 (progn
10485 (org-remove-timestamp-with-keyword org-scheduled-string)
10486 (message "Item is no longer scheduled."))
10487 (if (org-get-repeat)
10488 (error "Cannot reschedule task with repeater, please do that by hand")
10489 (org-add-planning-info 'scheduled time 'closed)
10490 (when (and old-date org-log-reschedule
10491 (not (equal old-date
10492 (substring org-last-inserted-timestamp 1 -1))))
10493 (org-add-log-setup 'reschedule nil old-date 'findpos
10494 org-log-reschedule))
10495 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10497 (defun org-get-scheduled-time (pom &optional inherit)
10498 "Get the scheduled time as a time tuple, of a format suitable
10499 for calling org-schedule with, or if there is no scheduling,
10500 returns nil."
10501 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10502 (when time
10503 (apply 'encode-time (org-parse-time-string time)))))
10505 (defun org-get-deadline-time (pom &optional inherit)
10506 "Get the deadine as a time tuple, of a format suitable for
10507 calling org-deadline with, or if there is no scheduling, returns
10508 nil."
10509 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10510 (when time
10511 (apply 'encode-time (org-parse-time-string time)))))
10513 (defun org-remove-timestamp-with-keyword (keyword)
10514 "Remove all time stamps with KEYWORD in the current entry."
10515 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10516 beg)
10517 (save-excursion
10518 (org-back-to-heading t)
10519 (setq beg (point))
10520 (outline-next-heading)
10521 (while (re-search-backward re beg t)
10522 (replace-match "")
10523 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10524 (equal (char-before) ?\ ))
10525 (backward-delete-char 1)
10526 (if (string-match "^[ \t]*$" (buffer-substring
10527 (point-at-bol) (point-at-eol)))
10528 (delete-region (point-at-bol)
10529 (min (point-max) (1+ (point-at-eol))))))))))
10531 (defun org-add-planning-info (what &optional time &rest remove)
10532 "Insert new timestamp with keyword in the line directly after the headline.
10533 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10534 If non is given, the user is prompted for a date.
10535 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10536 be removed."
10537 (interactive)
10538 (let (org-time-was-given org-end-time-was-given ts
10539 end default-time default-input)
10541 (catch 'exit
10542 (when (and (not time) (memq what '(scheduled deadline)))
10543 ;; Try to get a default date/time from existing timestamp
10544 (save-excursion
10545 (org-back-to-heading t)
10546 (setq end (save-excursion (outline-next-heading) (point)))
10547 (when (re-search-forward (if (eq what 'scheduled)
10548 org-scheduled-time-regexp
10549 org-deadline-time-regexp)
10550 end t)
10551 (setq ts (match-string 1)
10552 default-time
10553 (apply 'encode-time (org-parse-time-string ts))
10554 default-input (and ts (org-get-compact-tod ts))))))
10555 (when what
10556 ;; If necessary, get the time from the user
10557 (setq time (or time (org-read-date nil 'to-time nil nil
10558 default-time default-input))))
10560 (when (and org-insert-labeled-timestamps-at-point
10561 (member what '(scheduled deadline)))
10562 (insert
10563 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10564 (org-insert-time-stamp time org-time-was-given
10565 nil nil nil (list org-end-time-was-given))
10566 (setq what nil))
10567 (save-excursion
10568 (save-restriction
10569 (let (col list elt ts buffer-invisibility-spec)
10570 (org-back-to-heading t)
10571 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10572 (goto-char (match-end 1))
10573 (setq col (current-column))
10574 (goto-char (match-end 0))
10575 (if (eobp) (insert "\n") (forward-char 1))
10576 (when (and (not what)
10577 (not (looking-at
10578 (concat "[ \t]*"
10579 org-keyword-time-not-clock-regexp))))
10580 ;; Nothing to add, nothing to remove...... :-)
10581 (throw 'exit nil))
10582 (if (and (not (looking-at outline-regexp))
10583 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10584 "[^\r\n]*"))
10585 (not (equal (match-string 1) org-clock-string)))
10586 (narrow-to-region (match-beginning 0) (match-end 0))
10587 (insert-before-markers "\n")
10588 (backward-char 1)
10589 (narrow-to-region (point) (point))
10590 (and org-adapt-indentation (org-indent-to-column col)))
10591 ;; Check if we have to remove something.
10592 (setq list (cons what remove))
10593 (while list
10594 (setq elt (pop list))
10595 (goto-char (point-min))
10596 (when (or (and (eq elt 'scheduled)
10597 (re-search-forward org-scheduled-time-regexp nil t))
10598 (and (eq elt 'deadline)
10599 (re-search-forward org-deadline-time-regexp nil t))
10600 (and (eq elt 'closed)
10601 (re-search-forward org-closed-time-regexp nil t)))
10602 (replace-match "")
10603 (if (looking-at "--+<[^>]+>") (replace-match ""))
10604 (skip-chars-backward " ")
10605 (if (looking-at " +") (replace-match ""))))
10606 (goto-char (point-max))
10607 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10608 (when what
10609 (insert
10610 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10611 (cond ((eq what 'scheduled) org-scheduled-string)
10612 ((eq what 'deadline) org-deadline-string)
10613 ((eq what 'closed) org-closed-string))
10614 " ")
10615 (setq ts (org-insert-time-stamp
10616 time
10617 (or org-time-was-given
10618 (and (eq what 'closed) org-log-done-with-time))
10619 (eq what 'closed)
10620 nil nil (list org-end-time-was-given)))
10621 (end-of-line 1))
10622 (goto-char (point-min))
10623 (widen)
10624 (if (and (looking-at "[ \t]+\n")
10625 (equal (char-before) ?\n))
10626 (delete-region (1- (point)) (point-at-eol)))
10627 ts))))))
10629 (defvar org-log-note-marker (make-marker))
10630 (defvar org-log-note-purpose nil)
10631 (defvar org-log-note-state nil)
10632 (defvar org-log-note-previous-state nil)
10633 (defvar org-log-note-how nil)
10634 (defvar org-log-note-extra nil)
10635 (defvar org-log-note-window-configuration nil)
10636 (defvar org-log-note-return-to (make-marker))
10637 (defvar org-log-post-message nil
10638 "Message to be displayed after a log note has been stored.
10639 The auto-repeater uses this.")
10641 (defun org-add-note ()
10642 "Add a note to the current entry.
10643 This is done in the same way as adding a state change note."
10644 (interactive)
10645 (org-add-log-setup 'note nil nil 'findpos nil))
10647 (defvar org-property-end-re)
10648 (defun org-add-log-setup (&optional purpose state prev-state
10649 findpos how &optional extra)
10650 "Set up the post command hook to take a note.
10651 If this is about to TODO state change, the new state is expected in STATE.
10652 When FINDPOS is non-nil, find the correct position for the note in
10653 the current entry. If not, assume that it can be inserted at point.
10654 HOW is an indicator what kind of note should be created.
10655 EXTRA is additional text that will be inserted into the notes buffer."
10656 (let* ((org-log-into-drawer (org-log-into-drawer))
10657 (drawer (cond ((stringp org-log-into-drawer)
10658 org-log-into-drawer)
10659 (org-log-into-drawer "LOGBOOK")
10660 (t nil))))
10661 (save-restriction
10662 (save-excursion
10663 (when findpos
10664 (org-back-to-heading t)
10665 (narrow-to-region (point) (save-excursion
10666 (outline-next-heading) (point)))
10667 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10668 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10669 "[^\r\n]*\\)?"))
10670 (goto-char (match-end 0))
10671 (cond
10672 (drawer
10673 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10674 nil t)
10675 (progn
10676 (goto-char (match-end 0))
10677 (or org-log-states-order-reversed
10678 (and (re-search-forward org-property-end-re nil t)
10679 (goto-char (1- (match-beginning 0))))))
10680 (insert "\n:" drawer ":\n:END:")
10681 (beginning-of-line 0)
10682 (org-indent-line-function)
10683 (beginning-of-line 2)
10684 (org-indent-line-function)
10685 (end-of-line 0)))
10686 ((and org-log-state-notes-insert-after-drawers
10687 (save-excursion
10688 (forward-line) (looking-at org-drawer-regexp)))
10689 (forward-line)
10690 (while (looking-at org-drawer-regexp)
10691 (goto-char (match-end 0))
10692 (re-search-forward org-property-end-re (point-max) t)
10693 (forward-line))
10694 (forward-line -1)))
10695 (unless org-log-states-order-reversed
10696 (and (= (char-after) ?\n) (forward-char 1))
10697 (org-skip-over-state-notes)
10698 (skip-chars-backward " \t\n\r")))
10699 (move-marker org-log-note-marker (point))
10700 (setq org-log-note-purpose purpose
10701 org-log-note-state state
10702 org-log-note-previous-state prev-state
10703 org-log-note-how how
10704 org-log-note-extra extra)
10705 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10707 (defun org-skip-over-state-notes ()
10708 "Skip past the list of State notes in an entry."
10709 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10710 (while (looking-at "[ \t]*- State")
10711 (condition-case nil
10712 (org-next-item)
10713 (error (org-end-of-item)))))
10715 (defun org-add-log-note (&optional purpose)
10716 "Pop up a window for taking a note, and add this note later at point."
10717 (remove-hook 'post-command-hook 'org-add-log-note)
10718 (setq org-log-note-window-configuration (current-window-configuration))
10719 (delete-other-windows)
10720 (move-marker org-log-note-return-to (point))
10721 (switch-to-buffer (marker-buffer org-log-note-marker))
10722 (goto-char org-log-note-marker)
10723 (org-switch-to-buffer-other-window "*Org Note*")
10724 (erase-buffer)
10725 (if (memq org-log-note-how '(time state))
10726 (let (current-prefix-arg) (org-store-log-note))
10727 (let ((org-inhibit-startup t)) (org-mode))
10728 (insert (format "# Insert note for %s.
10729 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10730 (cond
10731 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10732 ((eq org-log-note-purpose 'done) "closed todo item")
10733 ((eq org-log-note-purpose 'state)
10734 (format "state change from \"%s\" to \"%s\""
10735 (or org-log-note-previous-state "")
10736 (or org-log-note-state "")))
10737 ((eq org-log-note-purpose 'reschedule)
10738 "rescheduling")
10739 ((eq org-log-note-purpose 'redeadline)
10740 "changing deadline")
10741 ((eq org-log-note-purpose 'note)
10742 "this entry")
10743 (t (error "This should not happen")))))
10744 (if org-log-note-extra (insert org-log-note-extra))
10745 (org-set-local 'org-finish-function 'org-store-log-note)))
10747 (defvar org-note-abort nil) ; dynamically scoped
10748 (defun org-store-log-note ()
10749 "Finish taking a log note, and insert it to where it belongs."
10750 (let ((txt (buffer-string))
10751 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10752 lines ind)
10753 (kill-buffer (current-buffer))
10754 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10755 (setq txt (replace-match "" t t txt)))
10756 (if (string-match "\\s-+\\'" txt)
10757 (setq txt (replace-match "" t t txt)))
10758 (setq lines (org-split-string txt "\n"))
10759 (when (and note (string-match "\\S-" note))
10760 (setq note
10761 (org-replace-escapes
10762 note
10763 (list (cons "%u" (user-login-name))
10764 (cons "%U" user-full-name)
10765 (cons "%t" (format-time-string
10766 (org-time-stamp-format 'long 'inactive)
10767 (current-time)))
10768 (cons "%s" (if org-log-note-state
10769 (concat "\"" org-log-note-state "\"")
10770 ""))
10771 (cons "%S" (if org-log-note-previous-state
10772 (concat "\"" org-log-note-previous-state "\"")
10773 "\"\"")))))
10774 (if lines (setq note (concat note " \\\\")))
10775 (push note lines))
10776 (when (or current-prefix-arg org-note-abort)
10777 (when org-log-into-drawer
10778 (org-remove-empty-drawer-at
10779 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10780 org-log-note-marker))
10781 (setq lines nil))
10782 (when lines
10783 (with-current-buffer (marker-buffer org-log-note-marker)
10784 (save-excursion
10785 (goto-char org-log-note-marker)
10786 (move-marker org-log-note-marker nil)
10787 (end-of-line 1)
10788 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10789 (insert "- " (pop lines))
10790 (org-indent-line-function)
10791 (beginning-of-line 1)
10792 (looking-at "[ \t]*")
10793 (setq ind (concat (match-string 0) " "))
10794 (end-of-line 1)
10795 (while lines (insert "\n" ind (pop lines)))
10796 (message "Note stored")
10797 (org-back-to-heading t)
10798 (org-cycle-hide-drawers 'children)))))
10799 (set-window-configuration org-log-note-window-configuration)
10800 (with-current-buffer (marker-buffer org-log-note-return-to)
10801 (goto-char org-log-note-return-to))
10802 (move-marker org-log-note-return-to nil)
10803 (and org-log-post-message (message "%s" org-log-post-message)))
10805 (defun org-remove-empty-drawer-at (drawer pos)
10806 "Remove an empty drawer DRAWER at position POS.
10807 POS may also be a marker."
10808 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10809 (save-excursion
10810 (save-restriction
10811 (widen)
10812 (goto-char pos)
10813 (if (org-in-regexp
10814 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10815 (replace-match ""))))))
10817 (defun org-sparse-tree (&optional arg)
10818 "Create a sparse tree, prompt for the details.
10819 This command can create sparse trees. You first need to select the type
10820 of match used to create the tree:
10822 t Show entries with a specific TODO keyword.
10823 m Show entries selected by a tags/property match.
10824 p Enter a property name and its value (both with completion on existing
10825 names/values) and show entries with that property.
10826 / Show entries matching a regular expression (`r' can be used as well)
10827 d Show deadlines due within `org-deadline-warning-days'.
10828 b Show deadlines and scheduled items before a date.
10829 a Show deadlines and scheduled items after a date."
10830 (interactive "P")
10831 (let (ans kwd value)
10832 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10833 (setq ans (read-char-exclusive))
10834 (cond
10835 ((equal ans ?d)
10836 (call-interactively 'org-check-deadlines))
10837 ((equal ans ?b)
10838 (call-interactively 'org-check-before-date))
10839 ((equal ans ?a)
10840 (call-interactively 'org-check-after-date))
10841 ((equal ans ?t)
10842 (org-show-todo-tree '(4)))
10843 ((member ans '(?T ?m))
10844 (call-interactively 'org-match-sparse-tree))
10845 ((member ans '(?p ?P))
10846 (setq kwd (org-icompleting-read "Property: "
10847 (mapcar 'list (org-buffer-property-keys))))
10848 (setq value (org-icompleting-read "Value: "
10849 (mapcar 'list (org-property-values kwd))))
10850 (unless (string-match "\\`{.*}\\'" value)
10851 (setq value (concat "\"" value "\"")))
10852 (org-match-sparse-tree arg (concat kwd "=" value)))
10853 ((member ans '(?r ?R ?/))
10854 (call-interactively 'org-occur))
10855 (t (error "No such sparse tree command \"%c\"" ans)))))
10857 (defvar org-occur-highlights nil
10858 "List of overlays used for occur matches.")
10859 (make-variable-buffer-local 'org-occur-highlights)
10860 (defvar org-occur-parameters nil
10861 "Parameters of the active org-occur calls.
10862 This is a list, each call to org-occur pushes as cons cell,
10863 containing the regular expression and the callback, onto the list.
10864 The list can contain several entries if `org-occur' has been called
10865 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10866 will only contain one set of parameters. When the highlights are
10867 removed (for example with `C-c C-c', or with the next edit (depending
10868 on `org-remove-highlights-with-change'), this variable is emptied
10869 as well.")
10870 (make-variable-buffer-local 'org-occur-parameters)
10872 (defun org-occur (regexp &optional keep-previous callback)
10873 "Make a compact tree which shows all matches of REGEXP.
10874 The tree will show the lines where the regexp matches, and all higher
10875 headlines above the match. It will also show the heading after the match,
10876 to make sure editing the matching entry is easy.
10877 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10878 call to `org-occur' will be kept, to allow stacking of calls to this
10879 command.
10880 If CALLBACK is non-nil, it is a function which is called to confirm
10881 that the match should indeed be shown."
10882 (interactive "sRegexp: \nP")
10883 (when (equal regexp "")
10884 (error "Regexp cannot be empty"))
10885 (unless keep-previous
10886 (org-remove-occur-highlights nil nil t))
10887 (push (cons regexp callback) org-occur-parameters)
10888 (let ((cnt 0))
10889 (save-excursion
10890 (goto-char (point-min))
10891 (if (or (not keep-previous) ; do not want to keep
10892 (not org-occur-highlights)) ; no previous matches
10893 ;; hide everything
10894 (org-overview))
10895 (while (re-search-forward regexp nil t)
10896 (when (or (not callback)
10897 (save-match-data (funcall callback)))
10898 (setq cnt (1+ cnt))
10899 (when org-highlight-sparse-tree-matches
10900 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10901 (org-show-context 'occur-tree))))
10902 (when org-remove-highlights-with-change
10903 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10904 nil 'local))
10905 (unless org-sparse-tree-open-archived-trees
10906 (org-hide-archived-subtrees (point-min) (point-max)))
10907 (run-hooks 'org-occur-hook)
10908 (if (interactive-p)
10909 (message "%d match(es) for regexp %s" cnt regexp))
10910 cnt))
10912 (defun org-show-context (&optional key)
10913 "Make sure point and context and visible.
10914 How much context is shown depends upon the variables
10915 `org-show-hierarchy-above', `org-show-following-heading'. and
10916 `org-show-siblings'."
10917 (let ((heading-p (org-on-heading-p t))
10918 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10919 (following-p (org-get-alist-option org-show-following-heading key))
10920 (entry-p (org-get-alist-option org-show-entry-below key))
10921 (siblings-p (org-get-alist-option org-show-siblings key)))
10922 (catch 'exit
10923 ;; Show heading or entry text
10924 (if (and heading-p (not entry-p))
10925 (org-flag-heading nil) ; only show the heading
10926 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10927 (org-show-hidden-entry))) ; show entire entry
10928 (when following-p
10929 ;; Show next sibling, or heading below text
10930 (save-excursion
10931 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10932 (org-flag-heading nil))))
10933 (when siblings-p (org-show-siblings))
10934 (when hierarchy-p
10935 ;; show all higher headings, possibly with siblings
10936 (save-excursion
10937 (while (and (condition-case nil
10938 (progn (org-up-heading-all 1) t)
10939 (error nil))
10940 (not (bobp)))
10941 (org-flag-heading nil)
10942 (when siblings-p (org-show-siblings))))))))
10944 (defun org-reveal (&optional siblings)
10945 "Show current entry, hierarchy above it, and the following headline.
10946 This can be used to show a consistent set of context around locations
10947 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10948 not t for the search context.
10950 With optional argument SIBLINGS, on each level of the hierarchy all
10951 siblings are shown. This repairs the tree structure to what it would
10952 look like when opened with hierarchical calls to `org-cycle'."
10953 (interactive "P")
10954 (let ((org-show-hierarchy-above t)
10955 (org-show-following-heading t)
10956 (org-show-siblings (if siblings t org-show-siblings)))
10957 (org-show-context nil)))
10959 (defun org-highlight-new-match (beg end)
10960 "Highlight from BEG to END and mark the highlight is an occur headline."
10961 (let ((ov (org-make-overlay beg end)))
10962 (org-overlay-put ov 'face 'secondary-selection)
10963 (push ov org-occur-highlights)))
10965 (defun org-remove-occur-highlights (&optional beg end noremove)
10966 "Remove the occur highlights from the buffer.
10967 BEG and END are ignored. If NOREMOVE is nil, remove this function
10968 from the `before-change-functions' in the current buffer."
10969 (interactive)
10970 (unless org-inhibit-highlight-removal
10971 (mapc 'org-delete-overlay org-occur-highlights)
10972 (setq org-occur-highlights nil)
10973 (setq org-occur-parameters nil)
10974 (unless noremove
10975 (remove-hook 'before-change-functions
10976 'org-remove-occur-highlights 'local))))
10978 ;;;; Priorities
10980 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10981 "Regular expression matching the priority indicator.")
10983 (defvar org-remove-priority-next-time nil)
10985 (defun org-priority-up ()
10986 "Increase the priority of the current item."
10987 (interactive)
10988 (org-priority 'up))
10990 (defun org-priority-down ()
10991 "Decrease the priority of the current item."
10992 (interactive)
10993 (org-priority 'down))
10995 (defun org-priority (&optional action)
10996 "Change the priority of an item by ARG.
10997 ACTION can be `set', `up', `down', or a character."
10998 (interactive)
10999 (unless org-enable-priority-commands
11000 (error "Priority commands are disabled"))
11001 (setq action (or action 'set))
11002 (let (current new news have remove)
11003 (save-excursion
11004 (org-back-to-heading t)
11005 (if (looking-at org-priority-regexp)
11006 (setq current (string-to-char (match-string 2))
11007 have t)
11008 (setq current org-default-priority))
11009 (cond
11010 ((eq action 'remove)
11011 (setq remove t new ?\ ))
11012 ((or (eq action 'set)
11013 (if (featurep 'xemacs) (characterp action) (integerp action)))
11014 (if (not (eq action 'set))
11015 (setq new action)
11016 (message "Priority %c-%c, SPC to remove: "
11017 org-highest-priority org-lowest-priority)
11018 (setq new (read-char-exclusive)))
11019 (if (and (= (upcase org-highest-priority) org-highest-priority)
11020 (= (upcase org-lowest-priority) org-lowest-priority))
11021 (setq new (upcase new)))
11022 (cond ((equal new ?\ ) (setq remove t))
11023 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11024 (error "Priority must be between `%c' and `%c'"
11025 org-highest-priority org-lowest-priority))))
11026 ((eq action 'up)
11027 (if (and (not have) (eq last-command this-command))
11028 (setq new org-lowest-priority)
11029 (setq new (if (and org-priority-start-cycle-with-default (not have))
11030 org-default-priority (1- current)))))
11031 ((eq action 'down)
11032 (if (and (not have) (eq last-command this-command))
11033 (setq new org-highest-priority)
11034 (setq new (if (and org-priority-start-cycle-with-default (not have))
11035 org-default-priority (1+ current)))))
11036 (t (error "Invalid action")))
11037 (if (or (< (upcase new) org-highest-priority)
11038 (> (upcase new) org-lowest-priority))
11039 (setq remove t))
11040 (setq news (format "%c" new))
11041 (if have
11042 (if remove
11043 (replace-match "" t t nil 1)
11044 (replace-match news t t nil 2))
11045 (if remove
11046 (error "No priority cookie found in line")
11047 (let ((case-fold-search nil))
11048 (looking-at org-todo-line-regexp))
11049 (if (match-end 2)
11050 (progn
11051 (goto-char (match-end 2))
11052 (insert " [#" news "]"))
11053 (goto-char (match-beginning 3))
11054 (insert "[#" news "] "))))
11055 (org-preserve-lc (org-set-tags nil 'align)))
11056 (if remove
11057 (message "Priority removed")
11058 (message "Priority of current item set to %s" news))))
11060 (defun org-get-priority (s)
11061 "Find priority cookie and return priority."
11062 (save-match-data
11063 (if (not (string-match org-priority-regexp s))
11064 (* 1000 (- org-lowest-priority org-default-priority))
11065 (* 1000 (- org-lowest-priority
11066 (string-to-char (match-string 2 s)))))))
11068 ;;;; Tags
11070 (defvar org-agenda-archives-mode)
11071 (defvar org-map-continue-from nil
11072 "Position from where mapping should continue.
11073 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11075 (defvar org-scanner-tags nil
11076 "The current tag list while the tags scanner is running.")
11077 (defvar org-trust-scanner-tags nil
11078 "Should `org-get-tags-at' use the tags fro the scanner.
11079 This is for internal dynamical scoping only.
11080 When this is non-nil, the function `org-get-tags-at' will return the value
11081 of `org-scanner-tags' instead of building the list by itself. This
11082 can lead to large speed-ups when the tags scanner is used in a file with
11083 many entries, and when the list of tags is retrieved, for example to
11084 obtain a list of properties. Building the tags list for each entry in such
11085 a file becomes an N^2 operation - but with this variable set, it scales
11086 as N.")
11088 (defun org-scan-tags (action matcher &optional todo-only)
11089 "Scan headline tags with inheritance and produce output ACTION.
11091 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11092 or `agenda' to produce an entry list for an agenda view. It can also be
11093 a Lisp form or a function that should be called at each matched headline, in
11094 this case the return value is a list of all return values from these calls.
11096 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11097 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11098 only lines with a TODO keyword are included in the output."
11099 (require 'org-agenda)
11100 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11101 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11102 (org-re
11103 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11104 (props (list 'face 'default
11105 'done-face 'org-agenda-done
11106 'undone-face 'default
11107 'mouse-face 'highlight
11108 'org-not-done-regexp org-not-done-regexp
11109 'org-todo-regexp org-todo-regexp
11110 'help-echo
11111 (format "mouse-2 or RET jump to org file %s"
11112 (abbreviate-file-name
11113 (or (buffer-file-name (buffer-base-buffer))
11114 (buffer-name (buffer-base-buffer)))))))
11115 (case-fold-search nil)
11116 (org-map-continue-from nil)
11117 lspos tags tags-list
11118 (tags-alist (list (cons 0 org-file-tags)))
11119 (llast 0) rtn rtn1 level category i txt
11120 todo marker entry priority)
11121 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11122 (setq action (list 'lambda nil action)))
11123 (save-excursion
11124 (goto-char (point-min))
11125 (when (eq action 'sparse-tree)
11126 (org-overview)
11127 (org-remove-occur-highlights))
11128 (while (re-search-forward re nil t)
11129 (catch :skip
11130 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11131 tags (if (match-end 4) (org-match-string-no-properties 4)))
11132 (goto-char (setq lspos (match-beginning 0)))
11133 (setq level (org-reduced-level (funcall outline-level))
11134 category (org-get-category))
11135 (setq i llast llast level)
11136 ;; remove tag lists from same and sublevels
11137 (while (>= i level)
11138 (when (setq entry (assoc i tags-alist))
11139 (setq tags-alist (delete entry tags-alist)))
11140 (setq i (1- i)))
11141 ;; add the next tags
11142 (when tags
11143 (setq tags (org-split-string tags ":")
11144 tags-alist
11145 (cons (cons level tags) tags-alist)))
11146 ;; compile tags for current headline
11147 (setq tags-list
11148 (if org-use-tag-inheritance
11149 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11150 tags)
11151 org-scanner-tags tags-list)
11152 (when org-use-tag-inheritance
11153 (setcdr (car tags-alist)
11154 (mapcar (lambda (x)
11155 (setq x (copy-sequence x))
11156 (org-add-prop-inherited x))
11157 (cdar tags-alist))))
11158 (when (and tags org-use-tag-inheritance
11159 (or (not (eq t org-use-tag-inheritance))
11160 org-tags-exclude-from-inheritance))
11161 ;; selective inheritance, remove uninherited ones
11162 (setcdr (car tags-alist)
11163 (org-remove-uniherited-tags (cdar tags-alist))))
11164 (when (and (or (not todo-only)
11165 (and (member todo org-not-done-keywords)
11166 (or (not org-agenda-tags-todo-honor-ignore-options)
11167 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11168 (let ((case-fold-search t)) (eval matcher))
11170 (not (member org-archive-tag tags-list))
11171 ;; we have an archive tag, should we use this anyway?
11172 (or (not org-agenda-skip-archived-trees)
11173 (and (eq action 'agenda) org-agenda-archives-mode))))
11174 (unless (eq action 'sparse-tree) (org-agenda-skip))
11176 ;; select this headline
11178 (cond
11179 ((eq action 'sparse-tree)
11180 (and org-highlight-sparse-tree-matches
11181 (org-get-heading) (match-end 0)
11182 (org-highlight-new-match
11183 (match-beginning 0) (match-beginning 1)))
11184 (org-show-context 'tags-tree))
11185 ((eq action 'agenda)
11186 (setq txt (org-format-agenda-item
11188 (concat
11189 (if (eq org-tags-match-list-sublevels 'indented)
11190 (make-string (1- level) ?.) "")
11191 (org-get-heading))
11192 category
11193 tags-list
11195 priority (org-get-priority txt))
11196 (goto-char lspos)
11197 (setq marker (org-agenda-new-marker))
11198 (org-add-props txt props
11199 'org-marker marker 'org-hd-marker marker 'org-category category
11200 'todo-state todo
11201 'priority priority 'type "tagsmatch")
11202 (push txt rtn))
11203 ((functionp action)
11204 (setq org-map-continue-from nil)
11205 (save-excursion
11206 (setq rtn1 (funcall action))
11207 (push rtn1 rtn)))
11208 (t (error "Invalid action")))
11210 ;; if we are to skip sublevels, jump to end of subtree
11211 (unless org-tags-match-list-sublevels
11212 (org-end-of-subtree t)
11213 (backward-char 1))))
11214 ;; Get the correct position from where to continue
11215 (if org-map-continue-from
11216 (goto-char org-map-continue-from)
11217 (and (= (point) lspos) (end-of-line 1)))))
11218 (when (and (eq action 'sparse-tree)
11219 (not org-sparse-tree-open-archived-trees))
11220 (org-hide-archived-subtrees (point-min) (point-max)))
11221 (nreverse rtn)))
11223 (defun org-remove-uniherited-tags (tags)
11224 "Remove all tags that are not inherited from the list TAGS."
11225 (cond
11226 ((eq org-use-tag-inheritance t)
11227 (if org-tags-exclude-from-inheritance
11228 (org-delete-all org-tags-exclude-from-inheritance tags)
11229 tags))
11230 ((not org-use-tag-inheritance) nil)
11231 ((stringp org-use-tag-inheritance)
11232 (delq nil (mapcar
11233 (lambda (x)
11234 (if (and (string-match org-use-tag-inheritance x)
11235 (not (member x org-tags-exclude-from-inheritance)))
11236 x nil))
11237 tags)))
11238 ((listp org-use-tag-inheritance)
11239 (delq nil (mapcar
11240 (lambda (x)
11241 (if (member x org-use-tag-inheritance) x nil))
11242 tags)))))
11244 (defvar todo-only) ;; dynamically scoped
11246 (defun org-match-sparse-tree (&optional todo-only match)
11247 "Create a sparse tree according to tags string MATCH.
11248 MATCH can contain positive and negative selection of tags, like
11249 \"+WORK+URGENT-WITHBOSS\".
11250 If optional argument TODO-ONLY is non-nil, only select lines that are
11251 also TODO lines."
11252 (interactive "P")
11253 (org-prepare-agenda-buffers (list (current-buffer)))
11254 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11256 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11258 (defvar org-cached-props nil)
11259 (defun org-cached-entry-get (pom property)
11260 (if (or (eq t org-use-property-inheritance)
11261 (and (stringp org-use-property-inheritance)
11262 (string-match org-use-property-inheritance property))
11263 (and (listp org-use-property-inheritance)
11264 (member property org-use-property-inheritance)))
11265 ;; Caching is not possible, check it directly
11266 (org-entry-get pom property 'inherit)
11267 ;; Get all properties, so that we can do complicated checks easily
11268 (cdr (assoc property (or org-cached-props
11269 (setq org-cached-props
11270 (org-entry-properties pom)))))))
11272 (defun org-global-tags-completion-table (&optional files)
11273 "Return the list of all tags in all agenda buffer/files."
11274 (save-excursion
11275 (org-uniquify
11276 (delq nil
11277 (apply 'append
11278 (mapcar
11279 (lambda (file)
11280 (set-buffer (find-file-noselect file))
11281 (append (org-get-buffer-tags)
11282 (mapcar (lambda (x) (if (stringp (car-safe x))
11283 (list (car-safe x)) nil))
11284 org-tag-alist)))
11285 (if (and files (car files))
11286 files
11287 (org-agenda-files))))))))
11289 (defun org-make-tags-matcher (match)
11290 "Create the TAGS//TODO matcher form for the selection string MATCH."
11291 ;; todo-only is scoped dynamically into this function, and the function
11292 ;; may change it if the matcher asks for it.
11293 (unless match
11294 ;; Get a new match request, with completion
11295 (let ((org-last-tags-completion-table
11296 (org-global-tags-completion-table)))
11297 (setq match (org-completing-read-no-i
11298 "Match: " 'org-tags-completion-function nil nil nil
11299 'org-tags-history))))
11301 ;; Parse the string and create a lisp form
11302 (let ((match0 match)
11303 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11304 minus tag mm
11305 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11306 orterms term orlist re-p str-p level-p level-op time-p
11307 prop-p pn pv po cat-p gv rest)
11308 (if (string-match "/+" match)
11309 ;; match contains also a todo-matching request
11310 (progn
11311 (setq tagsmatch (substring match 0 (match-beginning 0))
11312 todomatch (substring match (match-end 0)))
11313 (if (string-match "^!" todomatch)
11314 (setq todo-only t todomatch (substring todomatch 1)))
11315 (if (string-match "^\\s-*$" todomatch)
11316 (setq todomatch nil)))
11317 ;; only matching tags
11318 (setq tagsmatch match todomatch nil))
11320 ;; Make the tags matcher
11321 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11322 (setq tagsmatcher t)
11323 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11324 (while (setq term (pop orterms))
11325 (while (and (equal (substring term -1) "\\") orterms)
11326 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11327 (while (string-match re term)
11328 (setq rest (substring term (match-end 0))
11329 minus (and (match-end 1)
11330 (equal (match-string 1 term) "-"))
11331 tag (match-string 2 term)
11332 re-p (equal (string-to-char tag) ?{)
11333 level-p (match-end 4)
11334 prop-p (match-end 5)
11335 mm (cond
11336 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11337 (level-p
11338 (setq level-op (org-op-to-function (match-string 3 term)))
11339 `(,level-op level ,(string-to-number
11340 (match-string 4 term))))
11341 (prop-p
11342 (setq pn (match-string 5 term)
11343 po (match-string 6 term)
11344 pv (match-string 7 term)
11345 cat-p (equal pn "CATEGORY")
11346 re-p (equal (string-to-char pv) ?{)
11347 str-p (equal (string-to-char pv) ?\")
11348 time-p (save-match-data
11349 (string-match "^\"[[<].*[]>]\"$" pv))
11350 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11351 (if time-p (setq pv (org-matcher-time pv)))
11352 (setq po (org-op-to-function po (if time-p 'time str-p)))
11353 (cond
11354 ((equal pn "CATEGORY")
11355 (setq gv '(get-text-property (point) 'org-category)))
11356 ((equal pn "TODO")
11357 (setq gv 'todo))
11359 (setq gv `(org-cached-entry-get nil ,pn))))
11360 (if re-p
11361 (if (eq po 'org<>)
11362 `(not (string-match ,pv (or ,gv "")))
11363 `(string-match ,pv (or ,gv "")))
11364 (if str-p
11365 `(,po (or ,gv "") ,pv)
11366 `(,po (string-to-number (or ,gv ""))
11367 ,(string-to-number pv) ))))
11368 (t `(member ,tag tags-list)))
11369 mm (if minus (list 'not mm) mm)
11370 term rest)
11371 (push mm tagsmatcher))
11372 (push (if (> (length tagsmatcher) 1)
11373 (cons 'and tagsmatcher)
11374 (car tagsmatcher))
11375 orlist)
11376 (setq tagsmatcher nil))
11377 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11378 (setq tagsmatcher
11379 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11380 ;; Make the todo matcher
11381 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11382 (setq todomatcher t)
11383 (setq orterms (org-split-string todomatch "|") orlist nil)
11384 (while (setq term (pop orterms))
11385 (while (string-match re term)
11386 (setq minus (and (match-end 1)
11387 (equal (match-string 1 term) "-"))
11388 kwd (match-string 2 term)
11389 re-p (equal (string-to-char kwd) ?{)
11390 term (substring term (match-end 0))
11391 mm (if re-p
11392 `(string-match ,(substring kwd 1 -1) todo)
11393 (list 'equal 'todo kwd))
11394 mm (if minus (list 'not mm) mm))
11395 (push mm todomatcher))
11396 (push (if (> (length todomatcher) 1)
11397 (cons 'and todomatcher)
11398 (car todomatcher))
11399 orlist)
11400 (setq todomatcher nil))
11401 (setq todomatcher (if (> (length orlist) 1)
11402 (cons 'or orlist) (car orlist))))
11404 ;; Return the string and lisp forms of the matcher
11405 (setq matcher (if todomatcher
11406 (list 'and tagsmatcher todomatcher)
11407 tagsmatcher))
11408 (cons match0 matcher)))
11410 (defun org-op-to-function (op &optional stringp)
11411 "Turn an operator into the appropriate function."
11412 (setq op
11413 (cond
11414 ((equal op "<" ) '(< string< org-time<))
11415 ((equal op ">" ) '(> org-string> org-time>))
11416 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11417 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11418 ((member op '("=" "==")) '(= string= org-time=))
11419 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11420 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11422 (defun org<> (a b) (not (= a b)))
11423 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11424 (defun org-string>= (a b) (not (string< a b)))
11425 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11426 (defun org-string<> (a b) (not (string= a b)))
11427 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11428 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11429 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11430 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11431 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11432 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11433 (defun org-2ft (s)
11434 "Convert S to a floating point time.
11435 If S is already a number, just return it. If it is a string, parse
11436 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11437 (cond
11438 ((numberp s) s)
11439 ((stringp s)
11440 (condition-case nil
11441 (float-time (apply 'encode-time (org-parse-time-string s)))
11442 (error 0.)))
11443 (t 0.)))
11445 (defun org-time-today ()
11446 "Time in seconds today at 0:00.
11447 Returns the float number of seconds since the beginning of the
11448 epoch to the beginning of today (00:00)."
11449 (float-time (apply 'encode-time
11450 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11452 (defun org-matcher-time (s)
11453 "Interpret a time comparison value."
11454 (save-match-data
11455 (cond
11456 ((string= s "<now>") (float-time))
11457 ((string= s "<today>") (org-time-today))
11458 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11459 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11460 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11461 (+ (org-time-today)
11462 (* (string-to-number (match-string 1 s))
11463 (cdr (assoc (match-string 2 s)
11464 '(("d" . 86400.0) ("w" . 604800.0)
11465 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11466 (t (org-2ft s)))))
11468 (defun org-match-any-p (re list)
11469 "Does re match any element of list?"
11470 (setq list (mapcar (lambda (x) (string-match re x)) list))
11471 (delq nil list))
11473 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11474 (defvar org-tags-overlay (org-make-overlay 1 1))
11475 (org-detach-overlay org-tags-overlay)
11477 (defun org-get-local-tags-at (&optional pos)
11478 "Get a list of tags defined in the current headline."
11479 (org-get-tags-at pos 'local))
11481 (defun org-get-local-tags ()
11482 "Get a list of tags defined in the current headline."
11483 (org-get-tags-at nil 'local))
11485 (defun org-get-tags-at (&optional pos local)
11486 "Get a list of all headline tags applicable at POS.
11487 POS defaults to point. If tags are inherited, the list contains
11488 the targets in the same sequence as the headlines appear, i.e.
11489 the tags of the current headline come last.
11490 When LOCAL is non-nil, only return tags from the current headline,
11491 ignore inherited ones."
11492 (interactive)
11493 (if (and org-trust-scanner-tags
11494 (or (not pos) (equal pos (point)))
11495 (not local))
11496 org-scanner-tags
11497 (let (tags ltags lastpos parent)
11498 (save-excursion
11499 (save-restriction
11500 (widen)
11501 (goto-char (or pos (point)))
11502 (save-match-data
11503 (catch 'done
11504 (condition-case nil
11505 (progn
11506 (org-back-to-heading t)
11507 (while (not (equal lastpos (point)))
11508 (setq lastpos (point))
11509 (when (looking-at
11510 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11511 (setq ltags (org-split-string
11512 (org-match-string-no-properties 1) ":"))
11513 (when parent
11514 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11515 (setq tags (append
11516 (if parent
11517 (org-remove-uniherited-tags ltags)
11518 ltags)
11519 tags)))
11520 (or org-use-tag-inheritance (throw 'done t))
11521 (if local (throw 'done t))
11522 (or (org-up-heading-safe) (error nil))
11523 (setq parent t)))
11524 (error nil)))))
11525 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11527 (defun org-add-prop-inherited (s)
11528 (add-text-properties 0 (length s) '(inherited t) s)
11531 (defun org-toggle-tag (tag &optional onoff)
11532 "Toggle the tag TAG for the current line.
11533 If ONOFF is `on' or `off', don't toggle but set to this state."
11534 (let (res current)
11535 (save-excursion
11536 (org-back-to-heading t)
11537 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11538 (point-at-eol) t)
11539 (progn
11540 (setq current (match-string 1))
11541 (replace-match ""))
11542 (setq current ""))
11543 (setq current (nreverse (org-split-string current ":")))
11544 (cond
11545 ((eq onoff 'on)
11546 (setq res t)
11547 (or (member tag current) (push tag current)))
11548 ((eq onoff 'off)
11549 (or (not (member tag current)) (setq current (delete tag current))))
11550 (t (if (member tag current)
11551 (setq current (delete tag current))
11552 (setq res t)
11553 (push tag current))))
11554 (end-of-line 1)
11555 (if current
11556 (progn
11557 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11558 (org-set-tags nil t))
11559 (delete-horizontal-space))
11560 (run-hooks 'org-after-tags-change-hook))
11561 res))
11563 (defun org-align-tags-here (to-col)
11564 ;; Assumes that this is a headline
11565 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11566 (beginning-of-line 1)
11567 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11568 (< pos (match-beginning 2)))
11569 (progn
11570 (setq tags-l (- (match-end 2) (match-beginning 2)))
11571 (goto-char (match-beginning 1))
11572 (insert " ")
11573 (delete-region (point) (1+ (match-beginning 2)))
11574 (setq ncol (max (1+ (current-column))
11575 (1+ col)
11576 (if (> to-col 0)
11577 to-col
11578 (- (abs to-col) tags-l))))
11579 (setq p (point))
11580 (insert (make-string (- ncol (current-column)) ?\ ))
11581 (setq ncol (current-column))
11582 (when indent-tabs-mode (tabify p (point-at-eol)))
11583 (org-move-to-column (min ncol col) t))
11584 (goto-char pos))))
11586 (defun org-set-tags-command (&optional arg just-align)
11587 "Call the set-tags command for the current entry."
11588 (interactive "P")
11589 (if (org-on-heading-p)
11590 (org-set-tags arg just-align)
11591 (save-excursion
11592 (org-back-to-heading t)
11593 (org-set-tags arg just-align))))
11595 (defun org-set-tags-to (data)
11596 "Set the tags of the current entry to DATA, replacing the current tags.
11597 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11598 If DATA is nil or the empty string, any tags will be removed."
11599 (interactive "sTags: ")
11600 (setq data
11601 (cond
11602 ((eq data nil) "")
11603 ((equal data "") "")
11604 ((stringp data)
11605 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11606 ":"))
11607 ((listp data)
11608 (concat ":" (mapconcat 'identity data ":") ":"))
11609 (t nil)))
11610 (when data
11611 (save-excursion
11612 (org-back-to-heading t)
11613 (when (looking-at org-complex-heading-regexp)
11614 (if (match-end 5)
11615 (progn
11616 (goto-char (match-beginning 5))
11617 (insert data)
11618 (delete-region (point) (point-at-eol))
11619 (org-set-tags nil 'align))
11620 (goto-char (point-at-eol))
11621 (insert " " data)
11622 (org-set-tags nil 'align)))
11623 (beginning-of-line 1)
11624 (if (looking-at ".*?\\([ \t]+\\)$")
11625 (delete-region (match-beginning 1) (match-end 1))))))
11627 (defun org-set-tags (&optional arg just-align)
11628 "Set the tags for the current headline.
11629 With prefix ARG, realign all tags in headings in the current buffer."
11630 (interactive "P")
11631 (let* ((re (concat "^" outline-regexp))
11632 (current (org-get-tags-string))
11633 (col (current-column))
11634 (org-setting-tags t)
11635 table current-tags inherited-tags ; computed below when needed
11636 tags p0 c0 c1 rpl)
11637 (if arg
11638 (save-excursion
11639 (goto-char (point-min))
11640 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11641 (while (re-search-forward re nil t)
11642 (org-set-tags nil t)
11643 (end-of-line 1)))
11644 (message "All tags realigned to column %d" org-tags-column))
11645 (if just-align
11646 (setq tags current)
11647 ;; Get a new set of tags from the user
11648 (save-excursion
11649 (setq table (append org-tag-persistent-alist
11650 (or org-tag-alist (org-get-buffer-tags)))
11651 org-last-tags-completion-table table
11652 current-tags (org-split-string current ":")
11653 inherited-tags (nreverse
11654 (nthcdr (length current-tags)
11655 (nreverse (org-get-tags-at))))
11656 tags
11657 (if (or (eq t org-use-fast-tag-selection)
11658 (and org-use-fast-tag-selection
11659 (delq nil (mapcar 'cdr table))))
11660 (org-fast-tag-selection
11661 current-tags inherited-tags table
11662 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11663 (let ((org-add-colon-after-tag-completion t))
11664 (org-trim
11665 (org-without-partial-completion
11666 (org-icompleting-read "Tags: " 'org-tags-completion-function
11667 nil nil current 'org-tags-history)))))))
11668 (while (string-match "[-+&]+" tags)
11669 ;; No boolean logic, just a list
11670 (setq tags (replace-match ":" t t tags))))
11672 (if org-tags-sort-function
11673 (setq tags (mapconcat 'identity
11674 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11675 org-tags-sort-function) ":")))
11677 (if (string-match "\\`[\t ]*\\'" tags)
11678 (setq tags "")
11679 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11680 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11682 ;; Insert new tags at the correct column
11683 (beginning-of-line 1)
11684 (cond
11685 ((and (equal current "") (equal tags "")))
11686 ((re-search-forward
11687 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11688 (point-at-eol) t)
11689 (if (equal tags "")
11690 (setq rpl "")
11691 (goto-char (match-beginning 0))
11692 (setq c0 (current-column) p0 (point)
11693 c1 (max (1+ c0) (if (> org-tags-column 0)
11694 org-tags-column
11695 (- (- org-tags-column) (length tags))))
11696 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11697 (replace-match rpl t t)
11698 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11699 tags)
11700 (t (error "Tags alignment failed")))
11701 (org-move-to-column col)
11702 (unless just-align
11703 (run-hooks 'org-after-tags-change-hook)))))
11705 (defun org-change-tag-in-region (beg end tag off)
11706 "Add or remove TAG for each entry in the region.
11707 This works in the agenda, and also in an org-mode buffer."
11708 (interactive
11709 (list (region-beginning) (region-end)
11710 (let ((org-last-tags-completion-table
11711 (if (org-mode-p)
11712 (org-get-buffer-tags)
11713 (org-global-tags-completion-table))))
11714 (org-icompleting-read
11715 "Tag: " 'org-tags-completion-function nil nil nil
11716 'org-tags-history))
11717 (progn
11718 (message "[s]et or [r]emove? ")
11719 (equal (read-char-exclusive) ?r))))
11720 (if (fboundp 'deactivate-mark) (deactivate-mark))
11721 (let ((agendap (equal major-mode 'org-agenda-mode))
11722 l1 l2 m buf pos newhead (cnt 0))
11723 (goto-char end)
11724 (setq l2 (1- (org-current-line)))
11725 (goto-char beg)
11726 (setq l1 (org-current-line))
11727 (loop for l from l1 to l2 do
11728 (org-goto-line l)
11729 (setq m (get-text-property (point) 'org-hd-marker))
11730 (when (or (and (org-mode-p) (org-on-heading-p))
11731 (and agendap m))
11732 (setq buf (if agendap (marker-buffer m) (current-buffer))
11733 pos (if agendap m (point)))
11734 (with-current-buffer buf
11735 (save-excursion
11736 (save-restriction
11737 (goto-char pos)
11738 (setq cnt (1+ cnt))
11739 (org-toggle-tag tag (if off 'off 'on))
11740 (setq newhead (org-get-heading)))))
11741 (and agendap (org-agenda-change-all-lines newhead m))))
11742 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11744 (defun org-tags-completion-function (string predicate &optional flag)
11745 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11746 (confirm (lambda (x) (stringp (car x)))))
11747 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11748 (setq s1 (match-string 1 string)
11749 s2 (match-string 2 string))
11750 (setq s1 "" s2 string))
11751 (cond
11752 ((eq flag nil)
11753 ;; try completion
11754 (setq rtn (try-completion s2 ctable confirm))
11755 (if (stringp rtn)
11756 (setq rtn
11757 (concat s1 s2 (substring rtn (length s2))
11758 (if (and org-add-colon-after-tag-completion
11759 (assoc rtn ctable))
11760 ":" ""))))
11761 rtn)
11762 ((eq flag t)
11763 ;; all-completions
11764 (all-completions s2 ctable confirm)
11766 ((eq flag 'lambda)
11767 ;; exact match?
11768 (assoc s2 ctable)))
11771 (defun org-fast-tag-insert (kwd tags face &optional end)
11772 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11773 (insert (format "%-12s" (concat kwd ":"))
11774 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11775 (or end "")))
11777 (defun org-fast-tag-show-exit (flag)
11778 (save-excursion
11779 (org-goto-line 3)
11780 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11781 (replace-match ""))
11782 (when flag
11783 (end-of-line 1)
11784 (org-move-to-column (- (window-width) 19) t)
11785 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11787 (defun org-set-current-tags-overlay (current prefix)
11788 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11789 (if (featurep 'xemacs)
11790 (org-overlay-display org-tags-overlay (concat prefix s)
11791 'secondary-selection)
11792 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11793 (org-overlay-display org-tags-overlay (concat prefix s)))))
11795 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11796 "Fast tag selection with single keys.
11797 CURRENT is the current list of tags in the headline, INHERITED is the
11798 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11799 possibly with grouping information. TODO-TABLE is a similar table with
11800 TODO keywords, should these have keys assigned to them.
11801 If the keys are nil, a-z are automatically assigned.
11802 Returns the new tags string, or nil to not change the current settings."
11803 (let* ((fulltable (append table todo-table))
11804 (maxlen (apply 'max (mapcar
11805 (lambda (x)
11806 (if (stringp (car x)) (string-width (car x)) 0))
11807 fulltable)))
11808 (buf (current-buffer))
11809 (expert (eq org-fast-tag-selection-single-key 'expert))
11810 (buffer-tags nil)
11811 (fwidth (+ maxlen 3 1 3))
11812 (ncol (/ (- (window-width) 4) fwidth))
11813 (i-face 'org-done)
11814 (c-face 'org-todo)
11815 tg cnt e c char c1 c2 ntable tbl rtn
11816 ov-start ov-end ov-prefix
11817 (exit-after-next org-fast-tag-selection-single-key)
11818 (done-keywords org-done-keywords)
11819 groups ingroup)
11820 (save-excursion
11821 (beginning-of-line 1)
11822 (if (looking-at
11823 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11824 (setq ov-start (match-beginning 1)
11825 ov-end (match-end 1)
11826 ov-prefix "")
11827 (setq ov-start (1- (point-at-eol))
11828 ov-end (1+ ov-start))
11829 (skip-chars-forward "^\n\r")
11830 (setq ov-prefix
11831 (concat
11832 (buffer-substring (1- (point)) (point))
11833 (if (> (current-column) org-tags-column)
11835 (make-string (- org-tags-column (current-column)) ?\ ))))))
11836 (org-move-overlay org-tags-overlay ov-start ov-end)
11837 (save-window-excursion
11838 (if expert
11839 (set-buffer (get-buffer-create " *Org tags*"))
11840 (delete-other-windows)
11841 (split-window-vertically)
11842 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11843 (erase-buffer)
11844 (org-set-local 'org-done-keywords done-keywords)
11845 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11846 (org-fast-tag-insert "Current" current c-face "\n\n")
11847 (org-fast-tag-show-exit exit-after-next)
11848 (org-set-current-tags-overlay current ov-prefix)
11849 (setq tbl fulltable char ?a cnt 0)
11850 (while (setq e (pop tbl))
11851 (cond
11852 ((equal (car e) :startgroup)
11853 (push '() groups) (setq ingroup t)
11854 (when (not (= cnt 0))
11855 (setq cnt 0)
11856 (insert "\n"))
11857 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11858 ((equal (car e) :endgroup)
11859 (setq ingroup nil cnt 0)
11860 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11861 ((equal e '(:newline))
11862 (when (not (= cnt 0))
11863 (setq cnt 0)
11864 (insert "\n")
11865 (setq e (car tbl))
11866 (while (equal (car tbl) '(:newline))
11867 (insert "\n")
11868 (setq tbl (cdr tbl)))))
11870 (setq tg (copy-sequence (car e)) c2 nil)
11871 (if (cdr e)
11872 (setq c (cdr e))
11873 ;; automatically assign a character.
11874 (setq c1 (string-to-char
11875 (downcase (substring
11876 tg (if (= (string-to-char tg) ?@) 1 0)))))
11877 (if (or (rassoc c1 ntable) (rassoc c1 table))
11878 (while (or (rassoc char ntable) (rassoc char table))
11879 (setq char (1+ char)))
11880 (setq c2 c1))
11881 (setq c (or c2 char)))
11882 (if ingroup (push tg (car groups)))
11883 (setq tg (org-add-props tg nil 'face
11884 (cond
11885 ((not (assoc tg table))
11886 (org-get-todo-face tg))
11887 ((member tg current) c-face)
11888 ((member tg inherited) i-face)
11889 (t nil))))
11890 (if (and (= cnt 0) (not ingroup)) (insert " "))
11891 (insert "[" c "] " tg (make-string
11892 (- fwidth 4 (length tg)) ?\ ))
11893 (push (cons tg c) ntable)
11894 (when (= (setq cnt (1+ cnt)) ncol)
11895 (insert "\n")
11896 (if ingroup (insert " "))
11897 (setq cnt 0)))))
11898 (setq ntable (nreverse ntable))
11899 (insert "\n")
11900 (goto-char (point-min))
11901 (if (not expert) (org-fit-window-to-buffer))
11902 (setq rtn
11903 (catch 'exit
11904 (while t
11905 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11906 (if (not groups) "no " "")
11907 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11908 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11909 (cond
11910 ((= c ?\r) (throw 'exit t))
11911 ((= c ?!)
11912 (setq groups (not groups))
11913 (goto-char (point-min))
11914 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11915 ((= c ?\C-c)
11916 (if (not expert)
11917 (org-fast-tag-show-exit
11918 (setq exit-after-next (not exit-after-next)))
11919 (setq expert nil)
11920 (delete-other-windows)
11921 (split-window-vertically)
11922 (org-switch-to-buffer-other-window " *Org tags*")
11923 (org-fit-window-to-buffer)))
11924 ((or (= c ?\C-g)
11925 (and (= c ?q) (not (rassoc c ntable))))
11926 (org-detach-overlay org-tags-overlay)
11927 (setq quit-flag t))
11928 ((= c ?\ )
11929 (setq current nil)
11930 (if exit-after-next (setq exit-after-next 'now)))
11931 ((= c ?\t)
11932 (condition-case nil
11933 (setq tg (org-icompleting-read
11934 "Tag: "
11935 (or buffer-tags
11936 (with-current-buffer buf
11937 (org-get-buffer-tags)))))
11938 (quit (setq tg "")))
11939 (when (string-match "\\S-" tg)
11940 (add-to-list 'buffer-tags (list tg))
11941 (if (member tg current)
11942 (setq current (delete tg current))
11943 (push tg current)))
11944 (if exit-after-next (setq exit-after-next 'now)))
11945 ((setq e (rassoc c todo-table) tg (car e))
11946 (with-current-buffer buf
11947 (save-excursion (org-todo tg)))
11948 (if exit-after-next (setq exit-after-next 'now)))
11949 ((setq e (rassoc c ntable) tg (car e))
11950 (if (member tg current)
11951 (setq current (delete tg current))
11952 (loop for g in groups do
11953 (if (member tg g)
11954 (mapc (lambda (x)
11955 (setq current (delete x current)))
11956 g)))
11957 (push tg current))
11958 (if exit-after-next (setq exit-after-next 'now))))
11960 ;; Create a sorted list
11961 (setq current
11962 (sort current
11963 (lambda (a b)
11964 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11965 (if (eq exit-after-next 'now) (throw 'exit t))
11966 (goto-char (point-min))
11967 (beginning-of-line 2)
11968 (delete-region (point) (point-at-eol))
11969 (org-fast-tag-insert "Current" current c-face)
11970 (org-set-current-tags-overlay current ov-prefix)
11971 (while (re-search-forward
11972 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11973 (setq tg (match-string 1))
11974 (add-text-properties
11975 (match-beginning 1) (match-end 1)
11976 (list 'face
11977 (cond
11978 ((member tg current) c-face)
11979 ((member tg inherited) i-face)
11980 (t (get-text-property (match-beginning 1) 'face))))))
11981 (goto-char (point-min)))))
11982 (org-detach-overlay org-tags-overlay)
11983 (if rtn
11984 (mapconcat 'identity current ":")
11985 nil))))
11987 (defun org-get-tags-string ()
11988 "Get the TAGS string in the current headline."
11989 (unless (org-on-heading-p t)
11990 (error "Not on a heading"))
11991 (save-excursion
11992 (beginning-of-line 1)
11993 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11994 (org-match-string-no-properties 1)
11995 "")))
11997 (defun org-get-tags ()
11998 "Get the list of tags specified in the current headline."
11999 (org-split-string (org-get-tags-string) ":"))
12001 (defun org-get-buffer-tags ()
12002 "Get a table of all tags used in the buffer, for completion."
12003 (let (tags)
12004 (save-excursion
12005 (goto-char (point-min))
12006 (while (re-search-forward
12007 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12008 (when (equal (char-after (point-at-bol 0)) ?*)
12009 (mapc (lambda (x) (add-to-list 'tags x))
12010 (org-split-string (org-match-string-no-properties 1) ":")))))
12011 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12012 (mapcar 'list tags)))
12014 ;;;; The mapping API
12016 ;;;###autoload
12017 (defun org-map-entries (func &optional match scope &rest skip)
12018 "Call FUNC at each headline selected by MATCH in SCOPE.
12020 FUNC is a function or a lisp form. The function will be called without
12021 arguments, with the cursor positioned at the beginning of the headline.
12022 The return values of all calls to the function will be collected and
12023 returned as a list.
12025 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12026 does not need to preserve point. After evaluation, the cursor will be
12027 moved to the end of the line (presumably of the headline of the
12028 processed entry) and search continues from there. Under some
12029 circumstances, this may not produce the wanted results. For example,
12030 if you have removed (e.g. archived) the current (sub)tree it could
12031 mean that the next entry will be skipped entirely. In such cases, you
12032 can specify the position from where search should continue by making
12033 FUNC set the variable `org-map-continue-from' to the desired buffer
12034 position.
12036 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12037 Only headlines that are matched by this query will be considered during
12038 the iteration. When MATCH is nil or t, all headlines will be
12039 visited by the iteration.
12041 SCOPE determines the scope of this command. It can be any of:
12043 nil The current buffer, respecting the restriction if any
12044 tree The subtree started with the entry at point
12045 file The current buffer, without restriction
12046 file-with-archives
12047 The current buffer, and any archives associated with it
12048 agenda All agenda files
12049 agenda-with-archives
12050 All agenda files with any archive files associated with them
12051 \(file1 file2 ...)
12052 If this is a list, all files in the list will be scanned
12054 The remaining args are treated as settings for the skipping facilities of
12055 the scanner. The following items can be given here:
12057 archive skip trees with the archive tag.
12058 comment skip trees with the COMMENT keyword
12059 function or Emacs Lisp form:
12060 will be used as value for `org-agenda-skip-function', so whenever
12061 the function returns t, FUNC will not be called for that
12062 entry and search will continue from the point where the
12063 function leaves it.
12065 If your function needs to retrieve the tags including inherited tags
12066 at the *current* entry, you can use the value of the variable
12067 `org-scanner-tags' which will be much faster than getting the value
12068 with `org-get-tags-at'. If your function gets properties with
12069 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12070 to t around the call to `org-entry-properties' to get the same speedup.
12071 Note that if your function moves around to retrieve tags and properties at
12072 a *different* entry, you cannot use these techniques."
12073 (let* ((org-agenda-archives-mode nil) ; just to make sure
12074 (org-agenda-skip-archived-trees (memq 'archive skip))
12075 (org-agenda-skip-comment-trees (memq 'comment skip))
12076 (org-agenda-skip-function
12077 (car (org-delete-all '(comment archive) skip)))
12078 (org-tags-match-list-sublevels t)
12079 matcher file res
12080 org-todo-keywords-for-agenda
12081 org-done-keywords-for-agenda
12082 org-todo-keyword-alist-for-agenda
12083 org-drawers-for-agenda
12084 org-tag-alist-for-agenda)
12086 (cond
12087 ((eq match t) (setq matcher t))
12088 ((eq match nil) (setq matcher t))
12089 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12091 (save-excursion
12092 (save-restriction
12093 (when (eq scope 'tree)
12094 (org-back-to-heading t)
12095 (org-narrow-to-subtree)
12096 (setq scope nil))
12098 (if (not scope)
12099 (progn
12100 (org-prepare-agenda-buffers
12101 (list (buffer-file-name (current-buffer))))
12102 (setq res (org-scan-tags func matcher)))
12103 ;; Get the right scope
12104 (cond
12105 ((and scope (listp scope) (symbolp (car scope)))
12106 (setq scope (eval scope)))
12107 ((eq scope 'agenda)
12108 (setq scope (org-agenda-files t)))
12109 ((eq scope 'agenda-with-archives)
12110 (setq scope (org-agenda-files t))
12111 (setq scope (org-add-archive-files scope)))
12112 ((eq scope 'file)
12113 (setq scope (list (buffer-file-name))))
12114 ((eq scope 'file-with-archives)
12115 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12116 (org-prepare-agenda-buffers scope)
12117 (while (setq file (pop scope))
12118 (with-current-buffer (org-find-base-buffer-visiting file)
12119 (save-excursion
12120 (save-restriction
12121 (widen)
12122 (goto-char (point-min))
12123 (setq res (append res (org-scan-tags func matcher))))))))))
12124 res))
12126 ;;;; Properties
12128 ;;; Setting and retrieving properties
12130 (defconst org-special-properties
12131 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12132 "TIMESTAMP" "TIMESTAMP_IA")
12133 "The special properties valid in Org-mode.
12135 These are properties that are not defined in the property drawer,
12136 but in some other way.")
12138 (defconst org-default-properties
12139 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12140 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12141 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12142 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12143 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12144 "CLOCK_MODELINE_TOTAL" "STYLE")
12145 "Some properties that are used by Org-mode for various purposes.
12146 Being in this list makes sure that they are offered for completion.")
12148 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12149 "Regular expression matching the first line of a property drawer.")
12151 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12152 "Regular expression matching the first line of a property drawer.")
12154 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12155 "Regular expression matching the first line of a property drawer.")
12157 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12158 "Regular expression matching the first line of a property drawer.")
12160 (defconst org-property-drawer-re
12161 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12162 org-property-end-re "\\)\n?")
12163 "Matches an entire property drawer.")
12165 (defconst org-clock-drawer-re
12166 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12167 org-property-end-re "\\)\n?")
12168 "Matches an entire clock drawer.")
12170 (defun org-property-action ()
12171 "Do an action on properties."
12172 (interactive)
12173 (let (c)
12174 (org-at-property-p)
12175 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12176 (setq c (read-char-exclusive))
12177 (cond
12178 ((equal c ?s)
12179 (call-interactively 'org-set-property))
12180 ((equal c ?d)
12181 (call-interactively 'org-delete-property))
12182 ((equal c ?D)
12183 (call-interactively 'org-delete-property-globally))
12184 ((equal c ?c)
12185 (call-interactively 'org-compute-property-at-point))
12186 (t (error "No such property action %c" c)))))
12188 (defun org-set-effort (&optional value)
12189 "Set the effort property of the current entry.
12190 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12191 allowed value."
12192 (interactive "P")
12193 (if (equal value 0) (setq value 10))
12194 (let* ((completion-ignore-case t)
12195 (prop org-effort-property)
12196 (cur (org-entry-get nil prop))
12197 (allowed (org-property-get-allowed-values nil prop 'table))
12198 (existing (mapcar 'list (org-property-values prop)))
12200 (val (cond
12201 ((stringp value) value)
12202 ((and allowed (integerp value))
12203 (or (car (nth (1- value) allowed))
12204 (car (org-last allowed))))
12205 (allowed
12206 (message "Select 1-9,0, [RET%s]: %s"
12207 (if cur (concat "=" cur) "")
12208 (mapconcat 'car allowed " "))
12209 (setq rpl (read-char-exclusive))
12210 (if (equal rpl ?\r)
12212 (setq rpl (- rpl ?0))
12213 (if (equal rpl 0) (setq rpl 10))
12214 (if (and (> rpl 0) (<= rpl (length allowed)))
12215 (car (nth (1- rpl) allowed))
12216 (org-completing-read "Value: " allowed nil))))
12218 (let (org-completion-use-ido org-completion-use-iswitchb)
12219 (org-completing-read
12220 (concat "Value " (if (and cur (string-match "\\S-" cur))
12221 (concat "[" cur "]") "")
12222 ": ")
12223 existing nil nil "" nil cur))))))
12224 (unless (equal (org-entry-get nil prop) val)
12225 (org-entry-put nil prop val))
12226 (message "%s is now %s" prop val)))
12228 (defun org-at-property-p ()
12229 "Is the cursor in a property line?"
12230 ;; FIXME: Does not check if we are actually in the drawer.
12231 ;; FIXME: also returns true on any drawers.....
12232 ;; This is used by C-c C-c for property action.
12233 (save-excursion
12234 (beginning-of-line 1)
12235 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12237 (defun org-get-property-block (&optional beg end force)
12238 "Return the (beg . end) range of the body of the property drawer.
12239 BEG and END can be beginning and end of subtree, if not given
12240 they will be found.
12241 If the drawer does not exist and FORCE is non-nil, create the drawer."
12242 (catch 'exit
12243 (save-excursion
12244 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12245 (end (or end (progn (outline-next-heading) (point)))))
12246 (goto-char beg)
12247 (if (re-search-forward org-property-start-re end t)
12248 (setq beg (1+ (match-end 0)))
12249 (if force
12250 (save-excursion
12251 (org-insert-property-drawer)
12252 (setq end (progn (outline-next-heading) (point))))
12253 (throw 'exit nil))
12254 (goto-char beg)
12255 (if (re-search-forward org-property-start-re end t)
12256 (setq beg (1+ (match-end 0)))))
12257 (if (re-search-forward org-property-end-re end t)
12258 (setq end (match-beginning 0))
12259 (or force (throw 'exit nil))
12260 (goto-char beg)
12261 (setq end beg)
12262 (org-indent-line-function)
12263 (insert ":END:\n"))
12264 (cons beg end)))))
12266 (defun org-entry-properties (&optional pom which)
12267 "Get all properties of the entry at point-or-marker POM.
12268 This includes the TODO keyword, the tags, time strings for deadline,
12269 scheduled, and clocking, and any additional properties defined in the
12270 entry. The return value is an alist, keys may occur multiple times
12271 if the property key was used several times.
12272 POM may also be nil, in which case the current entry is used.
12273 If WHICH is nil or `all', get all properties. If WHICH is
12274 `special' or `standard', only get that subclass."
12275 (setq which (or which 'all))
12276 (org-with-point-at pom
12277 (let ((clockstr (substring org-clock-string 0 -1))
12278 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12279 beg end range props sum-props key value string clocksum)
12280 (save-excursion
12281 (when (condition-case nil
12282 (and (org-mode-p) (org-back-to-heading t))
12283 (error nil))
12284 (setq beg (point))
12285 (setq sum-props (get-text-property (point) 'org-summaries))
12286 (setq clocksum (get-text-property (point) :org-clock-minutes))
12287 (outline-next-heading)
12288 (setq end (point))
12289 (when (memq which '(all special))
12290 ;; Get the special properties, like TODO and tags
12291 (goto-char beg)
12292 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12293 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12294 (when (looking-at org-priority-regexp)
12295 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12296 (when (and (setq value (org-get-tags-string))
12297 (string-match "\\S-" value))
12298 (push (cons "TAGS" value) props))
12299 (when (setq value (org-get-tags-at))
12300 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12301 props))
12302 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12303 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12304 string (if (equal key clockstr)
12305 (org-no-properties
12306 (org-trim
12307 (buffer-substring
12308 (match-beginning 3) (goto-char (point-at-eol)))))
12309 (substring (org-match-string-no-properties 3) 1 -1)))
12310 (unless key
12311 (if (= (char-after (match-beginning 3)) ?\[)
12312 (setq key "TIMESTAMP_IA")
12313 (setq key "TIMESTAMP")))
12314 (when (or (equal key clockstr) (not (assoc key props)))
12315 (push (cons key string) props)))
12319 (when (memq which '(all standard))
12320 ;; Get the standard properties, like :PROP: ...
12321 (setq range (org-get-property-block beg end))
12322 (when range
12323 (goto-char (car range))
12324 (while (re-search-forward
12325 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12326 (cdr range) t)
12327 (setq key (org-match-string-no-properties 1)
12328 value (org-trim (or (org-match-string-no-properties 2) "")))
12329 (unless (member key excluded)
12330 (push (cons key (or value "")) props)))))
12331 (if clocksum
12332 (push (cons "CLOCKSUM"
12333 (org-columns-number-to-string (/ (float clocksum) 60.)
12334 'add_times))
12335 props))
12336 (unless (assoc "CATEGORY" props)
12337 (setq value (or (org-get-category)
12338 (progn (org-refresh-category-properties)
12339 (org-get-category))))
12340 (push (cons "CATEGORY" value) props))
12341 (append sum-props (nreverse props)))))))
12343 (defun org-entry-get (pom property &optional inherit)
12344 "Get value of PROPERTY for entry at point-or-marker POM.
12345 If INHERIT is non-nil and the entry does not have the property,
12346 then also check higher levels of the hierarchy.
12347 If INHERIT is the symbol `selective', use inheritance only if the setting
12348 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12349 If the property is present but empty, the return value is the empty string.
12350 If the property is not present at all, nil is returned."
12351 (org-with-point-at pom
12352 (if (and inherit (if (eq inherit 'selective)
12353 (org-property-inherit-p property)
12355 (org-entry-get-with-inheritance property)
12356 (if (member property org-special-properties)
12357 ;; We need a special property. Use brute force, get all properties.
12358 (cdr (assoc property (org-entry-properties nil 'special)))
12359 (let ((range (org-get-property-block)))
12360 (if (and range
12361 (goto-char (car range))
12362 (re-search-forward
12363 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12364 (cdr range) t))
12365 ;; Found the property, return it.
12366 (if (match-end 1)
12367 (org-match-string-no-properties 1)
12368 "")))))))
12370 (defun org-property-or-variable-value (var &optional inherit)
12371 "Check if there is a property fixing the value of VAR.
12372 If yes, return this value. If not, return the current value of the variable."
12373 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12374 (if (and prop (stringp prop) (string-match "\\S-" prop))
12375 (read prop)
12376 (symbol-value var))))
12378 (defun org-entry-delete (pom property)
12379 "Delete the property PROPERTY from entry at point-or-marker POM."
12380 (org-with-point-at pom
12381 (if (member property org-special-properties)
12382 nil ; cannot delete these properties.
12383 (let ((range (org-get-property-block)))
12384 (if (and range
12385 (goto-char (car range))
12386 (re-search-forward
12387 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12388 (cdr range) t))
12389 (progn
12390 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12392 nil)))))
12394 ;; Multi-values properties are properties that contain multiple values
12395 ;; These values are assumed to be single words, separated by whitespace.
12396 (defun org-entry-add-to-multivalued-property (pom property value)
12397 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12398 (let* ((old (org-entry-get pom property))
12399 (values (and old (org-split-string old "[ \t]"))))
12400 (setq value (org-entry-protect-space value))
12401 (unless (member value values)
12402 (setq values (cons value values))
12403 (org-entry-put pom property
12404 (mapconcat 'identity values " ")))))
12406 (defun org-entry-remove-from-multivalued-property (pom property value)
12407 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12408 (let* ((old (org-entry-get pom property))
12409 (values (and old (org-split-string old "[ \t]"))))
12410 (setq value (org-entry-protect-space value))
12411 (when (member value values)
12412 (setq values (delete value values))
12413 (org-entry-put pom property
12414 (mapconcat 'identity values " ")))))
12416 (defun org-entry-member-in-multivalued-property (pom property value)
12417 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12418 (let* ((old (org-entry-get pom property))
12419 (values (and old (org-split-string old "[ \t]"))))
12420 (setq value (org-entry-protect-space value))
12421 (member value values)))
12423 (defun org-entry-get-multivalued-property (pom property)
12424 "Return a list of values in a multivalued property."
12425 (let* ((value (org-entry-get pom property))
12426 (values (and value (org-split-string value "[ \t]"))))
12427 (mapcar 'org-entry-restore-space values)))
12429 (defun org-entry-put-multivalued-property (pom property &rest values)
12430 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12431 VALUES should be a list of strings. Spaces will be protected."
12432 (org-entry-put pom property
12433 (mapconcat 'org-entry-protect-space values " "))
12434 (let* ((value (org-entry-get pom property))
12435 (values (and value (org-split-string value "[ \t]"))))
12436 (mapcar 'org-entry-restore-space values)))
12438 (defun org-entry-protect-space (s)
12439 "Protect spaces and newline in string S."
12440 (while (string-match " " s)
12441 (setq s (replace-match "%20" t t s)))
12442 (while (string-match "\n" s)
12443 (setq s (replace-match "%0A" t t s)))
12446 (defun org-entry-restore-space (s)
12447 "Restore spaces and newline in string S."
12448 (while (string-match "%20" s)
12449 (setq s (replace-match " " t t s)))
12450 (while (string-match "%0A" s)
12451 (setq s (replace-match "\n" t t s)))
12454 (defvar org-entry-property-inherited-from (make-marker)
12455 "Marker pointing to the entry from where a property was inherited.
12456 Each call to `org-entry-get-with-inheritance' will set this marker to the
12457 location of the entry where the inheritance search matched. If there was
12458 no match, the marker will point nowhere.
12459 Note that also `org-entry-get' calls this function, if the INHERIT flag
12460 is set.")
12462 (defun org-entry-get-with-inheritance (property)
12463 "Get entry property, and search higher levels if not present."
12464 (move-marker org-entry-property-inherited-from nil)
12465 (let (tmp)
12466 (save-excursion
12467 (save-restriction
12468 (widen)
12469 (catch 'ex
12470 (while t
12471 (when (setq tmp (org-entry-get nil property))
12472 (org-back-to-heading t)
12473 (move-marker org-entry-property-inherited-from (point))
12474 (throw 'ex tmp))
12475 (or (org-up-heading-safe) (throw 'ex nil)))))
12476 (or tmp
12477 (cdr (assoc property org-file-properties))
12478 (cdr (assoc property org-global-properties))
12479 (cdr (assoc property org-global-properties-fixed))))))
12481 (defun org-entry-put (pom property value)
12482 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12483 (org-with-point-at pom
12484 (org-back-to-heading t)
12485 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12486 range)
12487 (cond
12488 ((equal property "TODO")
12489 (when (and (stringp value) (string-match "\\S-" value)
12490 (not (member value org-todo-keywords-1)))
12491 (error "\"%s\" is not a valid TODO state" value))
12492 (if (or (not value)
12493 (not (string-match "\\S-" value)))
12494 (setq value 'none))
12495 (org-todo value)
12496 (org-set-tags nil 'align))
12497 ((equal property "PRIORITY")
12498 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12499 (string-to-char value) ?\ ))
12500 (org-set-tags nil 'align))
12501 ((equal property "SCHEDULED")
12502 (if (re-search-forward org-scheduled-time-regexp end t)
12503 (cond
12504 ((eq value 'earlier) (org-timestamp-change -1 'day))
12505 ((eq value 'later) (org-timestamp-change 1 'day))
12506 (t (call-interactively 'org-schedule)))
12507 (call-interactively 'org-schedule)))
12508 ((equal property "DEADLINE")
12509 (if (re-search-forward org-deadline-time-regexp end t)
12510 (cond
12511 ((eq value 'earlier) (org-timestamp-change -1 'day))
12512 ((eq value 'later) (org-timestamp-change 1 'day))
12513 (t (call-interactively 'org-deadline)))
12514 (call-interactively 'org-deadline)))
12515 ((member property org-special-properties)
12516 (error "The %s property can not yet be set with `org-entry-put'"
12517 property))
12518 (t ; a non-special property
12519 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12520 (setq range (org-get-property-block beg end 'force))
12521 (goto-char (car range))
12522 (if (re-search-forward
12523 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12524 (progn
12525 (delete-region (match-beginning 1) (match-end 1))
12526 (goto-char (match-beginning 1)))
12527 (goto-char (cdr range))
12528 (insert "\n")
12529 (backward-char 1)
12530 (org-indent-line-function)
12531 (insert ":" property ":"))
12532 (and value (insert " " value))
12533 (org-indent-line-function)))))))
12535 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12536 "Get all property keys in the current buffer.
12537 With INCLUDE-SPECIALS, also list the special properties that reflect things
12538 like tags and TODO state.
12539 With INCLUDE-DEFAULTS, also include properties that has special meaning
12540 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12541 With INCLUDE-COLUMNS, also include property names given in COLUMN
12542 formats in the current buffer."
12543 (let (rtn range cfmt s p)
12544 (save-excursion
12545 (save-restriction
12546 (widen)
12547 (goto-char (point-min))
12548 (while (re-search-forward org-property-start-re nil t)
12549 (setq range (org-get-property-block))
12550 (goto-char (car range))
12551 (while (re-search-forward
12552 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12553 (cdr range) t)
12554 (add-to-list 'rtn (org-match-string-no-properties 1)))
12555 (outline-next-heading))))
12557 (when include-specials
12558 (setq rtn (append org-special-properties rtn)))
12560 (when include-defaults
12561 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12562 (add-to-list 'rtn org-effort-property))
12564 (when include-columns
12565 (save-excursion
12566 (save-restriction
12567 (widen)
12568 (goto-char (point-min))
12569 (while (re-search-forward
12570 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12571 nil t)
12572 (setq cfmt (match-string 2) s 0)
12573 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12574 cfmt s)
12575 (setq s (match-end 0)
12576 p (match-string 1 cfmt))
12577 (unless (or (equal p "ITEM")
12578 (member p org-special-properties))
12579 (add-to-list 'rtn (match-string 1 cfmt))))))))
12581 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12583 (defun org-property-values (key)
12584 "Return a list of all values of property KEY."
12585 (save-excursion
12586 (save-restriction
12587 (widen)
12588 (goto-char (point-min))
12589 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12590 values)
12591 (while (re-search-forward re nil t)
12592 (add-to-list 'values (org-trim (match-string 1))))
12593 (delete "" values)))))
12595 (defun org-insert-property-drawer ()
12596 "Insert a property drawer into the current entry."
12597 (interactive)
12598 (org-back-to-heading t)
12599 (looking-at outline-regexp)
12600 (let ((indent (if org-adapt-indentation
12601 (- (match-end 0)(match-beginning 0))
12603 (beg (point))
12604 (re (concat "^[ \t]*" org-keyword-time-regexp))
12605 end hiddenp)
12606 (outline-next-heading)
12607 (setq end (point))
12608 (goto-char beg)
12609 (while (re-search-forward re end t))
12610 (setq hiddenp (org-invisible-p))
12611 (end-of-line 1)
12612 (and (equal (char-after) ?\n) (forward-char 1))
12613 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12614 (if (member (match-string 1) '("CLOCK:" ":END:"))
12615 ;; just skip this line
12616 (beginning-of-line 2)
12617 ;; Drawer start, find the end
12618 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12619 (beginning-of-line 1)))
12620 (org-skip-over-state-notes)
12621 (skip-chars-backward " \t\n\r")
12622 (if (eq (char-before) ?*) (forward-char 1))
12623 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12624 (beginning-of-line 0)
12625 (org-indent-to-column indent)
12626 (beginning-of-line 2)
12627 (org-indent-to-column indent)
12628 (beginning-of-line 0)
12629 (if hiddenp
12630 (save-excursion
12631 (org-back-to-heading t)
12632 (hide-entry))
12633 (org-flag-drawer t))))
12635 (defun org-set-property (property value)
12636 "In the current entry, set PROPERTY to VALUE.
12637 When called interactively, this will prompt for a property name, offering
12638 completion on existing and default properties. And then it will prompt
12639 for a value, offering completion either on allowed values (via an inherited
12640 xxx_ALL property) or on existing values in other instances of this property
12641 in the current file."
12642 (interactive
12643 (let* ((completion-ignore-case t)
12644 (keys (org-buffer-property-keys nil t t))
12645 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12646 (prop (if (member prop0 keys)
12647 prop0
12648 (or (cdr (assoc (downcase prop0)
12649 (mapcar (lambda (x) (cons (downcase x) x))
12650 keys)))
12651 prop0)))
12652 (cur (org-entry-get nil prop))
12653 (allowed (org-property-get-allowed-values nil prop 'table))
12654 (existing (mapcar 'list (org-property-values prop)))
12655 (val (if allowed
12656 (org-completing-read "Value: " allowed nil 'req-match)
12657 (let (org-completion-use-ido org-completion-use-iswitchb)
12658 (org-completing-read
12659 (concat "Value " (if (and cur (string-match "\\S-" cur))
12660 (concat "[" cur "]") "")
12661 ": ")
12662 existing nil nil "" nil cur)))))
12663 (list prop (if (equal val "") cur val))))
12664 (unless (equal (org-entry-get nil property) value)
12665 (org-entry-put nil property value)))
12667 (defun org-delete-property (property)
12668 "In the current entry, delete PROPERTY."
12669 (interactive
12670 (let* ((completion-ignore-case t)
12671 (prop (org-icompleting-read
12672 "Property: " (org-entry-properties nil 'standard))))
12673 (list prop)))
12674 (message "Property %s %s" property
12675 (if (org-entry-delete nil property)
12676 "deleted"
12677 "was not present in the entry")))
12679 (defun org-delete-property-globally (property)
12680 "Remove PROPERTY globally, from all entries."
12681 (interactive
12682 (let* ((completion-ignore-case t)
12683 (prop (org-icompleting-read
12684 "Globally remove property: "
12685 (mapcar 'list (org-buffer-property-keys)))))
12686 (list prop)))
12687 (save-excursion
12688 (save-restriction
12689 (widen)
12690 (goto-char (point-min))
12691 (let ((cnt 0))
12692 (while (re-search-forward
12693 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12694 nil t)
12695 (setq cnt (1+ cnt))
12696 (replace-match ""))
12697 (message "Property \"%s\" removed from %d entries" property cnt)))))
12699 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12701 (defun org-compute-property-at-point ()
12702 "Compute the property at point.
12703 This looks for an enclosing column format, extracts the operator and
12704 then applies it to the property in the column format's scope."
12705 (interactive)
12706 (unless (org-at-property-p)
12707 (error "Not at a property"))
12708 (let ((prop (org-match-string-no-properties 2)))
12709 (org-columns-get-format-and-top-level)
12710 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12711 (error "No operator defined for property %s" prop))
12712 (org-columns-compute prop)))
12714 (defun org-property-get-allowed-values (pom property &optional table)
12715 "Get allowed values for the property PROPERTY.
12716 When TABLE is non-nil, return an alist that can directly be used for
12717 completion."
12718 (let (vals)
12719 (cond
12720 ((equal property "TODO")
12721 (setq vals (org-with-point-at pom
12722 (append org-todo-keywords-1 '("")))))
12723 ((equal property "PRIORITY")
12724 (let ((n org-lowest-priority))
12725 (while (>= n org-highest-priority)
12726 (push (char-to-string n) vals)
12727 (setq n (1- n)))))
12728 ((member property org-special-properties))
12730 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12732 (when (and vals (string-match "\\S-" vals))
12733 (setq vals (car (read-from-string (concat "(" vals ")"))))
12734 (setq vals (mapcar (lambda (x)
12735 (cond ((stringp x) x)
12736 ((numberp x) (number-to-string x))
12737 ((symbolp x) (symbol-name x))
12738 (t "???")))
12739 vals)))))
12740 (if table (mapcar 'list vals) vals)))
12742 (defun org-property-previous-allowed-value (&optional previous)
12743 "Switch to the next allowed value for this property."
12744 (interactive)
12745 (org-property-next-allowed-value t))
12747 (defun org-property-next-allowed-value (&optional previous)
12748 "Switch to the next allowed value for this property."
12749 (interactive)
12750 (unless (org-at-property-p)
12751 (error "Not at a property"))
12752 (let* ((key (match-string 2))
12753 (value (match-string 3))
12754 (allowed (or (org-property-get-allowed-values (point) key)
12755 (and (member value '("[ ]" "[-]" "[X]"))
12756 '("[ ]" "[X]"))))
12757 nval)
12758 (unless allowed
12759 (error "Allowed values for this property have not been defined"))
12760 (if previous (setq allowed (reverse allowed)))
12761 (if (member value allowed)
12762 (setq nval (car (cdr (member value allowed)))))
12763 (setq nval (or nval (car allowed)))
12764 (if (equal nval value)
12765 (error "Only one allowed value for this property"))
12766 (org-at-property-p)
12767 (replace-match (concat " :" key ": " nval) t t)
12768 (org-indent-line-function)
12769 (beginning-of-line 1)
12770 (skip-chars-forward " \t")))
12772 (defun org-find-entry-with-id (ident)
12773 "Locate the entry that contains the ID property with exact value IDENT.
12774 IDENT can be a string, a symbol or a number, this function will search for
12775 the string representation of it.
12776 Return the position where this entry starts, or nil if there is no such entry."
12777 (interactive "sID: ")
12778 (let ((id (cond
12779 ((stringp ident) ident)
12780 ((symbol-name ident) (symbol-name ident))
12781 ((numberp ident) (number-to-string ident))
12782 (t (error "IDENT %s must be a string, symbol or number" ident))))
12783 (case-fold-search nil))
12784 (save-excursion
12785 (save-restriction
12786 (widen)
12787 (goto-char (point-min))
12788 (when (re-search-forward
12789 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12790 nil t)
12791 (org-back-to-heading t)
12792 (point))))))
12794 ;;;; Timestamps
12796 (defvar org-last-changed-timestamp nil)
12797 (defvar org-last-inserted-timestamp nil
12798 "The last time stamp inserted with `org-insert-time-stamp'.")
12799 (defvar org-time-was-given) ; dynamically scoped parameter
12800 (defvar org-end-time-was-given) ; dynamically scoped parameter
12801 (defvar org-ts-what) ; dynamically scoped parameter
12803 (defun org-time-stamp (arg &optional inactive)
12804 "Prompt for a date/time and insert a time stamp.
12805 If the user specifies a time like HH:MM, or if this command is called
12806 with a prefix argument, the time stamp will contain date and time.
12807 Otherwise, only the date will be included. All parts of a date not
12808 specified by the user will be filled in from the current date/time.
12809 So if you press just return without typing anything, the time stamp
12810 will represent the current date/time. If there is already a timestamp
12811 at the cursor, it will be modified."
12812 (interactive "P")
12813 (let* ((ts nil)
12814 (default-time
12815 ;; Default time is either today, or, when entering a range,
12816 ;; the range start.
12817 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12818 (save-excursion
12819 (re-search-backward
12820 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12821 (- (point) 20) t)))
12822 (apply 'encode-time (org-parse-time-string (match-string 1)))
12823 (current-time)))
12824 (default-input (and ts (org-get-compact-tod ts)))
12825 org-time-was-given org-end-time-was-given time)
12826 (cond
12827 ((and (org-at-timestamp-p t)
12828 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12829 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12830 (insert "--")
12831 (setq time (let ((this-command this-command))
12832 (org-read-date arg 'totime nil nil
12833 default-time default-input)))
12834 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12835 ((org-at-timestamp-p t)
12836 (setq time (let ((this-command this-command))
12837 (org-read-date arg 'totime nil nil default-time default-input)))
12838 (when (org-at-timestamp-p t) ; just to get the match data
12839 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12840 (replace-match "")
12841 (setq org-last-changed-timestamp
12842 (org-insert-time-stamp
12843 time (or org-time-was-given arg)
12844 inactive nil nil (list org-end-time-was-given))))
12845 (message "Timestamp updated"))
12847 (setq time (let ((this-command this-command))
12848 (org-read-date arg 'totime nil nil default-time default-input)))
12849 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12850 nil nil (list org-end-time-was-given))))))
12852 ;; FIXME: can we use this for something else, like computing time differences?
12853 (defun org-get-compact-tod (s)
12854 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12855 (let* ((t1 (match-string 1 s))
12856 (h1 (string-to-number (match-string 2 s)))
12857 (m1 (string-to-number (match-string 3 s)))
12858 (t2 (and (match-end 4) (match-string 5 s)))
12859 (h2 (and t2 (string-to-number (match-string 6 s))))
12860 (m2 (and t2 (string-to-number (match-string 7 s))))
12861 dh dm)
12862 (if (not t2)
12864 (setq dh (- h2 h1) dm (- m2 m1))
12865 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12866 (concat t1 "+" (number-to-string dh)
12867 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12869 (defun org-time-stamp-inactive (&optional arg)
12870 "Insert an inactive time stamp.
12871 An inactive time stamp is enclosed in square brackets instead of angle
12872 brackets. It is inactive in the sense that it does not trigger agenda entries,
12873 does not link to the calendar and cannot be changed with the S-cursor keys.
12874 So these are more for recording a certain time/date."
12875 (interactive "P")
12876 (org-time-stamp arg 'inactive))
12878 (defvar org-date-ovl (org-make-overlay 1 1))
12879 (org-overlay-put org-date-ovl 'face 'org-warning)
12880 (org-detach-overlay org-date-ovl)
12882 (defvar org-ans1) ; dynamically scoped parameter
12883 (defvar org-ans2) ; dynamically scoped parameter
12885 (defvar org-plain-time-of-day-regexp) ; defined below
12887 (defvar org-overriding-default-time nil) ; dynamically scoped
12888 (defvar org-read-date-overlay nil)
12889 (defvar org-dcst nil) ; dynamically scoped
12890 (defvar org-read-date-history nil)
12891 (defvar org-read-date-final-answer nil)
12893 (defun org-read-date (&optional with-time to-time from-string prompt
12894 default-time default-input)
12895 "Read a date, possibly a time, and make things smooth for the user.
12896 The prompt will suggest to enter an ISO date, but you can also enter anything
12897 which will at least partially be understood by `parse-time-string'.
12898 Unrecognized parts of the date will default to the current day, month, year,
12899 hour and minute. If this command is called to replace a timestamp at point,
12900 of to enter the second timestamp of a range, the default time is taken from the
12901 existing stamp. For example,
12902 3-2-5 --> 2003-02-05
12903 feb 15 --> currentyear-02-15
12904 sep 12 9 --> 2009-09-12
12905 12:45 --> today 12:45
12906 22 sept 0:34 --> currentyear-09-22 0:34
12907 12 --> currentyear-currentmonth-12
12908 Fri --> nearest Friday (today or later)
12909 etc.
12911 Furthermore you can specify a relative date by giving, as the *first* thing
12912 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12913 change in days weeks, months, years.
12914 With a single plus or minus, the date is relative to today. With a double
12915 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12916 +4d --> four days from today
12917 +4 --> same as above
12918 +2w --> two weeks from today
12919 ++5 --> five days from default date
12921 The function understands only English month and weekday abbreviations,
12922 but this can be configured with the variables `parse-time-months' and
12923 `parse-time-weekdays'.
12925 While prompting, a calendar is popped up - you can also select the
12926 date with the mouse (button 1). The calendar shows a period of three
12927 months. To scroll it to other months, use the keys `>' and `<'.
12928 If you don't like the calendar, turn it off with
12929 \(setq org-read-date-popup-calendar nil)
12931 With optional argument TO-TIME, the date will immediately be converted
12932 to an internal time.
12933 With an optional argument WITH-TIME, the prompt will suggest to also
12934 insert a time. Note that when WITH-TIME is not set, you can still
12935 enter a time, and this function will inform the calling routine about
12936 this change. The calling routine may then choose to change the format
12937 used to insert the time stamp into the buffer to include the time.
12938 With optional argument FROM-STRING, read from this string instead from
12939 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12940 the time/date that is used for everything that is not specified by the
12941 user."
12942 (require 'parse-time)
12943 (let* ((org-time-stamp-rounding-minutes
12944 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12945 (org-dcst org-display-custom-times)
12946 (ct (org-current-time))
12947 (def (or org-overriding-default-time default-time ct))
12948 (defdecode (decode-time def))
12949 (dummy (progn
12950 (when (< (nth 2 defdecode) org-extend-today-until)
12951 (setcar (nthcdr 2 defdecode) -1)
12952 (setcar (nthcdr 1 defdecode) 59)
12953 (setq def (apply 'encode-time defdecode)
12954 defdecode (decode-time def)))))
12955 (calendar-frame-setup nil)
12956 (calendar-move-hook nil)
12957 (calendar-view-diary-initially-flag nil)
12958 (view-diary-entries-initially nil)
12959 (calendar-view-holidays-initially-flag nil)
12960 (view-calendar-holidays-initially nil)
12961 (timestr (format-time-string
12962 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12963 (prompt (concat (if prompt (concat prompt " ") "")
12964 (format "Date+time [%s]: " timestr)))
12965 ans (org-ans0 "") org-ans1 org-ans2 final)
12967 (cond
12968 (from-string (setq ans from-string))
12969 (org-read-date-popup-calendar
12970 (save-excursion
12971 (save-window-excursion
12972 (calendar)
12973 (calendar-forward-day (- (time-to-days def)
12974 (calendar-absolute-from-gregorian
12975 (calendar-current-date))))
12976 (org-eval-in-calendar nil t)
12977 (let* ((old-map (current-local-map))
12978 (map (copy-keymap calendar-mode-map))
12979 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12980 (org-defkey map (kbd "RET") 'org-calendar-select)
12981 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12982 'org-calendar-select-mouse)
12983 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12984 'org-calendar-select-mouse)
12985 (org-defkey minibuffer-local-map [(meta shift left)]
12986 (lambda () (interactive)
12987 (org-eval-in-calendar '(calendar-backward-month 1))))
12988 (org-defkey minibuffer-local-map [(meta shift right)]
12989 (lambda () (interactive)
12990 (org-eval-in-calendar '(calendar-forward-month 1))))
12991 (org-defkey minibuffer-local-map [(meta shift up)]
12992 (lambda () (interactive)
12993 (org-eval-in-calendar '(calendar-backward-year 1))))
12994 (org-defkey minibuffer-local-map [(meta shift down)]
12995 (lambda () (interactive)
12996 (org-eval-in-calendar '(calendar-forward-year 1))))
12997 (org-defkey minibuffer-local-map [?\e (shift left)]
12998 (lambda () (interactive)
12999 (org-eval-in-calendar '(calendar-backward-month 1))))
13000 (org-defkey minibuffer-local-map [?\e (shift right)]
13001 (lambda () (interactive)
13002 (org-eval-in-calendar '(calendar-forward-month 1))))
13003 (org-defkey minibuffer-local-map [?\e (shift up)]
13004 (lambda () (interactive)
13005 (org-eval-in-calendar '(calendar-backward-year 1))))
13006 (org-defkey minibuffer-local-map [?\e (shift down)]
13007 (lambda () (interactive)
13008 (org-eval-in-calendar '(calendar-forward-year 1))))
13009 (org-defkey minibuffer-local-map [(shift up)]
13010 (lambda () (interactive)
13011 (org-eval-in-calendar '(calendar-backward-week 1))))
13012 (org-defkey minibuffer-local-map [(shift down)]
13013 (lambda () (interactive)
13014 (org-eval-in-calendar '(calendar-forward-week 1))))
13015 (org-defkey minibuffer-local-map [(shift left)]
13016 (lambda () (interactive)
13017 (org-eval-in-calendar '(calendar-backward-day 1))))
13018 (org-defkey minibuffer-local-map [(shift right)]
13019 (lambda () (interactive)
13020 (org-eval-in-calendar '(calendar-forward-day 1))))
13021 (org-defkey minibuffer-local-map ">"
13022 (lambda () (interactive)
13023 (org-eval-in-calendar '(scroll-calendar-left 1))))
13024 (org-defkey minibuffer-local-map "<"
13025 (lambda () (interactive)
13026 (org-eval-in-calendar '(scroll-calendar-right 1))))
13027 (run-hooks 'org-read-date-minibuffer-setup-hook)
13028 (unwind-protect
13029 (progn
13030 (use-local-map map)
13031 (add-hook 'post-command-hook 'org-read-date-display)
13032 (setq org-ans0 (read-string prompt default-input
13033 'org-read-date-history nil))
13034 ;; org-ans0: from prompt
13035 ;; org-ans1: from mouse click
13036 ;; org-ans2: from calendar motion
13037 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13038 (remove-hook 'post-command-hook 'org-read-date-display)
13039 (use-local-map old-map)
13040 (when org-read-date-overlay
13041 (org-delete-overlay org-read-date-overlay)
13042 (setq org-read-date-overlay nil)))))))
13044 (t ; Naked prompt only
13045 (unwind-protect
13046 (setq ans (read-string prompt default-input
13047 'org-read-date-history timestr))
13048 (when org-read-date-overlay
13049 (org-delete-overlay org-read-date-overlay)
13050 (setq org-read-date-overlay nil)))))
13052 (setq final (org-read-date-analyze ans def defdecode))
13053 (setq org-read-date-final-answer ans)
13055 (if to-time
13056 (apply 'encode-time final)
13057 (if (and (boundp 'org-time-was-given) org-time-was-given)
13058 (format "%04d-%02d-%02d %02d:%02d"
13059 (nth 5 final) (nth 4 final) (nth 3 final)
13060 (nth 2 final) (nth 1 final))
13061 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13063 (defvar def)
13064 (defvar defdecode)
13065 (defvar with-time)
13066 (defvar org-read-date-analyze-futurep nil)
13067 (defun org-read-date-display ()
13068 "Display the current date prompt interpretation in the minibuffer."
13069 (when org-read-date-display-live
13070 (when org-read-date-overlay
13071 (org-delete-overlay org-read-date-overlay))
13072 (let ((p (point)))
13073 (end-of-line 1)
13074 (while (not (equal (buffer-substring
13075 (max (point-min) (- (point) 4)) (point))
13076 " "))
13077 (insert " "))
13078 (goto-char p))
13079 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13080 " " (or org-ans1 org-ans2)))
13081 (org-end-time-was-given nil)
13082 (f (org-read-date-analyze ans def defdecode))
13083 (fmts (if org-dcst
13084 org-time-stamp-custom-formats
13085 org-time-stamp-formats))
13086 (fmt (if (or with-time
13087 (and (boundp 'org-time-was-given) org-time-was-given))
13088 (cdr fmts)
13089 (car fmts)))
13090 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13091 (when (and org-end-time-was-given
13092 (string-match org-plain-time-of-day-regexp txt))
13093 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13094 org-end-time-was-given
13095 (substring txt (match-end 0)))))
13096 (when org-read-date-analyze-futurep
13097 (setq txt (concat txt " (=>F)")))
13098 (setq org-read-date-overlay
13099 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13100 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13102 (defun org-read-date-analyze (ans def defdecode)
13103 "Analyse the combined answer of the date prompt."
13104 ;; FIXME: cleanup and comment
13105 (let (delta deltan deltaw deltadef year month day
13106 hour minute second wday pm h2 m2 tl wday1
13107 iso-year iso-weekday iso-week iso-year iso-date futurep)
13108 (setq org-read-date-analyze-futurep nil)
13109 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13110 (setq ans "+0"))
13112 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13113 (setq ans (replace-match "" t t ans)
13114 deltan (car delta)
13115 deltaw (nth 1 delta)
13116 deltadef (nth 2 delta)))
13118 ;; Check if there is an iso week date in there
13119 ;; If yes, sore the info and postpone interpreting it until the rest
13120 ;; of the parsing is done
13121 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13122 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13123 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13124 iso-week (string-to-number (match-string 2 ans)))
13125 (setq ans (replace-match "" t t ans)))
13127 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13128 (when (string-match
13129 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13130 (setq year (if (match-end 2)
13131 (string-to-number (match-string 2 ans))
13132 (string-to-number (format-time-string "%Y")))
13133 month (string-to-number (match-string 3 ans))
13134 day (string-to-number (match-string 4 ans)))
13135 (if (< year 100) (setq year (+ 2000 year)))
13136 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13137 t nil ans)))
13138 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13139 ;; If there is a time with am/pm, and *no* time without it, we convert
13140 ;; so that matching will be successful.
13141 (loop for i from 1 to 2 do ; twice, for end time as well
13142 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13143 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13144 (setq hour (string-to-number (match-string 1 ans))
13145 minute (if (match-end 3)
13146 (string-to-number (match-string 3 ans))
13148 pm (equal ?p
13149 (string-to-char (downcase (match-string 4 ans)))))
13150 (if (and (= hour 12) (not pm))
13151 (setq hour 0)
13152 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13153 (setq ans (replace-match (format "%02d:%02d" hour minute)
13154 t t ans))))
13156 ;; Check if a time range is given as a duration
13157 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13158 (setq hour (string-to-number (match-string 1 ans))
13159 h2 (+ hour (string-to-number (match-string 3 ans)))
13160 minute (string-to-number (match-string 2 ans))
13161 m2 (+ minute (if (match-end 5) (string-to-number
13162 (match-string 5 ans))0)))
13163 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13164 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13165 t t ans)))
13167 ;; Check if there is a time range
13168 (when (boundp 'org-end-time-was-given)
13169 (setq org-time-was-given nil)
13170 (when (and (string-match org-plain-time-of-day-regexp ans)
13171 (match-end 8))
13172 (setq org-end-time-was-given (match-string 8 ans))
13173 (setq ans (concat (substring ans 0 (match-beginning 7))
13174 (substring ans (match-end 7))))))
13176 (setq tl (parse-time-string ans)
13177 day (or (nth 3 tl) (nth 3 defdecode))
13178 month (or (nth 4 tl)
13179 (if (and org-read-date-prefer-future
13180 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13181 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13182 (nth 4 defdecode)))
13183 year (or (nth 5 tl)
13184 (if (and org-read-date-prefer-future
13185 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13186 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13187 (nth 5 defdecode)))
13188 hour (or (nth 2 tl) (nth 2 defdecode))
13189 minute (or (nth 1 tl) (nth 1 defdecode))
13190 second (or (nth 0 tl) 0)
13191 wday (nth 6 tl))
13193 (when (and (eq org-read-date-prefer-future 'time)
13194 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13195 (equal day (nth 3 defdecode))
13196 (equal month (nth 4 defdecode))
13197 (equal year (nth 5 defdecode))
13198 (nth 2 tl)
13199 (or (< (nth 2 tl) (nth 2 defdecode))
13200 (and (= (nth 2 tl) (nth 2 defdecode))
13201 (nth 1 tl)
13202 (< (nth 1 tl) (nth 1 defdecode)))))
13203 (setq day (1+ day)
13204 futurep t))
13206 ;; Special date definitions below
13207 (cond
13208 (iso-week
13209 ;; There was an iso week
13210 (setq futurep nil)
13211 (setq year (or iso-year year)
13212 day (or iso-weekday wday 1)
13213 wday nil ; to make sure that the trigger below does not match
13214 iso-date (calendar-gregorian-from-absolute
13215 (calendar-absolute-from-iso
13216 (list iso-week day year))))
13217 ; FIXME: Should we also push ISO weeks into the future?
13218 ; (when (and org-read-date-prefer-future
13219 ; (not iso-year)
13220 ; (< (calendar-absolute-from-gregorian iso-date)
13221 ; (time-to-days (current-time))))
13222 ; (setq year (1+ year)
13223 ; iso-date (calendar-gregorian-from-absolute
13224 ; (calendar-absolute-from-iso
13225 ; (list iso-week day year)))))
13226 (setq month (car iso-date)
13227 year (nth 2 iso-date)
13228 day (nth 1 iso-date)))
13229 (deltan
13230 (setq futurep nil)
13231 (unless deltadef
13232 (let ((now (decode-time (current-time))))
13233 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13234 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13235 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13236 ((equal deltaw "m") (setq month (+ month deltan)))
13237 ((equal deltaw "y") (setq year (+ year deltan)))))
13238 ((and wday (not (nth 3 tl)))
13239 (setq futurep nil)
13240 ;; Weekday was given, but no day, so pick that day in the week
13241 ;; on or after the derived date.
13242 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13243 (unless (equal wday wday1)
13244 (setq day (+ day (% (- wday wday1 -7) 7))))))
13245 (if (and (boundp 'org-time-was-given)
13246 (nth 2 tl))
13247 (setq org-time-was-given t))
13248 (if (< year 100) (setq year (+ 2000 year)))
13249 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13250 (setq org-read-date-analyze-futurep futurep)
13251 (list second minute hour day month year)))
13253 (defvar parse-time-weekdays)
13255 (defun org-read-date-get-relative (s today default)
13256 "Check string S for special relative date string.
13257 TODAY and DEFAULT are internal times, for today and for a default.
13258 Return shift list (N what def-flag)
13259 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13260 N is the number of WHATs to shift.
13261 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13262 the DEFAULT date rather than TODAY."
13263 (when (and
13264 (string-match
13265 (concat
13266 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13267 "\\([0-9]+\\)?"
13268 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13269 "\\([ \t]\\|$\\)") s)
13270 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13271 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13272 (string-to-char (substring (match-string 1 s) -1))
13273 ?+))
13274 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13275 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13276 (what (if (match-end 3) (match-string 3 s) "d"))
13277 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13278 (date (if rel default today))
13279 (wday (nth 6 (decode-time date)))
13280 delta)
13281 (if wday1
13282 (progn
13283 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13284 (if (= dir ?-) (setq delta (- delta 7)))
13285 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13286 (list delta "d" rel))
13287 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13289 (defun org-eval-in-calendar (form &optional keepdate)
13290 "Eval FORM in the calendar window and return to current window.
13291 Also, store the cursor date in variable org-ans2."
13292 (let ((sf (selected-frame))
13293 (sw (selected-window)))
13294 (select-window (get-buffer-window "*Calendar*" t))
13295 (eval form)
13296 (when (and (not keepdate) (calendar-cursor-to-date))
13297 (let* ((date (calendar-cursor-to-date))
13298 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13299 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13300 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13301 (select-window sw)
13302 (org-select-frame-set-input-focus sf)))
13304 (defun org-calendar-select ()
13305 "Return to `org-read-date' with the date currently selected.
13306 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13307 (interactive)
13308 (when (calendar-cursor-to-date)
13309 (let* ((date (calendar-cursor-to-date))
13310 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13311 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13312 (if (active-minibuffer-window) (exit-minibuffer))))
13314 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13315 "Insert a date stamp for the date given by the internal TIME.
13316 WITH-HM means, use the stamp format that includes the time of the day.
13317 INACTIVE means use square brackets instead of angular ones, so that the
13318 stamp will not contribute to the agenda.
13319 PRE and POST are optional strings to be inserted before and after the
13320 stamp.
13321 The command returns the inserted time stamp."
13322 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13323 stamp)
13324 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13325 (insert-before-markers (or pre ""))
13326 (insert-before-markers (setq stamp (format-time-string fmt time)))
13327 (when (listp extra)
13328 (setq extra (car extra))
13329 (if (and (stringp extra)
13330 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13331 (setq extra (format "-%02d:%02d"
13332 (string-to-number (match-string 1 extra))
13333 (string-to-number (match-string 2 extra))))
13334 (setq extra nil)))
13335 (when extra
13336 (backward-char 1)
13337 (insert-before-markers extra)
13338 (forward-char 1))
13339 (insert-before-markers (or post ""))
13340 (setq org-last-inserted-timestamp stamp)))
13342 (defun org-toggle-time-stamp-overlays ()
13343 "Toggle the use of custom time stamp formats."
13344 (interactive)
13345 (setq org-display-custom-times (not org-display-custom-times))
13346 (unless org-display-custom-times
13347 (let ((p (point-min)) (bmp (buffer-modified-p)))
13348 (while (setq p (next-single-property-change p 'display))
13349 (if (and (get-text-property p 'display)
13350 (eq (get-text-property p 'face) 'org-date))
13351 (remove-text-properties
13352 p (setq p (next-single-property-change p 'display))
13353 '(display t))))
13354 (set-buffer-modified-p bmp)))
13355 (if (featurep 'xemacs)
13356 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13357 (org-restart-font-lock)
13358 (setq org-table-may-need-update t)
13359 (if org-display-custom-times
13360 (message "Time stamps are overlayed with custom format")
13361 (message "Time stamp overlays removed")))
13363 (defun org-display-custom-time (beg end)
13364 "Overlay modified time stamp format over timestamp between BEG and END."
13365 (let* ((ts (buffer-substring beg end))
13366 t1 w1 with-hm tf time str w2 (off 0))
13367 (save-match-data
13368 (setq t1 (org-parse-time-string ts t))
13369 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13370 (setq off (- (match-end 0) (match-beginning 0)))))
13371 (setq end (- end off))
13372 (setq w1 (- end beg)
13373 with-hm (and (nth 1 t1) (nth 2 t1))
13374 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13375 time (org-fix-decoded-time t1)
13376 str (org-add-props
13377 (format-time-string
13378 (substring tf 1 -1) (apply 'encode-time time))
13379 nil 'mouse-face 'highlight)
13380 w2 (length str))
13381 (if (not (= w2 w1))
13382 (add-text-properties (1+ beg) (+ 2 beg)
13383 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13384 (if (featurep 'xemacs)
13385 (progn
13386 (put-text-property beg end 'invisible t)
13387 (put-text-property beg end 'end-glyph (make-glyph str)))
13388 (put-text-property beg end 'display str))))
13390 (defun org-translate-time (string)
13391 "Translate all timestamps in STRING to custom format.
13392 But do this only if the variable `org-display-custom-times' is set."
13393 (when org-display-custom-times
13394 (save-match-data
13395 (let* ((start 0)
13396 (re org-ts-regexp-both)
13397 t1 with-hm inactive tf time str beg end)
13398 (while (setq start (string-match re string start))
13399 (setq beg (match-beginning 0)
13400 end (match-end 0)
13401 t1 (save-match-data
13402 (org-parse-time-string (substring string beg end) t))
13403 with-hm (and (nth 1 t1) (nth 2 t1))
13404 inactive (equal (substring string beg (1+ beg)) "[")
13405 tf (funcall (if with-hm 'cdr 'car)
13406 org-time-stamp-custom-formats)
13407 time (org-fix-decoded-time t1)
13408 str (format-time-string
13409 (concat
13410 (if inactive "[" "<") (substring tf 1 -1)
13411 (if inactive "]" ">"))
13412 (apply 'encode-time time))
13413 string (replace-match str t t string)
13414 start (+ start (length str)))))))
13415 string)
13417 (defun org-fix-decoded-time (time)
13418 "Set 0 instead of nil for the first 6 elements of time.
13419 Don't touch the rest."
13420 (let ((n 0))
13421 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13423 (defun org-days-to-time (timestamp-string)
13424 "Difference between TIMESTAMP-STRING and now in days."
13425 (- (time-to-days (org-time-string-to-time timestamp-string))
13426 (time-to-days (current-time))))
13428 (defun org-deadline-close (timestamp-string &optional ndays)
13429 "Is the time in TIMESTAMP-STRING close to the current date?"
13430 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13431 (and (< (org-days-to-time timestamp-string) ndays)
13432 (not (org-entry-is-done-p))))
13434 (defun org-get-wdays (ts)
13435 "Get the deadline lead time appropriate for timestring TS."
13436 (cond
13437 ((<= org-deadline-warning-days 0)
13438 ;; 0 or negative, enforce this value no matter what
13439 (- org-deadline-warning-days))
13440 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13441 ;; lead time is specified.
13442 (floor (* (string-to-number (match-string 1 ts))
13443 (cdr (assoc (match-string 2 ts)
13444 '(("d" . 1) ("w" . 7)
13445 ("m" . 30.4) ("y" . 365.25)))))))
13446 ;; go for the default.
13447 (t org-deadline-warning-days)))
13449 (defun org-calendar-select-mouse (ev)
13450 "Return to `org-read-date' with the date currently selected.
13451 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13452 (interactive "e")
13453 (mouse-set-point ev)
13454 (when (calendar-cursor-to-date)
13455 (let* ((date (calendar-cursor-to-date))
13456 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13457 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13458 (if (active-minibuffer-window) (exit-minibuffer))))
13460 (defun org-check-deadlines (ndays)
13461 "Check if there are any deadlines due or past due.
13462 A deadline is considered due if it happens within `org-deadline-warning-days'
13463 days from today's date. If the deadline appears in an entry marked DONE,
13464 it is not shown. The prefix arg NDAYS can be used to test that many
13465 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13466 (interactive "P")
13467 (let* ((org-warn-days
13468 (cond
13469 ((equal ndays '(4)) 100000)
13470 (ndays (prefix-numeric-value ndays))
13471 (t (abs org-deadline-warning-days))))
13472 (case-fold-search nil)
13473 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13474 (callback
13475 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13477 (message "%d deadlines past-due or due within %d days"
13478 (org-occur regexp nil callback)
13479 org-warn-days)))
13481 (defun org-check-before-date (date)
13482 "Check if there are deadlines or scheduled entries before DATE."
13483 (interactive (list (org-read-date)))
13484 (let ((case-fold-search nil)
13485 (regexp (concat "\\<\\(" org-deadline-string
13486 "\\|" org-scheduled-string
13487 "\\) *<\\([^>]+\\)>"))
13488 (callback
13489 (lambda () (time-less-p
13490 (org-time-string-to-time (match-string 2))
13491 (org-time-string-to-time date)))))
13492 (message "%d entries before %s"
13493 (org-occur regexp nil callback) date)))
13495 (defun org-check-after-date (date)
13496 "Check if there are deadlines or scheduled entries after DATE."
13497 (interactive (list (org-read-date)))
13498 (let ((case-fold-search nil)
13499 (regexp (concat "\\<\\(" org-deadline-string
13500 "\\|" org-scheduled-string
13501 "\\) *<\\([^>]+\\)>"))
13502 (callback
13503 (lambda () (not
13504 (time-less-p
13505 (org-time-string-to-time (match-string 2))
13506 (org-time-string-to-time date))))))
13507 (message "%d entries after %s"
13508 (org-occur regexp nil callback) date)))
13510 (defun org-evaluate-time-range (&optional to-buffer)
13511 "Evaluate a time range by computing the difference between start and end.
13512 Normally the result is just printed in the echo area, but with prefix arg
13513 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13514 If the time range is actually in a table, the result is inserted into the
13515 next column.
13516 For time difference computation, a year is assumed to be exactly 365
13517 days in order to avoid rounding problems."
13518 (interactive "P")
13520 (org-clock-update-time-maybe)
13521 (save-excursion
13522 (unless (org-at-date-range-p t)
13523 (goto-char (point-at-bol))
13524 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13525 (if (not (org-at-date-range-p t))
13526 (error "Not at a time-stamp range, and none found in current line")))
13527 (let* ((ts1 (match-string 1))
13528 (ts2 (match-string 2))
13529 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13530 (match-end (match-end 0))
13531 (time1 (org-time-string-to-time ts1))
13532 (time2 (org-time-string-to-time ts2))
13533 (t1 (org-float-time time1))
13534 (t2 (org-float-time time2))
13535 (diff (abs (- t2 t1)))
13536 (negative (< (- t2 t1) 0))
13537 ;; (ys (floor (* 365 24 60 60)))
13538 (ds (* 24 60 60))
13539 (hs (* 60 60))
13540 (fy "%dy %dd %02d:%02d")
13541 (fy1 "%dy %dd")
13542 (fd "%dd %02d:%02d")
13543 (fd1 "%dd")
13544 (fh "%02d:%02d")
13545 y d h m align)
13546 (if havetime
13547 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13549 d (floor (/ diff ds)) diff (mod diff ds)
13550 h (floor (/ diff hs)) diff (mod diff hs)
13551 m (floor (/ diff 60)))
13552 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13554 d (floor (+ (/ diff ds) 0.5))
13555 h 0 m 0))
13556 (if (not to-buffer)
13557 (message "%s" (org-make-tdiff-string y d h m))
13558 (if (org-at-table-p)
13559 (progn
13560 (goto-char match-end)
13561 (setq align t)
13562 (and (looking-at " *|") (goto-char (match-end 0))))
13563 (goto-char match-end))
13564 (if (looking-at
13565 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13566 (replace-match ""))
13567 (if negative (insert " -"))
13568 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13569 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13570 (insert " " (format fh h m))))
13571 (if align (org-table-align))
13572 (message "Time difference inserted")))))
13574 (defun org-make-tdiff-string (y d h m)
13575 (let ((fmt "")
13576 (l nil))
13577 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13578 l (push y l)))
13579 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13580 l (push d l)))
13581 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13582 l (push h l)))
13583 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13584 l (push m l)))
13585 (apply 'format fmt (nreverse l))))
13587 (defun org-time-string-to-time (s)
13588 (apply 'encode-time (org-parse-time-string s)))
13589 (defun org-time-string-to-seconds (s)
13590 (org-float-time (org-time-string-to-time s)))
13592 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13593 "Convert a time stamp to an absolute day number.
13594 If there is a specifyer for a cyclic time stamp, get the closest date to
13595 DAYNR.
13596 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13597 the variable date is bound by the calendar when this is called."
13598 (cond
13599 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13600 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13601 daynr
13602 (+ daynr 1000)))
13603 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13604 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13605 (time-to-days (current-time))) (match-string 0 s)
13606 prefer show-all))
13607 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13609 (defun org-days-to-iso-week (days)
13610 "Return the iso week number."
13611 (require 'cal-iso)
13612 (car (calendar-iso-from-absolute days)))
13614 (defun org-small-year-to-year (year)
13615 "Convert 2-digit years into 4-digit years.
13616 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13617 The year 2000 cannot be abbreviated. Any year larger than 99
13618 is returned unchanged."
13619 (if (< year 38)
13620 (setq year (+ 2000 year))
13621 (if (< year 100)
13622 (setq year (+ 1900 year))))
13623 year)
13625 (defun org-time-from-absolute (d)
13626 "Return the time corresponding to date D.
13627 D may be an absolute day number, or a calendar-type list (month day year)."
13628 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13629 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13631 (defun org-calendar-holiday ()
13632 "List of holidays, for Diary display in Org-mode."
13633 (require 'holidays)
13634 (let ((hl (funcall
13635 (if (fboundp 'calendar-check-holidays)
13636 'calendar-check-holidays 'check-calendar-holidays) date)))
13637 (if hl (mapconcat 'identity hl "; "))))
13639 (defun org-diary-sexp-entry (sexp entry date)
13640 "Process a SEXP diary ENTRY for DATE."
13641 (require 'diary-lib)
13642 (let ((result (if calendar-debug-sexp
13643 (let ((stack-trace-on-error t))
13644 (eval (car (read-from-string sexp))))
13645 (condition-case nil
13646 (eval (car (read-from-string sexp)))
13647 (error
13648 (beep)
13649 (message "Bad sexp at line %d in %s: %s"
13650 (org-current-line)
13651 (buffer-file-name) sexp)
13652 (sleep-for 2))))))
13653 (cond ((stringp result) result)
13654 ((and (consp result)
13655 (stringp (cdr result))) (cdr result))
13656 (result entry)
13657 (t nil))))
13659 (defun org-diary-to-ical-string (frombuf)
13660 "Get iCalendar entries from diary entries in buffer FROMBUF.
13661 This uses the icalendar.el library."
13662 (let* ((tmpdir (if (featurep 'xemacs)
13663 (temp-directory)
13664 temporary-file-directory))
13665 (tmpfile (make-temp-name
13666 (expand-file-name "orgics" tmpdir)))
13667 buf rtn b e)
13668 (with-current-buffer frombuf
13669 (icalendar-export-region (point-min) (point-max) tmpfile)
13670 (setq buf (find-buffer-visiting tmpfile))
13671 (set-buffer buf)
13672 (goto-char (point-min))
13673 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13674 (setq b (match-beginning 0)))
13675 (goto-char (point-max))
13676 (if (re-search-backward "^END:VEVENT" nil t)
13677 (setq e (match-end 0)))
13678 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13679 (kill-buffer buf)
13680 (delete-file tmpfile)
13681 rtn))
13683 (defun org-closest-date (start current change prefer show-all)
13684 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13685 When PREFER is `past' return a date that is either CURRENT or past.
13686 When PREFER is `future', return a date that is either CURRENT or future.
13687 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13688 ;; Make the proper lists from the dates
13689 (catch 'exit
13690 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13691 dn dw sday cday n1 n2 n0
13692 d m y y1 y2 date1 date2 nmonths nm ny m2)
13694 (setq start (org-date-to-gregorian start)
13695 current (org-date-to-gregorian
13696 (if show-all
13697 current
13698 (time-to-days (current-time))))
13699 sday (calendar-absolute-from-gregorian start)
13700 cday (calendar-absolute-from-gregorian current))
13702 (if (<= cday sday) (throw 'exit sday))
13704 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13705 (setq dn (string-to-number (match-string 1 change))
13706 dw (cdr (assoc (match-string 2 change) a1)))
13707 (error "Invalid change specifyer: %s" change))
13708 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13709 (cond
13710 ((eq dw 'day)
13711 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13712 n2 (+ n1 dn)))
13713 ((eq dw 'year)
13714 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13715 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13716 (setq date1 (list m d y1)
13717 n1 (calendar-absolute-from-gregorian date1)
13718 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13719 n2 (calendar-absolute-from-gregorian date2)))
13720 ((eq dw 'month)
13721 ;; approx number of month between the two dates
13722 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13723 ;; How often does dn fit in there?
13724 (setq d (nth 1 start) m (car start) y (nth 2 start)
13725 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13726 m (+ m nm)
13727 ny (floor (/ m 12))
13728 y (+ y ny)
13729 m (- m (* ny 12)))
13730 (while (> m 12) (setq m (- m 12) y (1+ y)))
13731 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13732 (setq m2 (+ m dn) y2 y)
13733 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13734 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13735 (while (<= n2 cday)
13736 (setq n1 n2 m m2 y y2)
13737 (setq m2 (+ m dn) y2 y)
13738 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13739 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13740 ;; Make sure n1 is the earlier date
13741 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13742 (if show-all
13743 (cond
13744 ((eq prefer 'past) (if (= cday n2) n2 n1))
13745 ((eq prefer 'future) (if (= cday n1) n1 n2))
13746 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13747 (cond
13748 ((eq prefer 'past) (if (= cday n2) n2 n1))
13749 ((eq prefer 'future) (if (= cday n1) n1 n2))
13750 (t (if (= cday n1) n1 n2)))))))
13752 (defun org-date-to-gregorian (date)
13753 "Turn any specification of DATE into a gregorian date for the calendar."
13754 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13755 ((and (listp date) (= (length date) 3)) date)
13756 ((stringp date)
13757 (setq date (org-parse-time-string date))
13758 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13759 ((listp date)
13760 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13762 (defun org-parse-time-string (s &optional nodefault)
13763 "Parse the standard Org-mode time string.
13764 This should be a lot faster than the normal `parse-time-string'.
13765 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13766 hour and minute fields will be nil if not given."
13767 (if (string-match org-ts-regexp0 s)
13768 (list 0
13769 (if (or (match-beginning 8) (not nodefault))
13770 (string-to-number (or (match-string 8 s) "0")))
13771 (if (or (match-beginning 7) (not nodefault))
13772 (string-to-number (or (match-string 7 s) "0")))
13773 (string-to-number (match-string 4 s))
13774 (string-to-number (match-string 3 s))
13775 (string-to-number (match-string 2 s))
13776 nil nil nil)
13777 (error "Not a standard Org-mode time string: %s" s)))
13779 (defun org-timestamp-up (&optional arg)
13780 "Increase the date item at the cursor by one.
13781 If the cursor is on the year, change the year. If it is on the month or
13782 the day, change that.
13783 With prefix ARG, change by that many units."
13784 (interactive "p")
13785 (org-timestamp-change (prefix-numeric-value arg)))
13787 (defun org-timestamp-down (&optional arg)
13788 "Decrease the date item at the cursor by one.
13789 If the cursor is on the year, change the year. If it is on the month or
13790 the day, change that.
13791 With prefix ARG, change by that many units."
13792 (interactive "p")
13793 (org-timestamp-change (- (prefix-numeric-value arg))))
13795 (defun org-timestamp-up-day (&optional arg)
13796 "Increase the date in the time stamp by one day.
13797 With prefix ARG, change that many days."
13798 (interactive "p")
13799 (if (and (not (org-at-timestamp-p t))
13800 (org-on-heading-p))
13801 (org-todo 'up)
13802 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13804 (defun org-timestamp-down-day (&optional arg)
13805 "Decrease the date in the time stamp by one day.
13806 With prefix ARG, change that many days."
13807 (interactive "p")
13808 (if (and (not (org-at-timestamp-p t))
13809 (org-on-heading-p))
13810 (org-todo 'down)
13811 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13813 (defun org-at-timestamp-p (&optional inactive-ok)
13814 "Determine if the cursor is in or at a timestamp."
13815 (interactive)
13816 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13817 (pos (point))
13818 (ans (or (looking-at tsr)
13819 (save-excursion
13820 (skip-chars-backward "^[<\n\r\t")
13821 (if (> (point) (point-min)) (backward-char 1))
13822 (and (looking-at tsr)
13823 (> (- (match-end 0) pos) -1))))))
13824 (and ans
13825 (boundp 'org-ts-what)
13826 (setq org-ts-what
13827 (cond
13828 ((= pos (match-beginning 0)) 'bracket)
13829 ((= pos (1- (match-end 0))) 'bracket)
13830 ((org-pos-in-match-range pos 2) 'year)
13831 ((org-pos-in-match-range pos 3) 'month)
13832 ((org-pos-in-match-range pos 7) 'hour)
13833 ((org-pos-in-match-range pos 8) 'minute)
13834 ((or (org-pos-in-match-range pos 4)
13835 (org-pos-in-match-range pos 5)) 'day)
13836 ((and (> pos (or (match-end 8) (match-end 5)))
13837 (< pos (match-end 0)))
13838 (- pos (or (match-end 8) (match-end 5))))
13839 (t 'day))))
13840 ans))
13842 (defun org-toggle-timestamp-type ()
13843 "Toggle the type (<active> or [inactive]) of a time stamp."
13844 (interactive)
13845 (when (org-at-timestamp-p t)
13846 (let ((beg (match-beginning 0)) (end (match-end 0))
13847 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13848 (save-excursion
13849 (goto-char beg)
13850 (while (re-search-forward "[][<>]" end t)
13851 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13852 t t)))
13853 (message "Timestamp is now %sactive"
13854 (if (equal (char-after beg) ?<) "" "in")))))
13856 (defun org-timestamp-change (n &optional what)
13857 "Change the date in the time stamp at point.
13858 The date will be changed by N times WHAT. WHAT can be `day', `month',
13859 `year', `minute', `second'. If WHAT is not given, the cursor position
13860 in the timestamp determines what will be changed."
13861 (let ((pos (point))
13862 with-hm inactive
13863 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13864 org-ts-what
13865 extra rem
13866 ts time time0)
13867 (if (not (org-at-timestamp-p t))
13868 (error "Not at a timestamp"))
13869 (if (and (not what) (eq org-ts-what 'bracket))
13870 (org-toggle-timestamp-type)
13871 (if (and (not what) (not (eq org-ts-what 'day))
13872 org-display-custom-times
13873 (get-text-property (point) 'display)
13874 (not (get-text-property (1- (point)) 'display)))
13875 (setq org-ts-what 'day))
13876 (setq org-ts-what (or what org-ts-what)
13877 inactive (= (char-after (match-beginning 0)) ?\[)
13878 ts (match-string 0))
13879 (replace-match "")
13880 (if (string-match
13881 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13883 (setq extra (match-string 1 ts)))
13884 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13885 (setq with-hm t))
13886 (setq time0 (org-parse-time-string ts))
13887 (when (and (eq org-ts-what 'minute)
13888 (eq current-prefix-arg nil))
13889 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13890 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13891 (setcar (cdr time0) (+ (nth 1 time0)
13892 (if (> n 0) (- rem) (- dm rem))))))
13893 (setq time
13894 (encode-time (or (car time0) 0)
13895 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13896 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13897 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13898 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13899 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13900 (nthcdr 6 time0)))
13901 (when (and (member org-ts-what '(hour minute))
13902 extra
13903 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13904 (setq extra (org-modify-ts-extra
13905 extra
13906 (if (eq org-ts-what 'hour) 2 5)
13907 n dm)))
13908 (when (integerp org-ts-what)
13909 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13910 (if (eq what 'calendar)
13911 (let ((cal-date (org-get-date-from-calendar)))
13912 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13913 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13914 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13915 (setcar time0 (or (car time0) 0))
13916 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13917 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13918 (setq time (apply 'encode-time time0))))
13919 (setq org-last-changed-timestamp
13920 (org-insert-time-stamp time with-hm inactive nil nil extra))
13921 (org-clock-update-time-maybe)
13922 (goto-char pos)
13923 ;; Try to recenter the calendar window, if any
13924 (if (and org-calendar-follow-timestamp-change
13925 (get-buffer-window "*Calendar*" t)
13926 (memq org-ts-what '(day month year)))
13927 (org-recenter-calendar (time-to-days time))))))
13929 (defun org-modify-ts-extra (s pos n dm)
13930 "Change the different parts of the lead-time and repeat fields in timestamp."
13931 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13932 ng h m new rem)
13933 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13934 (cond
13935 ((or (org-pos-in-match-range pos 2)
13936 (org-pos-in-match-range pos 3))
13937 (setq m (string-to-number (match-string 3 s))
13938 h (string-to-number (match-string 2 s)))
13939 (if (org-pos-in-match-range pos 2)
13940 (setq h (+ h n))
13941 (setq n (* dm (org-no-warnings (signum n))))
13942 (when (not (= 0 (setq rem (% m dm))))
13943 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13944 (setq m (+ m n)))
13945 (if (< m 0) (setq m (+ m 60) h (1- h)))
13946 (if (> m 59) (setq m (- m 60) h (1+ h)))
13947 (setq h (min 24 (max 0 h)))
13948 (setq ng 1 new (format "-%02d:%02d" h m)))
13949 ((org-pos-in-match-range pos 6)
13950 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13951 ((org-pos-in-match-range pos 5)
13952 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13954 ((org-pos-in-match-range pos 9)
13955 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13956 ((org-pos-in-match-range pos 8)
13957 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13959 (when ng
13960 (setq s (concat
13961 (substring s 0 (match-beginning ng))
13963 (substring s (match-end ng))))))
13966 (defun org-recenter-calendar (date)
13967 "If the calendar is visible, recenter it to DATE."
13968 (let* ((win (selected-window))
13969 (cwin (get-buffer-window "*Calendar*" t))
13970 (calendar-move-hook nil))
13971 (when cwin
13972 (select-window cwin)
13973 (calendar-goto-date (if (listp date) date
13974 (calendar-gregorian-from-absolute date)))
13975 (select-window win))))
13977 (defun org-goto-calendar (&optional arg)
13978 "Go to the Emacs calendar at the current date.
13979 If there is a time stamp in the current line, go to that date.
13980 A prefix ARG can be used to force the current date."
13981 (interactive "P")
13982 (let ((tsr org-ts-regexp) diff
13983 (calendar-move-hook nil)
13984 (calendar-view-holidays-initially-flag nil)
13985 (view-calendar-holidays-initially nil)
13986 (calendar-view-diary-initially-flag nil)
13987 (view-diary-entries-initially nil))
13988 (if (or (org-at-timestamp-p)
13989 (save-excursion
13990 (beginning-of-line 1)
13991 (looking-at (concat ".*" tsr))))
13992 (let ((d1 (time-to-days (current-time)))
13993 (d2 (time-to-days
13994 (org-time-string-to-time (match-string 1)))))
13995 (setq diff (- d2 d1))))
13996 (calendar)
13997 (calendar-goto-today)
13998 (if (and diff (not arg)) (calendar-forward-day diff))))
14000 (defun org-get-date-from-calendar ()
14001 "Return a list (month day year) of date at point in calendar."
14002 (with-current-buffer "*Calendar*"
14003 (save-match-data
14004 (calendar-cursor-to-date))))
14006 (defun org-date-from-calendar ()
14007 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14008 If there is already a time stamp at the cursor position, update it."
14009 (interactive)
14010 (if (org-at-timestamp-p t)
14011 (org-timestamp-change 0 'calendar)
14012 (let ((cal-date (org-get-date-from-calendar)))
14013 (org-insert-time-stamp
14014 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14016 (defun org-minutes-to-hh:mm-string (m)
14017 "Compute H:MM from a number of minutes."
14018 (let ((h (/ m 60)))
14019 (setq m (- m (* 60 h)))
14020 (format org-time-clocksum-format h m)))
14022 (defun org-hh:mm-string-to-minutes (s)
14023 "Convert a string H:MM to a number of minutes.
14024 If the string is just a number, interpret it as minutes.
14025 In fact, the first hh:mm or number in the string will be taken,
14026 there can be extra stuff in the string.
14027 If no number is found, the return value is 0."
14028 (cond
14029 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14030 (+ (* (string-to-number (match-string 1 s)) 60)
14031 (string-to-number (match-string 2 s))))
14032 ((string-match "\\([0-9]+\\)" s)
14033 (string-to-number (match-string 1 s)))
14034 (t 0)))
14036 ;;;; Files
14038 (defun org-save-all-org-buffers ()
14039 "Save all Org-mode buffers without user confirmation."
14040 (interactive)
14041 (message "Saving all Org-mode buffers...")
14042 (save-some-buffers t 'org-mode-p)
14043 (when (featurep 'org-id) (org-id-locations-save))
14044 (message "Saving all Org-mode buffers... done"))
14046 (defun org-revert-all-org-buffers ()
14047 "Revert all Org-mode buffers.
14048 Prompt for confirmation when there are unsaved changes.
14049 Be sure you know what you are doing before letting this function
14050 overwrite your changes.
14052 This function is useful in a setup where one tracks org files
14053 with a version control system, to revert on one machine after pulling
14054 changes from another. I believe the procedure must be like this:
14056 1. M-x org-save-all-org-buffers
14057 2. Pull changes from the other machine, resolve conflicts
14058 3. M-x org-revert-all-org-buffers"
14059 (interactive)
14060 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14061 (error "Abort"))
14062 (save-excursion
14063 (save-window-excursion
14064 (mapc
14065 (lambda (b)
14066 (when (and (with-current-buffer b (org-mode-p))
14067 (with-current-buffer b buffer-file-name))
14068 (switch-to-buffer b)
14069 (revert-buffer t 'no-confirm)))
14070 (buffer-list))
14071 (when (and (featurep 'org-id) org-id-track-globally)
14072 (org-id-locations-load)))))
14074 ;;;; Agenda files
14076 ;;;###autoload
14077 (defun org-iswitchb (&optional arg)
14078 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14079 With a prefix argument, restrict available to files.
14080 With two prefix arguments, restrict available buffers to agenda files."
14081 (interactive "P")
14082 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14083 ((equal arg '(16)) (org-buffer-list 'agenda))
14084 (t (org-buffer-list)))))
14085 (switch-to-buffer
14086 (org-icompleting-read "Org buffer: "
14087 (mapcar 'list (mapcar 'buffer-name blist))
14088 nil t))))
14090 ;;;###autoload
14091 (defalias 'org-ido-switchb 'org-iswitchb)
14093 (defun org-buffer-list (&optional predicate exclude-tmp)
14094 "Return a list of Org buffers.
14095 PREDICATE can be `export', `files' or `agenda'.
14097 export restrict the list to Export buffers.
14098 files restrict the list to buffers visiting Org files.
14099 agenda restrict the list to buffers visiting agenda files.
14101 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14102 (let* ((bfn nil)
14103 (agenda-files (and (eq predicate 'agenda)
14104 (mapcar 'file-truename (org-agenda-files t))))
14105 (filter
14106 (cond
14107 ((eq predicate 'files)
14108 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14109 ((eq predicate 'export)
14110 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14111 ((eq predicate 'agenda)
14112 (lambda (b)
14113 (with-current-buffer b
14114 (and (eq major-mode 'org-mode)
14115 (setq bfn (buffer-file-name b))
14116 (member (file-truename bfn) agenda-files)))))
14117 (t (lambda (b) (with-current-buffer b
14118 (or (eq major-mode 'org-mode)
14119 (string-match "\*Org .*Export"
14120 (buffer-name b)))))))))
14121 (delq nil
14122 (mapcar
14123 (lambda(b)
14124 (if (and (funcall filter b)
14125 (or (not exclude-tmp)
14126 (not (string-match "tmp" (buffer-name b)))))
14128 nil))
14129 (buffer-list)))))
14131 (defun org-agenda-files (&optional unrestricted archives)
14132 "Get the list of agenda files.
14133 Optional UNRESTRICTED means return the full list even if a restriction
14134 is currently in place.
14135 When ARCHIVES is t, include all archive files hat are really being
14136 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14137 `org-agenda-archives-mode' is t."
14138 (let ((files
14139 (cond
14140 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14141 ((stringp org-agenda-files) (org-read-agenda-file-list))
14142 ((listp org-agenda-files) org-agenda-files)
14143 (t (error "Invalid value of `org-agenda-files'")))))
14144 (setq files (apply 'append
14145 (mapcar (lambda (f)
14146 (if (file-directory-p f)
14147 (directory-files
14148 f t org-agenda-file-regexp)
14149 (list f)))
14150 files)))
14151 (when org-agenda-skip-unavailable-files
14152 (setq files (delq nil
14153 (mapcar (function
14154 (lambda (file)
14155 (and (file-readable-p file) file)))
14156 files))))
14157 (when (or (eq archives t)
14158 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14159 (setq files (org-add-archive-files files)))
14160 files))
14162 (defun org-edit-agenda-file-list ()
14163 "Edit the list of agenda files.
14164 Depending on setup, this either uses customize to edit the variable
14165 `org-agenda-files', or it visits the file that is holding the list. In the
14166 latter case, the buffer is set up in a way that saving it automatically kills
14167 the buffer and restores the previous window configuration."
14168 (interactive)
14169 (if (stringp org-agenda-files)
14170 (let ((cw (current-window-configuration)))
14171 (find-file org-agenda-files)
14172 (org-set-local 'org-window-configuration cw)
14173 (org-add-hook 'after-save-hook
14174 (lambda ()
14175 (set-window-configuration
14176 (prog1 org-window-configuration
14177 (kill-buffer (current-buffer))))
14178 (org-install-agenda-files-menu)
14179 (message "New agenda file list installed"))
14180 nil 'local)
14181 (message "%s" (substitute-command-keys
14182 "Edit list and finish with \\[save-buffer]")))
14183 (customize-variable 'org-agenda-files)))
14185 (defun org-store-new-agenda-file-list (list)
14186 "Set new value for the agenda file list and save it correctly."
14187 (if (stringp org-agenda-files)
14188 (let ((f org-agenda-files) b)
14189 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14190 (with-temp-file f
14191 (insert (mapconcat 'identity list "\n") "\n")))
14192 (let ((org-mode-hook nil) (org-inhibit-startup t)
14193 (org-insert-mode-line-in-empty-file nil))
14194 (setq org-agenda-files list)
14195 (customize-save-variable 'org-agenda-files org-agenda-files))))
14197 (defun org-read-agenda-file-list ()
14198 "Read the list of agenda files from a file."
14199 (when (file-directory-p org-agenda-files)
14200 (error "`org-agenda-files' cannot be a single directory"))
14201 (when (stringp org-agenda-files)
14202 (with-temp-buffer
14203 (insert-file-contents org-agenda-files)
14204 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14207 ;;;###autoload
14208 (defun org-cycle-agenda-files ()
14209 "Cycle through the files in `org-agenda-files'.
14210 If the current buffer visits an agenda file, find the next one in the list.
14211 If the current buffer does not, find the first agenda file."
14212 (interactive)
14213 (let* ((fs (org-agenda-files t))
14214 (files (append fs (list (car fs))))
14215 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14216 file)
14217 (unless files (error "No agenda files"))
14218 (catch 'exit
14219 (while (setq file (pop files))
14220 (if (equal (file-truename file) tcf)
14221 (when (car files)
14222 (find-file (car files))
14223 (throw 'exit t))))
14224 (find-file (car fs)))
14225 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14227 (defun org-agenda-file-to-front (&optional to-end)
14228 "Move/add the current file to the top of the agenda file list.
14229 If the file is not present in the list, it is added to the front. If it is
14230 present, it is moved there. With optional argument TO-END, add/move to the
14231 end of the list."
14232 (interactive "P")
14233 (let ((org-agenda-skip-unavailable-files nil)
14234 (file-alist (mapcar (lambda (x)
14235 (cons (file-truename x) x))
14236 (org-agenda-files t)))
14237 (ctf (file-truename buffer-file-name))
14238 x had)
14239 (setq x (assoc ctf file-alist) had x)
14241 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14242 (if to-end
14243 (setq file-alist (append (delq x file-alist) (list x)))
14244 (setq file-alist (cons x (delq x file-alist))))
14245 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14246 (org-install-agenda-files-menu)
14247 (message "File %s to %s of agenda file list"
14248 (if had "moved" "added") (if to-end "end" "front"))))
14250 (defun org-remove-file (&optional file)
14251 "Remove current file from the list of files in variable `org-agenda-files'.
14252 These are the files which are being checked for agenda entries.
14253 Optional argument FILE means, use this file instead of the current."
14254 (interactive)
14255 (let* ((org-agenda-skip-unavailable-files nil)
14256 (file (or file buffer-file-name))
14257 (true-file (file-truename file))
14258 (afile (abbreviate-file-name file))
14259 (files (delq nil (mapcar
14260 (lambda (x)
14261 (if (equal true-file
14262 (file-truename x))
14263 nil x))
14264 (org-agenda-files t)))))
14265 (if (not (= (length files) (length (org-agenda-files t))))
14266 (progn
14267 (org-store-new-agenda-file-list files)
14268 (org-install-agenda-files-menu)
14269 (message "Removed file: %s" afile))
14270 (message "File was not in list: %s (not removed)" afile))))
14272 (defun org-file-menu-entry (file)
14273 (vector file (list 'find-file file) t))
14275 (defun org-check-agenda-file (file)
14276 "Make sure FILE exists. If not, ask user what to do."
14277 (when (not (file-exists-p file))
14278 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14279 (abbreviate-file-name file))
14280 (let ((r (downcase (read-char-exclusive))))
14281 (cond
14282 ((equal r ?r)
14283 (org-remove-file file)
14284 (throw 'nextfile t))
14285 (t (error "Abort"))))))
14287 (defun org-get-agenda-file-buffer (file)
14288 "Get a buffer visiting FILE. If the buffer needs to be created, add
14289 it to the list of buffers which might be released later."
14290 (let ((buf (org-find-base-buffer-visiting file)))
14291 (if buf
14292 buf ; just return it
14293 ;; Make a new buffer and remember it
14294 (setq buf (find-file-noselect file))
14295 (if buf (push buf org-agenda-new-buffers))
14296 buf)))
14298 (defun org-release-buffers (blist)
14299 "Release all buffers in list, asking the user for confirmation when needed.
14300 When a buffer is unmodified, it is just killed. When modified, it is saved
14301 \(if the user agrees) and then killed."
14302 (let (buf file)
14303 (while (setq buf (pop blist))
14304 (setq file (buffer-file-name buf))
14305 (when (and (buffer-modified-p buf)
14306 file
14307 (y-or-n-p (format "Save file %s? " file)))
14308 (with-current-buffer buf (save-buffer)))
14309 (kill-buffer buf))))
14311 (defun org-prepare-agenda-buffers (files)
14312 "Create buffers for all agenda files, protect archived trees and comments."
14313 (interactive)
14314 (let ((pa '(:org-archived t))
14315 (pc '(:org-comment t))
14316 (pall '(:org-archived t :org-comment t))
14317 (inhibit-read-only t)
14318 (rea (concat ":" org-archive-tag ":"))
14319 bmp file re)
14320 (save-excursion
14321 (save-restriction
14322 (while (setq file (pop files))
14323 (catch 'nextfile
14324 (if (bufferp file)
14325 (set-buffer file)
14326 (org-check-agenda-file file)
14327 (set-buffer (org-get-agenda-file-buffer file)))
14328 (widen)
14329 (setq bmp (buffer-modified-p))
14330 (org-refresh-category-properties)
14331 (setq org-todo-keywords-for-agenda
14332 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14333 (setq org-done-keywords-for-agenda
14334 (append org-done-keywords-for-agenda org-done-keywords))
14335 (setq org-todo-keyword-alist-for-agenda
14336 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14337 (setq org-drawers-for-agenda
14338 (append org-drawers-for-agenda org-drawers))
14339 (setq org-tag-alist-for-agenda
14340 (append org-tag-alist-for-agenda org-tag-alist))
14342 (save-excursion
14343 (remove-text-properties (point-min) (point-max) pall)
14344 (when org-agenda-skip-archived-trees
14345 (goto-char (point-min))
14346 (while (re-search-forward rea nil t)
14347 (if (org-on-heading-p t)
14348 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14349 (goto-char (point-min))
14350 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14351 (while (re-search-forward re nil t)
14352 (add-text-properties
14353 (match-beginning 0) (org-end-of-subtree t) pc)))
14354 (set-buffer-modified-p bmp)))))
14355 (setq org-todo-keyword-alist-for-agenda
14356 (org-uniquify org-todo-keyword-alist-for-agenda)
14357 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14359 ;;;; Embedded LaTeX
14361 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14362 "Keymap for the minor `org-cdlatex-mode'.")
14364 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14365 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14366 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14367 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14368 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14370 (defvar org-cdlatex-texmathp-advice-is-done nil
14371 "Flag remembering if we have applied the advice to texmathp already.")
14373 (define-minor-mode org-cdlatex-mode
14374 "Toggle the minor `org-cdlatex-mode'.
14375 This mode supports entering LaTeX environment and math in LaTeX fragments
14376 in Org-mode.
14377 \\{org-cdlatex-mode-map}"
14378 nil " OCDL" nil
14379 (when org-cdlatex-mode (require 'cdlatex))
14380 (unless org-cdlatex-texmathp-advice-is-done
14381 (setq org-cdlatex-texmathp-advice-is-done t)
14382 (defadvice texmathp (around org-math-always-on activate)
14383 "Always return t in org-mode buffers.
14384 This is because we want to insert math symbols without dollars even outside
14385 the LaTeX math segments. If Orgmode thinks that point is actually inside
14386 an embedded LaTeX fragment, let texmathp do its job.
14387 \\[org-cdlatex-mode-map]"
14388 (interactive)
14389 (let (p)
14390 (cond
14391 ((not (org-mode-p)) ad-do-it)
14392 ((eq this-command 'cdlatex-math-symbol)
14393 (setq ad-return-value t
14394 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14396 (let ((p (org-inside-LaTeX-fragment-p)))
14397 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14398 (setq ad-return-value t
14399 texmathp-why '("Org-mode embedded math" . 0))
14400 (if p ad-do-it)))))))))
14402 (defun turn-on-org-cdlatex ()
14403 "Unconditionally turn on `org-cdlatex-mode'."
14404 (org-cdlatex-mode 1))
14406 (defun org-inside-LaTeX-fragment-p ()
14407 "Test if point is inside a LaTeX fragment.
14408 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14409 sequence appearing also before point.
14410 Even though the matchers for math are configurable, this function assumes
14411 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14412 delimiters are skipped when they have been removed by customization.
14413 The return value is nil, or a cons cell with the delimiter and
14414 and the position of this delimiter.
14416 This function does a reasonably good job, but can locally be fooled by
14417 for example currency specifications. For example it will assume being in
14418 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14419 fragments that are properly closed, but during editing, we have to live
14420 with the uncertainty caused by missing closing delimiters. This function
14421 looks only before point, not after."
14422 (catch 'exit
14423 (let ((pos (point))
14424 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14425 (lim (progn
14426 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14427 (point)))
14428 dd-on str (start 0) m re)
14429 (goto-char pos)
14430 (when dodollar
14431 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14432 re (nth 1 (assoc "$" org-latex-regexps)))
14433 (while (string-match re str start)
14434 (cond
14435 ((= (match-end 0) (length str))
14436 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14437 ((= (match-end 0) (- (length str) 5))
14438 (throw 'exit nil))
14439 (t (setq start (match-end 0))))))
14440 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14441 (goto-char pos)
14442 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14443 (and (match-beginning 2) (throw 'exit nil))
14444 ;; count $$
14445 (while (re-search-backward "\\$\\$" lim t)
14446 (setq dd-on (not dd-on)))
14447 (goto-char pos)
14448 (if dd-on (cons "$$" m))))))
14451 (defun org-try-cdlatex-tab ()
14452 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14453 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14454 - inside a LaTeX fragment, or
14455 - after the first word in a line, where an abbreviation expansion could
14456 insert a LaTeX environment."
14457 (when org-cdlatex-mode
14458 (cond
14459 ((save-excursion
14460 (skip-chars-backward "a-zA-Z0-9*")
14461 (skip-chars-backward " \t")
14462 (bolp))
14463 (cdlatex-tab) t)
14464 ((org-inside-LaTeX-fragment-p)
14465 (cdlatex-tab) t)
14466 (t nil))))
14468 (defun org-cdlatex-underscore-caret (&optional arg)
14469 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14470 Revert to the normal definition outside of these fragments."
14471 (interactive "P")
14472 (if (org-inside-LaTeX-fragment-p)
14473 (call-interactively 'cdlatex-sub-superscript)
14474 (let (org-cdlatex-mode)
14475 (call-interactively (key-binding (vector last-input-event))))))
14477 (defun org-cdlatex-math-modify (&optional arg)
14478 "Execute `cdlatex-math-modify' in LaTeX fragments.
14479 Revert to the normal definition outside of these fragments."
14480 (interactive "P")
14481 (if (org-inside-LaTeX-fragment-p)
14482 (call-interactively 'cdlatex-math-modify)
14483 (let (org-cdlatex-mode)
14484 (call-interactively (key-binding (vector last-input-event))))))
14486 (defvar org-latex-fragment-image-overlays nil
14487 "List of overlays carrying the images of latex fragments.")
14488 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14490 (defun org-remove-latex-fragment-image-overlays ()
14491 "Remove all overlays with LaTeX fragment images in current buffer."
14492 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14493 (setq org-latex-fragment-image-overlays nil))
14495 (defun org-preview-latex-fragment (&optional subtree)
14496 "Preview the LaTeX fragment at point, or all locally or globally.
14497 If the cursor is in a LaTeX fragment, create the image and overlay
14498 it over the source code. If there is no fragment at point, display
14499 all fragments in the current text, from one headline to the next. With
14500 prefix SUBTREE, display all fragments in the current subtree. With a
14501 double prefix `C-u C-u', or when the cursor is before the first headline,
14502 display all fragments in the buffer.
14503 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14504 (interactive "P")
14505 (org-remove-latex-fragment-image-overlays)
14506 (save-excursion
14507 (save-restriction
14508 (let (beg end at msg)
14509 (cond
14510 ((or (equal subtree '(16))
14511 (not (save-excursion
14512 (re-search-backward (concat "^" outline-regexp) nil t))))
14513 (setq beg (point-min) end (point-max)
14514 msg "Creating images for buffer...%s"))
14515 ((equal subtree '(4))
14516 (org-back-to-heading)
14517 (setq beg (point) end (org-end-of-subtree t)
14518 msg "Creating images for subtree...%s"))
14520 (if (setq at (org-inside-LaTeX-fragment-p))
14521 (goto-char (max (point-min) (- (cdr at) 2)))
14522 (org-back-to-heading))
14523 (setq beg (point) end (progn (outline-next-heading) (point))
14524 msg (if at "Creating image...%s"
14525 "Creating images for entry...%s"))))
14526 (message msg "")
14527 (narrow-to-region beg end)
14528 (goto-char beg)
14529 (org-format-latex
14530 (concat "ltxpng/" (file-name-sans-extension
14531 (file-name-nondirectory
14532 buffer-file-name)))
14533 default-directory 'overlays msg at 'forbuffer)
14534 (message msg "done. Use `C-c C-c' to remove images.")))))
14536 (defvar org-latex-regexps
14537 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14538 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14539 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14540 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14541 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14542 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14543 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14544 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14545 "Regular expressions for matching embedded LaTeX.")
14547 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14548 "Replace LaTeX fragments with links to an image, and produce images.
14549 Some of the options can be changed using the variable
14550 `org-format-latex-options'."
14551 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14552 (let* ((prefixnodir (file-name-nondirectory prefix))
14553 (absprefix (expand-file-name prefix dir))
14554 (todir (file-name-directory absprefix))
14555 (opt org-format-latex-options)
14556 (matchers (plist-get opt :matchers))
14557 (re-list org-latex-regexps)
14558 (cnt 0) txt link beg end re e checkdir
14559 executables-checked
14560 m n block linkfile movefile ov)
14561 ;; Check if there are old images files with this prefix, and remove them
14562 (when (file-directory-p todir)
14563 (mapc 'delete-file
14564 (directory-files
14565 todir 'full
14566 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14567 ;; Check the different regular expressions
14568 (while (setq e (pop re-list))
14569 (setq m (car e) re (nth 1 e) n (nth 2 e)
14570 block (if (nth 3 e) "\n\n" ""))
14571 (when (member m matchers)
14572 (goto-char (point-min))
14573 (while (re-search-forward re nil t)
14574 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14575 (not (get-text-property (match-beginning n)
14576 'org-protected))
14577 (or (not overlays)
14578 (not (eq (get-char-property (match-beginning n)
14579 'org-overlay-type)
14580 'org-latex-overlay))))
14581 (setq txt (match-string n)
14582 beg (match-beginning n) end (match-end n)
14583 cnt (1+ cnt)
14584 linkfile (format "%s_%04d.png" prefix cnt)
14585 movefile (format "%s_%04d.png" absprefix cnt)
14586 link (concat block "[[file:" linkfile "]]" block))
14587 (if msg (message msg cnt))
14588 (goto-char beg)
14589 (unless checkdir ; make sure the directory exists
14590 (setq checkdir t)
14591 (or (file-directory-p todir) (make-directory todir)))
14593 (unless executables-checked
14594 (org-check-external-command
14595 "latex" "needed to convert LaTeX fragments to images")
14596 (org-check-external-command
14597 "dvipng" "needed to convert LaTeX fragments to images")
14598 (setq executables-checked t))
14600 (org-create-formula-image
14601 txt movefile opt forbuffer)
14602 (if overlays
14603 (progn
14604 (mapc (lambda (o)
14605 (if (eq (org-overlay-get o 'org-overlay-type)
14606 'org-latex-overlay)
14607 (org-delete-overlay o)))
14608 (org-overlays-in beg end))
14609 (setq ov (org-make-overlay beg end))
14610 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14611 (if (featurep 'xemacs)
14612 (progn
14613 (org-overlay-put ov 'invisible t)
14614 (org-overlay-put
14615 ov 'end-glyph
14616 (make-glyph (vector 'png :file movefile))))
14617 (org-overlay-put
14618 ov 'display
14619 (list 'image :type 'png :file movefile :ascent 'center)))
14620 (push ov org-latex-fragment-image-overlays)
14621 (goto-char end))
14622 (delete-region beg end)
14623 (insert link))))))))
14625 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14626 ;; This function borrows from Ganesh Swami's latex2png.el
14627 (defun org-create-formula-image (string tofile options buffer)
14628 "This calls dvipng."
14629 (require 'org-latex)
14630 (let* ((tmpdir (if (featurep 'xemacs)
14631 (temp-directory)
14632 temporary-file-directory))
14633 (texfilebase (make-temp-name
14634 (expand-file-name "orgtex" tmpdir)))
14635 (texfile (concat texfilebase ".tex"))
14636 (dvifile (concat texfilebase ".dvi"))
14637 (pngfile (concat texfilebase ".png"))
14638 (fnh (if (featurep 'xemacs)
14639 (font-height (get-face-font 'default))
14640 (face-attribute 'default :height nil)))
14641 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14642 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14643 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14644 "Black"))
14645 (bg (or (plist-get options (if buffer :background :html-background))
14646 "Transparent")))
14647 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14648 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14649 (with-temp-file texfile
14650 (insert org-format-latex-header
14651 (if org-export-latex-packages-alist
14652 (concat "\n"
14653 (mapconcat (lambda(p)
14654 (if (equal "" (car p))
14655 (format "\\usepackage{%s}" (cadr p))
14656 (format "\\usepackage[%s]{%s}"
14657 (car p) (cadr p))))
14658 org-export-latex-packages-alist "\n"))
14660 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14661 (let ((dir default-directory))
14662 (condition-case nil
14663 (progn
14664 (cd tmpdir)
14665 (call-process "latex" nil nil nil texfile))
14666 (error nil))
14667 (cd dir))
14668 (if (not (file-exists-p dvifile))
14669 (progn (message "Failed to create dvi file from %s" texfile) nil)
14670 (condition-case nil
14671 (call-process "dvipng" nil nil nil
14672 "-fg" fg "-bg" bg
14673 "-D" dpi
14674 ;;"-x" scale "-y" scale
14675 "-T" "tight"
14676 "-o" pngfile
14677 dvifile)
14678 (error nil))
14679 (if (not (file-exists-p pngfile))
14680 (progn (message "Failed to create png file from %s" texfile) nil)
14681 ;; Use the requested file name and clean up
14682 (copy-file pngfile tofile 'replace)
14683 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14684 (delete-file (concat texfilebase e)))
14685 pngfile))))
14687 (defun org-dvipng-color (attr)
14688 "Return an rgb color specification for dvipng."
14689 (apply 'format "rgb %s %s %s"
14690 (mapcar 'org-normalize-color
14691 (color-values (face-attribute 'default attr nil)))))
14693 (defun org-normalize-color (value)
14694 "Return string to be used as color value for an RGB component."
14695 (format "%g" (/ value 65535.0)))
14697 ;;;; Key bindings
14699 ;; Make `C-c C-x' a prefix key
14700 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14702 ;; TAB key with modifiers
14703 (org-defkey org-mode-map "\C-i" 'org-cycle)
14704 (org-defkey org-mode-map [(tab)] 'org-cycle)
14705 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14706 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14707 (org-defkey org-mode-map "\M-\t" 'org-complete)
14708 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14709 ;; The following line is necessary under Suse GNU/Linux
14710 (unless (featurep 'xemacs)
14711 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14712 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14713 (define-key org-mode-map [backtab] 'org-shifttab)
14715 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14716 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14717 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14719 ;; Cursor keys with modifiers
14720 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14721 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14722 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14723 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14725 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14726 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14727 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14728 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14730 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14731 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14732 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14733 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14735 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14736 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14738 ;;; Extra keys for tty access.
14739 ;; We only set them when really needed because otherwise the
14740 ;; menus don't show the simple keys
14742 (when (or org-use-extra-keys
14743 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14744 (not window-system))
14745 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14746 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14747 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14748 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14749 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14750 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14751 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14752 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14753 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14754 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14755 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14756 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14757 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14758 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14759 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14760 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14761 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14762 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14763 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14764 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14765 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14766 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14767 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14768 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14769 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14770 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14771 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14772 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14774 ;; All the other keys
14776 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14777 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14778 (if (boundp 'narrow-map)
14779 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14780 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14781 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14782 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14783 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14784 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14785 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14786 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14787 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14788 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14789 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14790 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14791 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14792 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14793 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14794 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14795 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14796 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14797 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14798 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14799 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14800 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14801 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14802 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14803 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14804 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14805 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14806 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14807 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14808 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14809 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14810 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14811 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14812 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14813 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14814 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14815 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14816 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14817 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14818 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14819 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14820 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14821 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14822 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14823 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14824 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14825 (org-defkey org-mode-map "\C-c^" 'org-sort)
14826 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14827 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14828 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14829 (org-defkey org-mode-map "\C-m" 'org-return)
14830 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14831 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14832 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14833 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14834 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14835 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14836 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14837 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14838 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14839 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14840 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14841 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14842 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14843 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14844 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14845 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14846 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14847 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14848 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14849 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14850 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14852 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14853 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14854 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14855 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14857 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14858 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14859 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14860 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14861 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14862 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14863 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14864 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14865 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14866 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14867 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14868 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14869 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14870 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14871 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14873 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14874 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14875 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14876 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14878 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14880 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14882 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14883 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14885 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14888 (when (featurep 'xemacs)
14889 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14892 (defconst org-speed-commands-default
14894 ("n" . org-speed-move-safe)
14895 ("p" . org-speed-move-safe)
14896 ("f" . org-speed-move-safe)
14897 ("b" . org-speed-move-safe)
14898 ("u" . org-speed-move-safe)
14899 (" " . org-display-outline-path)
14901 ("c" . org-cycle)
14902 ("C" . org-shifttab)
14903 ("U" . org-shiftmetaup)
14904 ("D" . org-shiftmetadown)
14905 ("r" . org-metaright)
14906 ("l" . org-metaleft)
14907 ("R" . org-shiftmetaright)
14908 ("L" . org-shiftmetaleft)
14909 ("i" . (progn (forward-char 1) (call-interactively
14910 'org-insert-heading-respect-content)))
14912 ("v" . org-agenda)
14913 ("/" . org-sparse-tree)
14914 (";" . org-set-tags-command)
14915 ("I" . org-clock-in)
14916 ("O" . org-clock-out)
14917 ("o" . org-open-at-point)
14918 ("t" . org-todo)
14919 ("j" . org-goto)
14920 ("g" . (org-refile t))
14921 ("e" . org-set-effort)
14922 ("0" . (org-priority ?\ ))
14923 ("1" . (org-priority ?A))
14924 ("2" . (org-priority ?B))
14925 ("3" . (org-priority ?C))
14926 ("." . outline-mark-subtree)
14927 ("^" . org-sort)
14928 ("w" . org-refile)
14929 ("a" . org-archive-subtree-default-with-confirmation)
14930 ("/" . org-sparse-tree)
14931 ("?" . org-speed-command-help)
14933 "The default speed commands.")
14935 (defun org-print-speed-command (e)
14936 (princ (car e))
14937 (princ " ")
14938 (if (symbolp (cdr e))
14939 (princ (symbol-name (cdr e)))
14940 (prin1 (cdr e)))
14941 (princ "\n"))
14943 (defun org-speed-command-help ()
14944 "Show the available speed commands."
14945 (interactive)
14946 (if (not org-use-speed-commands)
14947 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
14948 (with-output-to-temp-buffer "*Help*"
14949 (princ "Speed commands\n==============\n")
14950 (mapc 'org-print-speed-command org-speed-commands-user)
14951 (princ "\n")
14952 (mapc 'org-print-speed-command org-speed-commands-default))))
14954 (defun org-speed-move-safe ()
14955 (interactive)
14956 (let ((pos (point))
14957 (tbl '(("n" . outline-next-visible-heading)
14958 ("p" . outline-previous-visible-heading)
14959 ("f" . org-forward-same-level)
14960 ("b" . org-backward-same-level)
14961 ("u" . outline-up-heading))))
14962 (call-interactively (cdr (assoc (this-command-keys) tbl)))
14963 (unless (and (bolp) (org-on-heading-p))
14964 (goto-char pos)
14965 (error "Boundary reached"))))
14967 (defvar org-self-insert-command-undo-counter 0)
14969 (defvar org-table-auto-blank-field) ; defined in org-table.el
14970 (defvar org-speed-command nil)
14971 (defun org-self-insert-command (N)
14972 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14973 If the cursor is in a table looking at whitespace, the whitespace is
14974 overwritten, and the table is not marked as requiring realignment."
14975 (interactive "p")
14976 (cond
14977 ((and org-use-speed-commands
14978 (or (and (bolp) (looking-at outline-regexp))
14979 (and (functionp org-use-speed-commands)
14980 (funcall org-use-speed-commands)))
14981 (setq
14982 org-speed-command
14983 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
14984 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
14985 (cond
14986 ((commandp org-speed-command)
14987 (setq this-command org-speed-command)
14988 (call-interactively org-speed-command))
14989 ((functionp org-speed-command)
14990 (funcall org-speed-command))
14991 ((and org-speed-command (listp org-speed-command))
14992 (eval org-speed-command))
14993 (t (let (org-use-speed-commands)
14994 (call-interactively 'org-self-insert-command)))))
14995 ((and
14996 (org-table-p)
14997 (progn
14998 ;; check if we blank the field, and if that triggers align
14999 (and (featurep 'org-table) org-table-auto-blank-field
15000 (member last-command
15001 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15002 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15003 ;; got extra space, this field does not determine column width
15004 (let (org-table-may-need-update) (org-table-blank-field))
15005 ;; no extra space, this field may determine column width
15006 (org-table-blank-field)))
15008 (eq N 1)
15009 (looking-at "[^|\n]* |"))
15010 (let (org-table-may-need-update)
15011 (goto-char (1- (match-end 0)))
15012 (delete-backward-char 1)
15013 (goto-char (match-beginning 0))
15014 (self-insert-command N)))
15016 (setq org-table-may-need-update t)
15017 (self-insert-command N)
15018 (org-fix-tags-on-the-fly)
15019 (if org-self-insert-cluster-for-undo
15020 (if (not (eq last-command 'org-self-insert-command))
15021 (setq org-self-insert-command-undo-counter 1)
15022 (if (>= org-self-insert-command-undo-counter 20)
15023 (setq org-self-insert-command-undo-counter 1)
15024 (and (> org-self-insert-command-undo-counter 0)
15025 buffer-undo-list
15026 (not (cadr buffer-undo-list)) ; remove nil entry
15027 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15028 (setq org-self-insert-command-undo-counter
15029 (1+ org-self-insert-command-undo-counter))))))))
15031 (defun org-fix-tags-on-the-fly ()
15032 (when (and (equal (char-after (point-at-bol)) ?*)
15033 (org-on-heading-p))
15034 (org-align-tags-here org-tags-column)))
15036 (defun org-delete-backward-char (N)
15037 "Like `delete-backward-char', insert whitespace at field end in tables.
15038 When deleting backwards, in tables this function will insert whitespace in
15039 front of the next \"|\" separator, to keep the table aligned. The table will
15040 still be marked for re-alignment if the field did fill the entire column,
15041 because, in this case the deletion might narrow the column."
15042 (interactive "p")
15043 (if (and (org-table-p)
15044 (eq N 1)
15045 (string-match "|" (buffer-substring (point-at-bol) (point)))
15046 (looking-at ".*?|"))
15047 (let ((pos (point))
15048 (noalign (looking-at "[^|\n\r]* |"))
15049 (c org-table-may-need-update))
15050 (backward-delete-char N)
15051 (skip-chars-forward "^|")
15052 (insert " ")
15053 (goto-char (1- pos))
15054 ;; noalign: if there were two spaces at the end, this field
15055 ;; does not determine the width of the column.
15056 (if noalign (setq org-table-may-need-update c)))
15057 (backward-delete-char N)
15058 (org-fix-tags-on-the-fly)))
15060 (defun org-delete-char (N)
15061 "Like `delete-char', but insert whitespace at field end in tables.
15062 When deleting characters, in tables this function will insert whitespace in
15063 front of the next \"|\" separator, to keep the table aligned. The table will
15064 still be marked for re-alignment if the field did fill the entire column,
15065 because, in this case the deletion might narrow the column."
15066 (interactive "p")
15067 (if (and (org-table-p)
15068 (not (bolp))
15069 (not (= (char-after) ?|))
15070 (eq N 1))
15071 (if (looking-at ".*?|")
15072 (let ((pos (point))
15073 (noalign (looking-at "[^|\n\r]* |"))
15074 (c org-table-may-need-update))
15075 (replace-match (concat
15076 (substring (match-string 0) 1 -1)
15077 " |"))
15078 (goto-char pos)
15079 ;; noalign: if there were two spaces at the end, this field
15080 ;; does not determine the width of the column.
15081 (if noalign (setq org-table-may-need-update c)))
15082 (delete-char N))
15083 (delete-char N)
15084 (org-fix-tags-on-the-fly)))
15086 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15087 (put 'org-self-insert-command 'delete-selection t)
15088 (put 'orgtbl-self-insert-command 'delete-selection t)
15089 (put 'org-delete-char 'delete-selection 'supersede)
15090 (put 'org-delete-backward-char 'delete-selection 'supersede)
15091 (put 'org-yank 'delete-selection 'yank)
15093 ;; Make `flyspell-mode' delay after some commands
15094 (put 'org-self-insert-command 'flyspell-delayed t)
15095 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15096 (put 'org-delete-char 'flyspell-delayed t)
15097 (put 'org-delete-backward-char 'flyspell-delayed t)
15099 ;; Make pabbrev-mode expand after org-mode commands
15100 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15101 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15103 ;; How to do this: Measure non-white length of current string
15104 ;; If equal to column width, we should realign.
15106 (defun org-remap (map &rest commands)
15107 "In MAP, remap the functions given in COMMANDS.
15108 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15109 (let (new old)
15110 (while commands
15111 (setq old (pop commands) new (pop commands))
15112 (if (fboundp 'command-remapping)
15113 (org-defkey map (vector 'remap old) new)
15114 (substitute-key-definition old new map global-map)))))
15116 (when (eq org-enable-table-editor 'optimized)
15117 ;; If the user wants maximum table support, we need to hijack
15118 ;; some standard editing functions
15119 (org-remap org-mode-map
15120 'self-insert-command 'org-self-insert-command
15121 'delete-char 'org-delete-char
15122 'delete-backward-char 'org-delete-backward-char)
15123 (org-defkey org-mode-map "|" 'org-force-self-insert))
15125 (defvar org-ctrl-c-ctrl-c-hook nil
15126 "Hook for functions attaching themselves to `C-c C-c'.
15127 This can be used to add additional functionality to the C-c C-c key which
15128 executes context-dependent commands.
15129 Each function will be called with no arguments. The function must check
15130 if the context is appropriate for it to act. If yes, it should do its
15131 thing and then return a non-nil value. If the context is wrong,
15132 just do nothing and return nil.")
15134 (defvar org-tab-first-hook nil
15135 "Hook for functions to attach themselves to TAB.
15136 See `org-ctrl-c-ctrl-c-hook' for more information.
15137 This hook runs as the first action when TAB is pressed, even before
15138 `org-cycle' messes around with the `outline-regexp' to cater for
15139 inline tasks and plain list item folding.
15140 If any function in this hook returns t, not other actions like table
15141 field motion visibility cycling will be done.")
15143 (defvar org-tab-after-check-for-table-hook nil
15144 "Hook for functions to attach themselves to TAB.
15145 See `org-ctrl-c-ctrl-c-hook' for more information.
15146 This hook runs after it has been established that the cursor is not in a
15147 table, but before checking if the cursor is in a headline or if global cycling
15148 should be done.
15149 If any function in this hook returns t, not other actions like visibility
15150 cycling will be done.")
15152 (defvar org-tab-after-check-for-cycling-hook nil
15153 "Hook for functions to attach themselves to TAB.
15154 See `org-ctrl-c-ctrl-c-hook' for more information.
15155 This hook runs after it has been established that not table field motion and
15156 not visibility should be done because of current context. This is probably
15157 the place where a package like yasnippets can hook in.")
15159 (defvar org-tab-before-tab-emulation-hook nil
15160 "Hook for functions to attach themselves to TAB.
15161 See `org-ctrl-c-ctrl-c-hook' for more information.
15162 This hook runs after every other options for TAB have been exhausted, but
15163 before indentation and \t insertion takes place.")
15165 (defvar org-metaleft-hook nil
15166 "Hook for functions attaching themselves to `M-left'.
15167 See `org-ctrl-c-ctrl-c-hook' for more information.")
15168 (defvar org-metaright-hook nil
15169 "Hook for functions attaching themselves to `M-right'.
15170 See `org-ctrl-c-ctrl-c-hook' for more information.")
15171 (defvar org-metaup-hook nil
15172 "Hook for functions attaching themselves to `M-up'.
15173 See `org-ctrl-c-ctrl-c-hook' for more information.")
15174 (defvar org-metadown-hook nil
15175 "Hook for functions attaching themselves to `M-down'.
15176 See `org-ctrl-c-ctrl-c-hook' for more information.")
15177 (defvar org-shiftmetaleft-hook nil
15178 "Hook for functions attaching themselves to `M-S-left'.
15179 See `org-ctrl-c-ctrl-c-hook' for more information.")
15180 (defvar org-shiftmetaright-hook nil
15181 "Hook for functions attaching themselves to `M-S-right'.
15182 See `org-ctrl-c-ctrl-c-hook' for more information.")
15183 (defvar org-shiftmetaup-hook nil
15184 "Hook for functions attaching themselves to `M-S-up'.
15185 See `org-ctrl-c-ctrl-c-hook' for more information.")
15186 (defvar org-shiftmetadown-hook nil
15187 "Hook for functions attaching themselves to `M-S-down'.
15188 See `org-ctrl-c-ctrl-c-hook' for more information.")
15189 (defvar org-metareturn-hook nil
15190 "Hook for functions attaching themselves to `M-RET'.
15191 See `org-ctrl-c-ctrl-c-hook' for more information.")
15193 (defun org-modifier-cursor-error ()
15194 "Throw an error, a modified cursor command was applied in wrong context."
15195 (error "This command is active in special context like tables, headlines or items"))
15197 (defun org-shiftselect-error ()
15198 "Throw an error because Shift-Cursor command was applied in wrong context."
15199 (if (and (boundp 'shift-select-mode) shift-select-mode)
15200 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15201 (error "This command works only in special context like headlines or timestamps")))
15203 (defun org-call-for-shift-select (cmd)
15204 (let ((this-command-keys-shift-translated t))
15205 (call-interactively cmd)))
15207 (defun org-shifttab (&optional arg)
15208 "Global visibility cycling or move to previous table field.
15209 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15210 on context.
15211 See the individual commands for more information."
15212 (interactive "P")
15213 (cond
15214 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15215 ((integerp arg)
15216 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15217 (message "Content view to level: %d" arg)
15218 (org-content (prefix-numeric-value arg2))
15219 (setq org-cycle-global-status 'overview)))
15220 (t (call-interactively 'org-global-cycle))))
15222 (defun org-shiftmetaleft ()
15223 "Promote subtree or delete table column.
15224 Calls `org-promote-subtree', `org-outdent-item',
15225 or `org-table-delete-column', depending on context.
15226 See the individual commands for more information."
15227 (interactive)
15228 (cond
15229 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15230 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15231 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15232 ((org-at-item-p) (call-interactively 'org-outdent-item))
15233 (t (org-modifier-cursor-error))))
15235 (defun org-shiftmetaright ()
15236 "Demote subtree or insert table column.
15237 Calls `org-demote-subtree', `org-indent-item',
15238 or `org-table-insert-column', depending on context.
15239 See the individual commands for more information."
15240 (interactive)
15241 (cond
15242 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15243 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15244 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15245 ((org-at-item-p) (call-interactively 'org-indent-item))
15246 (t (org-modifier-cursor-error))))
15248 (defun org-shiftmetaup (&optional arg)
15249 "Move subtree up or kill table row.
15250 Calls `org-move-subtree-up' or `org-table-kill-row' or
15251 `org-move-item-up' depending on context. See the individual commands
15252 for more information."
15253 (interactive "P")
15254 (cond
15255 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15256 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15257 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15258 ((org-at-item-p) (call-interactively 'org-move-item-up))
15259 (t (org-modifier-cursor-error))))
15261 (defun org-shiftmetadown (&optional arg)
15262 "Move subtree down or insert table row.
15263 Calls `org-move-subtree-down' or `org-table-insert-row' or
15264 `org-move-item-down', depending on context. See the individual
15265 commands for more information."
15266 (interactive "P")
15267 (cond
15268 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15269 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15270 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15271 ((org-at-item-p) (call-interactively 'org-move-item-down))
15272 (t (org-modifier-cursor-error))))
15274 (defun org-metaleft (&optional arg)
15275 "Promote heading or move table column to left.
15276 Calls `org-do-promote' or `org-table-move-column', depending on context.
15277 With no specific context, calls the Emacs default `backward-word'.
15278 See the individual commands for more information."
15279 (interactive "P")
15280 (cond
15281 ((run-hook-with-args-until-success 'org-metaleft-hook))
15282 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15283 ((or (org-on-heading-p)
15284 (and (org-region-active-p)
15285 (save-excursion
15286 (goto-char (region-beginning))
15287 (org-on-heading-p))))
15288 (call-interactively 'org-do-promote))
15289 ((or (org-at-item-p)
15290 (and (org-region-active-p)
15291 (save-excursion
15292 (goto-char (region-beginning))
15293 (org-at-item-p))))
15294 (call-interactively 'org-outdent-item))
15295 (t (call-interactively 'backward-word))))
15297 (defun org-metaright (&optional arg)
15298 "Demote subtree or move table column to right.
15299 Calls `org-do-demote' or `org-table-move-column', depending on context.
15300 With no specific context, calls the Emacs default `forward-word'.
15301 See the individual commands for more information."
15302 (interactive "P")
15303 (cond
15304 ((run-hook-with-args-until-success 'org-metaright-hook))
15305 ((org-at-table-p) (call-interactively 'org-table-move-column))
15306 ((or (org-on-heading-p)
15307 (and (org-region-active-p)
15308 (save-excursion
15309 (goto-char (region-beginning))
15310 (org-on-heading-p))))
15311 (call-interactively 'org-do-demote))
15312 ((or (org-at-item-p)
15313 (and (org-region-active-p)
15314 (save-excursion
15315 (goto-char (region-beginning))
15316 (org-at-item-p))))
15317 (call-interactively 'org-indent-item))
15318 (t (call-interactively 'forward-word))))
15320 (defun org-metaup (&optional arg)
15321 "Move subtree up or move table row up.
15322 Calls `org-move-subtree-up' or `org-table-move-row' or
15323 `org-move-item-up', depending on context. See the individual commands
15324 for more information."
15325 (interactive "P")
15326 (cond
15327 ((run-hook-with-args-until-success 'org-metaup-hook))
15328 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15329 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15330 ((org-at-item-p) (call-interactively 'org-move-item-up))
15331 (t (transpose-lines 1) (beginning-of-line -1))))
15333 (defun org-metadown (&optional arg)
15334 "Move subtree down or move table row down.
15335 Calls `org-move-subtree-down' or `org-table-move-row' or
15336 `org-move-item-down', depending on context. See the individual
15337 commands for more information."
15338 (interactive "P")
15339 (cond
15340 ((run-hook-with-args-until-success 'org-metadown-hook))
15341 ((org-at-table-p) (call-interactively 'org-table-move-row))
15342 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15343 ((org-at-item-p) (call-interactively 'org-move-item-down))
15344 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15346 (defun org-shiftup (&optional arg)
15347 "Increase item in timestamp or increase priority of current headline.
15348 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15349 depending on context. See the individual commands for more information."
15350 (interactive "P")
15351 (cond
15352 ((and org-support-shift-select (org-region-active-p))
15353 (org-call-for-shift-select 'previous-line))
15354 ((org-at-timestamp-p t)
15355 (call-interactively (if org-edit-timestamp-down-means-later
15356 'org-timestamp-down 'org-timestamp-up)))
15357 ((and (not (eq org-support-shift-select 'always))
15358 org-enable-priority-commands
15359 (org-on-heading-p))
15360 (call-interactively 'org-priority-up))
15361 ((and (not org-support-shift-select) (org-at-item-p))
15362 (call-interactively 'org-previous-item))
15363 ((org-clocktable-try-shift 'up arg))
15364 (org-support-shift-select
15365 (org-call-for-shift-select 'previous-line))
15366 (t (org-shiftselect-error))))
15368 (defun org-shiftdown (&optional arg)
15369 "Decrease item in timestamp or decrease priority of current headline.
15370 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15371 depending on context. See the individual commands for more information."
15372 (interactive "P")
15373 (cond
15374 ((and org-support-shift-select (org-region-active-p))
15375 (org-call-for-shift-select 'next-line))
15376 ((org-at-timestamp-p t)
15377 (call-interactively (if org-edit-timestamp-down-means-later
15378 'org-timestamp-up 'org-timestamp-down)))
15379 ((and (not (eq org-support-shift-select 'always))
15380 org-enable-priority-commands
15381 (org-on-heading-p))
15382 (call-interactively 'org-priority-down))
15383 ((and (not org-support-shift-select) (org-at-item-p))
15384 (call-interactively 'org-next-item))
15385 ((org-clocktable-try-shift 'down arg))
15386 (org-support-shift-select
15387 (org-call-for-shift-select 'next-line))
15388 (t (org-shiftselect-error))))
15390 (defun org-shiftright (&optional arg)
15391 "Cycle the thing at point or in the current line, depending on context.
15392 Depending on context, this does one of the following:
15394 - switch a timestamp at point one day into the future
15395 - on a headline, switch to the next TODO keyword.
15396 - on an item, switch entire list to the next bullet type
15397 - on a property line, switch to the next allowed value
15398 - on a clocktable definition line, move time block into the future"
15399 (interactive "P")
15400 (cond
15401 ((and org-support-shift-select (org-region-active-p))
15402 (org-call-for-shift-select 'forward-char))
15403 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15404 ((and (not (eq org-support-shift-select 'always))
15405 (org-on-heading-p))
15406 (let ((org-inhibit-logging
15407 (not org-treat-S-cursor-todo-selection-as-state-change))
15408 (org-inhibit-blocking
15409 (not org-treat-S-cursor-todo-selection-as-state-change)))
15410 (org-call-with-arg 'org-todo 'right)))
15411 ((or (and org-support-shift-select
15412 (not (eq org-support-shift-select 'always))
15413 (org-at-item-bullet-p))
15414 (and (not org-support-shift-select) (org-at-item-p)))
15415 (org-call-with-arg 'org-cycle-list-bullet nil))
15416 ((and (not (eq org-support-shift-select 'always))
15417 (org-at-property-p))
15418 (call-interactively 'org-property-next-allowed-value))
15419 ((org-clocktable-try-shift 'right arg))
15420 (org-support-shift-select
15421 (org-call-for-shift-select 'forward-char))
15422 (t (org-shiftselect-error))))
15424 (defun org-shiftleft (&optional arg)
15425 "Cycle the thing at point or in the current line, depending on context.
15426 Depending on context, this does one of the following:
15428 - switch a timestamp at point one day into the past
15429 - on a headline, switch to the previous TODO keyword.
15430 - on an item, switch entire list to the previous bullet type
15431 - on a property line, switch to the previous allowed value
15432 - on a clocktable definition line, move time block into the past"
15433 (interactive "P")
15434 (cond
15435 ((and org-support-shift-select (org-region-active-p))
15436 (org-call-for-shift-select 'backward-char))
15437 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15438 ((and (not (eq org-support-shift-select 'always))
15439 (org-on-heading-p))
15440 (let ((org-inhibit-logging
15441 (not org-treat-S-cursor-todo-selection-as-state-change))
15442 (org-inhibit-blocking
15443 (not org-treat-S-cursor-todo-selection-as-state-change)))
15444 (org-call-with-arg 'org-todo 'left)))
15445 ((or (and org-support-shift-select
15446 (not (eq org-support-shift-select 'always))
15447 (org-at-item-bullet-p))
15448 (and (not org-support-shift-select) (org-at-item-p)))
15449 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15450 ((and (not (eq org-support-shift-select 'always))
15451 (org-at-property-p))
15452 (call-interactively 'org-property-previous-allowed-value))
15453 ((org-clocktable-try-shift 'left arg))
15454 (org-support-shift-select
15455 (org-call-for-shift-select 'backward-char))
15456 (t (org-shiftselect-error))))
15458 (defun org-shiftcontrolright ()
15459 "Switch to next TODO set."
15460 (interactive)
15461 (cond
15462 ((and org-support-shift-select (org-region-active-p))
15463 (org-call-for-shift-select 'forward-word))
15464 ((and (not (eq org-support-shift-select 'always))
15465 (org-on-heading-p))
15466 (org-call-with-arg 'org-todo 'nextset))
15467 (org-support-shift-select
15468 (org-call-for-shift-select 'forward-word))
15469 (t (org-shiftselect-error))))
15471 (defun org-shiftcontrolleft ()
15472 "Switch to previous TODO set."
15473 (interactive)
15474 (cond
15475 ((and org-support-shift-select (org-region-active-p))
15476 (org-call-for-shift-select 'backward-word))
15477 ((and (not (eq org-support-shift-select 'always))
15478 (org-on-heading-p))
15479 (org-call-with-arg 'org-todo 'previousset))
15480 (org-support-shift-select
15481 (org-call-for-shift-select 'backward-word))
15482 (t (org-shiftselect-error))))
15484 (defun org-ctrl-c-ret ()
15485 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15486 (interactive)
15487 (cond
15488 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15489 (t (call-interactively 'org-insert-heading))))
15491 (defun org-copy-special ()
15492 "Copy region in table or copy current subtree.
15493 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15494 See the individual commands for more information."
15495 (interactive)
15496 (call-interactively
15497 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15499 (defun org-cut-special ()
15500 "Cut region in table or cut current subtree.
15501 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15502 See the individual commands for more information."
15503 (interactive)
15504 (call-interactively
15505 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15507 (defun org-paste-special (arg)
15508 "Paste rectangular region into table, or past subtree relative to level.
15509 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15510 See the individual commands for more information."
15511 (interactive "P")
15512 (if (org-at-table-p)
15513 (org-table-paste-rectangle)
15514 (org-paste-subtree arg)))
15516 (defun org-edit-special ()
15517 "Call a special editor for the stuff at point.
15518 When at a table, call the formula editor with `org-table-edit-formulas'.
15519 When at the first line of an src example, call `org-edit-src-code'.
15520 When in an #+include line, visit the include file. Otherwise call
15521 `ffap' to visit the file at point."
15522 (interactive)
15523 (cond
15524 ((org-at-table-p)
15525 (call-interactively 'org-table-edit-formulas))
15526 ((save-excursion
15527 (beginning-of-line 1)
15528 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15529 (find-file (org-trim (match-string 1))))
15530 ((org-edit-src-code))
15531 ((org-edit-fixed-width-region))
15532 (t (call-interactively 'ffap))))
15535 (defun org-ctrl-c-ctrl-c (&optional arg)
15536 "Set tags in headline, or update according to changed information at point.
15538 This command does many different things, depending on context:
15540 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15541 this is what we do.
15543 - If the cursor is on a statistics cookie, update it.
15545 - If the cursor is in a headline, prompt for tags and insert them
15546 into the current line, aligned to `org-tags-column'. When called
15547 with prefix arg, realign all tags in the current buffer.
15549 - If the cursor is in one of the special #+KEYWORD lines, this
15550 triggers scanning the buffer for these lines and updating the
15551 information.
15553 - If the cursor is inside a table, realign the table. This command
15554 works even if the automatic table editor has been turned off.
15556 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15557 the entire table.
15559 - If the cursor is at a footnote reference or definition, jump to
15560 the corresponding definition or references, respectively.
15562 - If the cursor is a the beginning of a dynamic block, update it.
15564 - If the cursor is inside a table created by the table.el package,
15565 activate that table.
15567 - If the current buffer is a remember buffer, close note and file
15568 it. A prefix argument of 1 files to the default location
15569 without further interaction. A prefix argument of 2 files to
15570 the currently clocking task.
15572 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15573 links in this buffer.
15575 - If the cursor is on a numbered item in a plain list, renumber the
15576 ordered list.
15578 - If the cursor is on a checkbox, toggle it."
15579 (interactive "P")
15580 (let ((org-enable-table-editor t))
15581 (cond
15582 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15583 org-occur-highlights
15584 org-latex-fragment-image-overlays)
15585 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15586 (org-remove-occur-highlights)
15587 (org-remove-latex-fragment-image-overlays)
15588 (message "Temporary highlights/overlays removed from current buffer"))
15589 ((and (local-variable-p 'org-finish-function (current-buffer))
15590 (fboundp org-finish-function))
15591 (funcall org-finish-function))
15592 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15593 ((org-at-property-p)
15594 (call-interactively 'org-property-action))
15595 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15596 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15597 (or (org-on-heading-p) (org-at-item-p)))
15598 (call-interactively 'org-update-statistics-cookies))
15599 ((org-on-heading-p) (call-interactively 'org-set-tags))
15600 ((org-at-table.el-p)
15601 (require 'table)
15602 (beginning-of-line 1)
15603 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15604 (call-interactively 'table-recognize-table))
15605 ((org-at-table-p)
15606 (org-table-maybe-eval-formula)
15607 (if arg
15608 (call-interactively 'org-table-recalculate)
15609 (org-table-maybe-recalculate-line))
15610 (call-interactively 'org-table-align))
15611 ((or (org-footnote-at-reference-p)
15612 (org-footnote-at-definition-p))
15613 (call-interactively 'org-footnote-action))
15614 ((org-at-item-checkbox-p)
15615 (call-interactively 'org-toggle-checkbox))
15616 ((org-at-item-p)
15617 (if arg
15618 (call-interactively 'org-toggle-checkbox)
15619 (call-interactively 'org-maybe-renumber-ordered-list)))
15620 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15621 ;; Dynamic block
15622 (beginning-of-line 1)
15623 (save-excursion (org-update-dblock)))
15624 ((save-excursion
15625 (beginning-of-line 1)
15626 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15627 (cond
15628 ((equal (match-string 1) "TBLFM")
15629 ;; Recalculate the table before this line
15630 (save-excursion
15631 (beginning-of-line 1)
15632 (skip-chars-backward " \r\n\t")
15633 (if (org-at-table-p)
15634 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15636 ; (org-set-regexps-and-options)
15637 ; (org-restart-font-lock)
15638 (let ((org-inhibit-startup t)) (org-mode-restart))
15639 (message "Local setup has been refreshed"))))
15640 ((org-clock-update-time-maybe))
15641 (t (error "C-c C-c can do nothing useful at this location")))))
15643 (defun org-mode-restart ()
15644 "Restart Org-mode, to scan again for special lines.
15645 Also updates the keyword regular expressions."
15646 (interactive)
15647 (org-mode)
15648 (message "Org-mode restarted"))
15650 (defun org-kill-note-or-show-branches ()
15651 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15652 (interactive)
15653 (if (not org-finish-function)
15654 (call-interactively 'show-branches)
15655 (let ((org-note-abort t))
15656 (funcall org-finish-function))))
15658 (defun org-return (&optional indent)
15659 "Goto next table row or insert a newline.
15660 Calls `org-table-next-row' or `newline', depending on context.
15661 See the individual commands for more information."
15662 (interactive)
15663 (cond
15664 ((bobp) (if indent (newline-and-indent) (newline)))
15665 ((org-at-table-p)
15666 (org-table-justify-field-maybe)
15667 (call-interactively 'org-table-next-row))
15668 ((and org-return-follows-link
15669 (eq (get-text-property (point) 'face) 'org-link))
15670 (call-interactively 'org-open-at-point))
15671 ((and (org-at-heading-p)
15672 (looking-at
15673 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15674 (org-show-entry)
15675 (end-of-line 1)
15676 (newline))
15677 (t (if indent (newline-and-indent) (newline)))))
15679 (defun org-return-indent ()
15680 "Goto next table row or insert a newline and indent.
15681 Calls `org-table-next-row' or `newline-and-indent', depending on
15682 context. See the individual commands for more information."
15683 (interactive)
15684 (org-return t))
15686 (defun org-ctrl-c-star ()
15687 "Compute table, or change heading status of lines.
15688 Calls `org-table-recalculate' or `org-toggle-heading',
15689 depending on context."
15690 (interactive)
15691 (cond
15692 ((org-at-table-p)
15693 (call-interactively 'org-table-recalculate))
15695 ;; Convert all lines in region to list items
15696 (call-interactively 'org-toggle-heading))))
15698 (defun org-ctrl-c-minus ()
15699 "Insert separator line in table or modify bullet status of line.
15700 Also turns a plain line or a region of lines into list items.
15701 Calls `org-table-insert-hline', `org-toggle-item', or
15702 `org-cycle-list-bullet', depending on context."
15703 (interactive)
15704 (cond
15705 ((org-at-table-p)
15706 (call-interactively 'org-table-insert-hline))
15707 ((org-region-active-p)
15708 (call-interactively 'org-toggle-item))
15709 ((org-in-item-p)
15710 (call-interactively 'org-cycle-list-bullet))
15712 (call-interactively 'org-toggle-item))))
15714 (defun org-toggle-item ()
15715 "Convert headings or normal lines to items, items to normal lines.
15716 If there is no active region, only the current line is considered.
15718 If the first line in the region is a headline, convert all headlines to items.
15720 If the first line in the region is an item, convert all items to normal lines.
15722 If the first line is normal text, add an item bullet to each line."
15723 (interactive)
15724 (let (l2 l beg end)
15725 (if (org-region-active-p)
15726 (setq beg (region-beginning) end (region-end))
15727 (setq beg (point-at-bol)
15728 end (min (1+ (point-at-eol)) (point-max))))
15729 (save-excursion
15730 (goto-char end)
15731 (setq l2 (org-current-line))
15732 (goto-char beg)
15733 (beginning-of-line 1)
15734 (setq l (1- (org-current-line)))
15735 (if (org-at-item-p)
15736 ;; We already have items, de-itemize
15737 (while (< (setq l (1+ l)) l2)
15738 (when (org-at-item-p)
15739 (goto-char (match-beginning 2))
15740 (delete-region (match-beginning 2) (match-end 2))
15741 (and (looking-at "[ \t]+") (replace-match "")))
15742 (beginning-of-line 2))
15743 (if (org-on-heading-p)
15744 ;; Headings, convert to items
15745 (while (< (setq l (1+ l)) l2)
15746 (if (looking-at org-outline-regexp)
15747 (replace-match "- " t t))
15748 (beginning-of-line 2))
15749 ;; normal lines, turn them into items
15750 (while (< (setq l (1+ l)) l2)
15751 (unless (org-at-item-p)
15752 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15753 (replace-match "\\1- \\2")))
15754 (beginning-of-line 2)))))))
15756 (defun org-toggle-heading (&optional nstars)
15757 "Convert headings to normal text, or items or text to headings.
15758 If there is no active region, only the current line is considered.
15760 If the first line is a heading, remove the stars from all headlines
15761 in the region.
15763 If the first line is a plain list item, turn all plain list items
15764 into headings.
15766 If the first line is a normal line, turn each and every line in the
15767 region into a heading.
15769 When converting a line into a heading, the number of stars is chosen
15770 such that the lines become children of the current entry. However,
15771 when a prefix argument is given, its value determines the number of
15772 stars to add."
15773 (interactive "P")
15774 (let (l2 l itemp beg end)
15775 (if (org-region-active-p)
15776 (setq beg (region-beginning) end (region-end))
15777 (setq beg (point-at-bol)
15778 end (min (1+ (point-at-eol)) (point-max))))
15779 (save-excursion
15780 (goto-char end)
15781 (setq l2 (org-current-line))
15782 (goto-char beg)
15783 (beginning-of-line 1)
15784 (setq l (1- (org-current-line)))
15785 (if (org-on-heading-p)
15786 ;; We already have headlines, de-star them
15787 (while (< (setq l (1+ l)) l2)
15788 (when (org-on-heading-p t)
15789 (and (looking-at outline-regexp) (replace-match "")))
15790 (beginning-of-line 2))
15791 (setq itemp (org-at-item-p))
15792 (let* ((stars
15793 (if nstars
15794 (make-string (prefix-numeric-value current-prefix-arg)
15796 (save-excursion
15797 (if (re-search-backward org-complex-heading-regexp nil t)
15798 (match-string 1) ""))))
15799 (add-stars (cond (nstars "")
15800 ((equal stars "") "*")
15801 (org-odd-levels-only "**")
15802 (t "*")))
15803 (rpl (concat stars add-stars " ")))
15804 (while (< (setq l (1+ l)) l2)
15805 (if itemp
15806 (and (org-at-item-p) (replace-match rpl t t))
15807 (unless (org-on-heading-p)
15808 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15809 (replace-match (concat rpl (match-string 2))))))
15810 (beginning-of-line 2)))))))
15812 (defun org-meta-return (&optional arg)
15813 "Insert a new heading or wrap a region in a table.
15814 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15815 See the individual commands for more information."
15816 (interactive "P")
15817 (cond
15818 ((run-hook-with-args-until-success 'org-metareturn-hook))
15819 ((org-at-table-p)
15820 (call-interactively 'org-table-wrap-region))
15821 (t (call-interactively 'org-insert-heading))))
15823 ;;; Menu entries
15825 ;; Define the Org-mode menus
15826 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15827 '("Tbl"
15828 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15829 ["Next Field" org-cycle (org-at-table-p)]
15830 ["Previous Field" org-shifttab (org-at-table-p)]
15831 ["Next Row" org-return (org-at-table-p)]
15832 "--"
15833 ["Blank Field" org-table-blank-field (org-at-table-p)]
15834 ["Edit Field" org-table-edit-field (org-at-table-p)]
15835 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15836 "--"
15837 ("Column"
15838 ["Move Column Left" org-metaleft (org-at-table-p)]
15839 ["Move Column Right" org-metaright (org-at-table-p)]
15840 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15841 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15842 ("Row"
15843 ["Move Row Up" org-metaup (org-at-table-p)]
15844 ["Move Row Down" org-metadown (org-at-table-p)]
15845 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15846 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15847 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15848 "--"
15849 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15850 ("Rectangle"
15851 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15852 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15853 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15854 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15855 "--"
15856 ("Calculate"
15857 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15858 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15859 ["Edit Formulas" org-edit-special (org-at-table-p)]
15860 "--"
15861 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15862 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15863 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15864 "--"
15865 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15866 "--"
15867 ["Sum Column/Rectangle" org-table-sum
15868 (or (org-at-table-p) (org-region-active-p))]
15869 ["Which Column?" org-table-current-column (org-at-table-p)])
15870 ["Debug Formulas"
15871 org-table-toggle-formula-debugger
15872 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15873 ["Show Col/Row Numbers"
15874 org-table-toggle-coordinate-overlays
15875 :style toggle
15876 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15877 "--"
15878 ["Create" org-table-create (and (not (org-at-table-p))
15879 org-enable-table-editor)]
15880 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15881 ["Import from File" org-table-import (not (org-at-table-p))]
15882 ["Export to File" org-table-export (org-at-table-p)]
15883 "--"
15884 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15886 (easy-menu-define org-org-menu org-mode-map "Org menu"
15887 '("Org"
15888 ("Show/Hide"
15889 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15890 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15891 ["Sparse Tree..." org-sparse-tree t]
15892 ["Reveal Context" org-reveal t]
15893 ["Show All" show-all t]
15894 "--"
15895 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15896 "--"
15897 ["New Heading" org-insert-heading t]
15898 ("Navigate Headings"
15899 ["Up" outline-up-heading t]
15900 ["Next" outline-next-visible-heading t]
15901 ["Previous" outline-previous-visible-heading t]
15902 ["Next Same Level" outline-forward-same-level t]
15903 ["Previous Same Level" outline-backward-same-level t]
15904 "--"
15905 ["Jump" org-goto t])
15906 ("Edit Structure"
15907 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15908 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15909 "--"
15910 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15911 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15912 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15913 "--"
15914 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15915 "--"
15916 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15917 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15918 ["Demote Heading" org-metaright (not (org-at-table-p))]
15919 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15920 "--"
15921 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15922 "--"
15923 ["Convert to odd levels" org-convert-to-odd-levels t]
15924 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15925 ("Editing"
15926 ["Emphasis..." org-emphasize t]
15927 ["Edit Source Example" org-edit-special t]
15928 "--"
15929 ["Footnote new/jump" org-footnote-action t]
15930 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15931 ("Archive"
15932 ["Archive (default method)" org-archive-subtree-default t]
15933 "--"
15934 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
15935 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15936 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
15938 "--"
15939 ("Hyperlinks"
15940 ["Store Link (Global)" org-store-link t]
15941 ["Find existing link to here" org-occur-link-in-agenda-files t]
15942 ["Insert Link" org-insert-link t]
15943 ["Follow Link" org-open-at-point t]
15944 "--"
15945 ["Next link" org-next-link t]
15946 ["Previous link" org-previous-link t]
15947 "--"
15948 ["Descriptive Links"
15949 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15950 :style radio
15951 :selected (member '(org-link) buffer-invisibility-spec)]
15952 ["Literal Links"
15953 (progn
15954 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15955 :style radio
15956 :selected (not (member '(org-link) buffer-invisibility-spec))])
15957 "--"
15958 ("TODO Lists"
15959 ["TODO/DONE/-" org-todo t]
15960 ("Select keyword"
15961 ["Next keyword" org-shiftright (org-on-heading-p)]
15962 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15963 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15964 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15965 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15966 ["Show TODO Tree" org-show-todo-tree t]
15967 ["Global TODO list" org-todo-list t]
15968 "--"
15969 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15970 :selected org-enforce-todo-dependencies :style toggle :active t]
15971 "Settings for tree at point"
15972 ["Do Children sequentially" org-toggle-ordered-property :style radio
15973 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15974 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15975 ["Do Children parallel" org-toggle-ordered-property :style radio
15976 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15977 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15978 "--"
15979 ["Set Priority" org-priority t]
15980 ["Priority Up" org-shiftup t]
15981 ["Priority Down" org-shiftdown t]
15982 "--"
15983 ["Get news from all feeds" org-feed-update-all t]
15984 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15985 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15986 ("TAGS and Properties"
15987 ["Set Tags" org-set-tags-command t]
15988 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15989 "--"
15990 ["Set property" org-set-property t]
15991 ["Column view of properties" org-columns t]
15992 ["Insert Column View DBlock" org-insert-columns-dblock t])
15993 ("Dates and Scheduling"
15994 ["Timestamp" org-time-stamp t]
15995 ["Timestamp (inactive)" org-time-stamp-inactive t]
15996 ("Change Date"
15997 ["1 Day Later" org-shiftright t]
15998 ["1 Day Earlier" org-shiftleft t]
15999 ["1 ... Later" org-shiftup t]
16000 ["1 ... Earlier" org-shiftdown t])
16001 ["Compute Time Range" org-evaluate-time-range t]
16002 ["Schedule Item" org-schedule t]
16003 ["Deadline" org-deadline t]
16004 "--"
16005 ["Custom time format" org-toggle-time-stamp-overlays
16006 :style radio :selected org-display-custom-times]
16007 "--"
16008 ["Goto Calendar" org-goto-calendar t]
16009 ["Date from Calendar" org-date-from-calendar t]
16010 "--"
16011 ["Start/Restart Timer" org-timer-start t]
16012 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16013 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16014 ["Insert Timer String" org-timer t]
16015 ["Insert Timer Item" org-timer-item t])
16016 ("Logging work"
16017 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16018 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16019 ["Clock out" org-clock-out t]
16020 ["Clock cancel" org-clock-cancel t]
16021 "--"
16022 ["Mark as default task" org-clock-mark-default-task t]
16023 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16024 ["Goto running clock" org-clock-goto t]
16025 "--"
16026 ["Display times" org-clock-display t]
16027 ["Create clock table" org-clock-report t]
16028 "--"
16029 ["Record DONE time"
16030 (progn (setq org-log-done (not org-log-done))
16031 (message "Switching to %s will %s record a timestamp"
16032 (car org-done-keywords)
16033 (if org-log-done "automatically" "not")))
16034 :style toggle :selected org-log-done])
16035 "--"
16036 ["Agenda Command..." org-agenda t]
16037 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16038 ("File List for Agenda")
16039 ("Special views current file"
16040 ["TODO Tree" org-show-todo-tree t]
16041 ["Check Deadlines" org-check-deadlines t]
16042 ["Timeline" org-timeline t]
16043 ["Tags/Property tree" org-match-sparse-tree t])
16044 "--"
16045 ["Export/Publish..." org-export t]
16046 ("LaTeX"
16047 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16048 :selected org-cdlatex-mode]
16049 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16050 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16051 ["Modify math symbol" org-cdlatex-math-modify
16052 (org-inside-LaTeX-fragment-p)]
16053 ["Insert citation" org-reftex-citation t]
16054 "--"
16055 ["Export LaTeX fragments as images"
16056 (if (featurep 'org-exp)
16057 (setq org-export-with-LaTeX-fragments
16058 (not org-export-with-LaTeX-fragments))
16059 (require 'org-exp))
16060 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16061 org-export-with-LaTeX-fragments)])
16062 "--"
16063 ("MobileOrg"
16064 ["Push Files and Views" org-mobile-push t]
16065 ["Get Captured and Flagged" org-mobile-pull t]
16066 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16067 "--"
16068 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16069 "--"
16070 ("Documentation"
16071 ["Show Version" org-version t]
16072 ["Info Documentation" org-info t])
16073 ("Customize"
16074 ["Browse Org Group" org-customize t]
16075 "--"
16076 ["Expand This Menu" org-create-customize-menu
16077 (fboundp 'customize-menu-create)])
16078 ["Send bug report" org-submit-bug-report t]
16079 "--"
16080 ("Refresh/Reload"
16081 ["Refresh setup current buffer" org-mode-restart t]
16082 ["Reload Org (after update)" org-reload t]
16083 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16086 (defun org-info (&optional node)
16087 "Read documentation for Org-mode in the info system.
16088 With optional NODE, go directly to that node."
16089 (interactive)
16090 (info (format "(org)%s" (or node ""))))
16092 ;;;###autoload
16093 (defun org-submit-bug-report ()
16094 "Submit a bug report on Org-mode via mail.
16096 Don't hesitate to report any problems or inaccurate documentation.
16098 If you don't have setup sending mail from (X)Emacs, please copy the
16099 output buffer into your mail program, as it gives us important
16100 information about your Org-mode version and configuration."
16101 (interactive)
16102 (require 'reporter)
16103 (org-load-modules-maybe)
16104 (org-require-autoloaded-modules)
16105 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16106 (reporter-submit-bug-report
16107 "emacs-orgmode@gnu.org"
16108 (org-version)
16109 (let (list)
16110 (save-window-excursion
16111 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16112 (delete-other-windows)
16113 (erase-buffer)
16114 (insert "You are about to submit a bug report to the Org-mode mailing list.
16116 We would like to add your full Org-mode and Outline configuration to the
16117 bug report. This greatly simplifies the work of the maintainer and
16118 other experts on the mailing list.
16120 HOWEVER, some variables you have customized may contain private
16121 information. The names of customers, colleagues, or friends, might
16122 appear in the form of file names, tags, todo states, or search strings.
16123 If you answer yes to the prompt, you might want to check and remove
16124 such private information before sending the email.")
16125 (add-text-properties (point-min) (point-max) '(face org-warning))
16126 (when (yes-or-no-p "Include your Org-mode configuration ")
16127 (mapatoms
16128 (lambda (v)
16129 (and (boundp v)
16130 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16131 (or (and (symbol-value v)
16132 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16133 (and
16134 (get v 'custom-type) (get v 'standard-value)
16135 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16136 (push v list)))))
16137 (kill-buffer (get-buffer "*Warn about privacy*"))
16138 list))
16139 nil nil
16140 "Remember to cover the basics, that is, what you expected to happen and
16141 what in fact did happen. You don't know how to make a good report? See
16143 http://orgmode.org/manual/Feedback.html#Feedback
16145 Your bug report will be posted to the Org-mode mailing list.
16146 ------------------------------------------------------------------------")
16147 (save-excursion
16148 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16149 (replace-match "\\1Bug: \\3 [\\2]")))))
16152 (defun org-install-agenda-files-menu ()
16153 (let ((bl (buffer-list)))
16154 (save-excursion
16155 (while bl
16156 (set-buffer (pop bl))
16157 (if (org-mode-p) (setq bl nil)))
16158 (when (org-mode-p)
16159 (easy-menu-change
16160 '("Org") "File List for Agenda"
16161 (append
16162 (list
16163 ["Edit File List" (org-edit-agenda-file-list) t]
16164 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16165 ["Remove Current File from List" org-remove-file t]
16166 ["Cycle through agenda files" org-cycle-agenda-files t]
16167 ["Occur in all agenda files" org-occur-in-agenda-files t]
16168 "--")
16169 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16171 ;;;; Documentation
16173 ;;;###autoload
16174 (defun org-require-autoloaded-modules ()
16175 (interactive)
16176 (mapc 'require
16177 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16178 org-docbook org-exp org-html org-icalendar
16179 org-id org-latex
16180 org-publish org-remember org-table
16181 org-timer org-xoxo)))
16183 ;;;###autoload
16184 (defun org-reload (&optional uncompiled)
16185 "Reload all org lisp files.
16186 With prefix arg UNCOMPILED, load the uncompiled versions."
16187 (interactive "P")
16188 (require 'find-func)
16189 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16190 (dir-org (file-name-directory (org-find-library-name "org")))
16191 (dir-org-contrib (ignore-errors
16192 (file-name-directory
16193 (org-find-library-name "org-contribdir"))))
16194 (files
16195 (append (directory-files dir-org t file-re)
16196 (and dir-org-contrib
16197 (directory-files dir-org-contrib t file-re))))
16198 (remove-re (concat (if (featurep 'xemacs)
16199 "org-colview" "org-colview-xemacs")
16200 "\\'")))
16201 (setq files (mapcar 'file-name-sans-extension files))
16202 (setq files (mapcar
16203 (lambda (x) (if (string-match remove-re x) nil x))
16204 files))
16205 (setq files (delq nil files))
16206 (mapc
16207 (lambda (f)
16208 (when (featurep (intern (file-name-nondirectory f)))
16209 (if (and (not uncompiled)
16210 (file-exists-p (concat f ".elc")))
16211 (load (concat f ".elc") nil nil t)
16212 (load (concat f ".el") nil nil t))))
16213 files))
16214 (org-version))
16216 ;;;###autoload
16217 (defun org-customize ()
16218 "Call the customize function with org as argument."
16219 (interactive)
16220 (org-load-modules-maybe)
16221 (org-require-autoloaded-modules)
16222 (customize-browse 'org))
16224 (defun org-create-customize-menu ()
16225 "Create a full customization menu for Org-mode, insert it into the menu."
16226 (interactive)
16227 (org-load-modules-maybe)
16228 (org-require-autoloaded-modules)
16229 (if (fboundp 'customize-menu-create)
16230 (progn
16231 (easy-menu-change
16232 '("Org") "Customize"
16233 `(["Browse Org group" org-customize t]
16234 "--"
16235 ,(customize-menu-create 'org)
16236 ["Set" Custom-set t]
16237 ["Save" Custom-save t]
16238 ["Reset to Current" Custom-reset-current t]
16239 ["Reset to Saved" Custom-reset-saved t]
16240 ["Reset to Standard Settings" Custom-reset-standard t]))
16241 (message "\"Org\"-menu now contains full customization menu"))
16242 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16244 ;;;; Miscellaneous stuff
16246 ;;; Generally useful functions
16248 (defun org-get-at-bol (property)
16249 "Get text property PROPERTY at beginning of line."
16250 (get-text-property (point-at-bol) property))
16252 (defun org-find-text-property-in-string (prop s)
16253 "Return the first non-nil value of property PROP in string S."
16254 (or (get-text-property 0 prop s)
16255 (get-text-property (or (next-single-property-change 0 prop s) 0)
16256 prop s)))
16258 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16259 "Display the given MESSAGE as a warning."
16260 (if (fboundp 'display-warning)
16261 (display-warning 'org message
16262 (if (featurep 'xemacs)
16263 'warning
16264 :warning))
16265 (let ((buf (get-buffer-create "*Org warnings*")))
16266 (with-current-buffer buf
16267 (goto-char (point-max))
16268 (insert "Warning (Org): " message)
16269 (unless (bolp)
16270 (newline)))
16271 (display-buffer buf)
16272 (sit-for 0))))
16274 (defun org-in-commented-line ()
16275 "Is point in a line starting with `#'?"
16276 (equal (char-after (point-at-bol)) ?#))
16278 (defun org-in-verbatim-emphasis ()
16279 (save-match-data
16280 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16282 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16283 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16284 (if (and marker (marker-buffer marker)
16285 (buffer-live-p (marker-buffer marker)))
16286 (progn
16287 (switch-to-buffer (marker-buffer marker))
16288 (if (or (> marker (point-max)) (< marker (point-min)))
16289 (widen))
16290 (goto-char marker)
16291 (org-show-context 'org-goto))
16292 (if bookmark
16293 (bookmark-jump bookmark)
16294 (error "Cannot find location"))))
16296 (defun org-quote-csv-field (s)
16297 "Quote field for inclusion in CSV material."
16298 (if (string-match "[\",]" s)
16299 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16302 (defun org-plist-delete (plist property)
16303 "Delete PROPERTY from PLIST.
16304 This is in contrast to merely setting it to 0."
16305 (let (p)
16306 (while plist
16307 (if (not (eq property (car plist)))
16308 (setq p (plist-put p (car plist) (nth 1 plist))))
16309 (setq plist (cddr plist)))
16312 (defun org-force-self-insert (N)
16313 "Needed to enforce self-insert under remapping."
16314 (interactive "p")
16315 (self-insert-command N))
16317 (defun org-string-width (s)
16318 "Compute width of string, ignoring invisible characters.
16319 This ignores character with invisibility property `org-link', and also
16320 characters with property `org-cwidth', because these will become invisible
16321 upon the next fontification round."
16322 (let (b l)
16323 (when (or (eq t buffer-invisibility-spec)
16324 (assq 'org-link buffer-invisibility-spec))
16325 (while (setq b (text-property-any 0 (length s)
16326 'invisible 'org-link s))
16327 (setq s (concat (substring s 0 b)
16328 (substring s (or (next-single-property-change
16329 b 'invisible s) (length s)))))))
16330 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16331 (setq s (concat (substring s 0 b)
16332 (substring s (or (next-single-property-change
16333 b 'org-cwidth s) (length s))))))
16334 (setq l (string-width s) b -1)
16335 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16336 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16339 (defun org-get-indentation (&optional line)
16340 "Get the indentation of the current line, interpreting tabs.
16341 When LINE is given, assume it represents a line and compute its indentation."
16342 (if line
16343 (if (string-match "^ *" (org-remove-tabs line))
16344 (match-end 0))
16345 (save-excursion
16346 (beginning-of-line 1)
16347 (skip-chars-forward " \t")
16348 (current-column))))
16350 (defun org-remove-tabs (s &optional width)
16351 "Replace tabulators in S with spaces.
16352 Assumes that s is a single line, starting in column 0."
16353 (setq width (or width tab-width))
16354 (while (string-match "\t" s)
16355 (setq s (replace-match
16356 (make-string
16357 (- (* width (/ (+ (match-beginning 0) width) width))
16358 (match-beginning 0)) ?\ )
16359 t t s)))
16362 (defun org-fix-indentation (line ind)
16363 "Fix indentation in LINE.
16364 IND is a cons cell with target and minimum indentation.
16365 If the current indentation in LINE is smaller than the minimum,
16366 leave it alone. If it is larger than ind, set it to the target."
16367 (let* ((l (org-remove-tabs line))
16368 (i (org-get-indentation l))
16369 (i1 (car ind)) (i2 (cdr ind)))
16370 (if (>= i i2) (setq l (substring line i2)))
16371 (if (> i1 0)
16372 (concat (make-string i1 ?\ ) l)
16373 l)))
16375 (defun org-remove-indentation (code &optional n)
16376 "Remove the maximum common indentation from the lines in CODE.
16377 N may optionally be the number of spaces to remove."
16378 (with-temp-buffer
16379 (insert code)
16380 (org-do-remove-indentation n)
16381 (buffer-string)))
16383 (defun org-do-remove-indentation (&optional n)
16384 "Remove the maximum common indentation from the buffer."
16385 (untabify (point-min) (point-max))
16386 (let ((min 10000) re)
16387 (if n
16388 (setq min n)
16389 (goto-char (point-min))
16390 (while (re-search-forward "^ *[^ \n]" nil t)
16391 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16392 (unless (or (= min 0) (= min 10000))
16393 (setq re (format "^ \\{%d\\}" min))
16394 (goto-char (point-min))
16395 (while (re-search-forward re nil t)
16396 (replace-match "")
16397 (end-of-line 1))
16398 min)))
16400 (defun org-fill-template (template alist)
16401 "Find each %key of ALIST in TEMPLATE and replace it."
16402 (let (entry key value)
16403 (setq alist (sort (copy-sequence alist)
16404 (lambda (a b) (< (length (car a)) (length (car b))))))
16405 (while (setq entry (pop alist))
16406 (setq template
16407 (replace-regexp-in-string
16408 (concat "%" (regexp-quote (car entry)))
16409 (cdr entry) template t t)))
16410 template))
16412 (defun org-base-buffer (buffer)
16413 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16414 (if (not buffer)
16415 buffer
16416 (or (buffer-base-buffer buffer)
16417 buffer)))
16419 (defun org-trim (s)
16420 "Remove whitespace at beginning and end of string."
16421 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16422 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16425 (defun org-wrap (string &optional width lines)
16426 "Wrap string to either a number of lines, or a width in characters.
16427 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16428 that costs. If there is a word longer than WIDTH, the text is actually
16429 wrapped to the length of that word.
16430 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16431 many lines, whatever width that takes.
16432 The return value is a list of lines, without newlines at the end."
16433 (let* ((words (org-split-string string "[ \t\n]+"))
16434 (maxword (apply 'max (mapcar 'org-string-width words)))
16435 w ll)
16436 (cond (width
16437 (org-do-wrap words (max maxword width)))
16438 (lines
16439 (setq w maxword)
16440 (setq ll (org-do-wrap words maxword))
16441 (if (<= (length ll) lines)
16443 (setq ll words)
16444 (while (> (length ll) lines)
16445 (setq w (1+ w))
16446 (setq ll (org-do-wrap words w)))
16447 ll))
16448 (t (error "Cannot wrap this")))))
16450 (defun org-do-wrap (words width)
16451 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16452 (let (lines line)
16453 (while words
16454 (setq line (pop words))
16455 (while (and words (< (+ (length line) (length (car words))) width))
16456 (setq line (concat line " " (pop words))))
16457 (setq lines (push line lines)))
16458 (nreverse lines)))
16460 (defun org-split-string (string &optional separators)
16461 "Splits STRING into substrings at SEPARATORS.
16462 No empty strings are returned if there are matches at the beginning
16463 and end of string."
16464 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16465 (start 0)
16466 notfirst
16467 (list nil))
16468 (while (and (string-match rexp string
16469 (if (and notfirst
16470 (= start (match-beginning 0))
16471 (< start (length string)))
16472 (1+ start) start))
16473 (< (match-beginning 0) (length string)))
16474 (setq notfirst t)
16475 (or (eq (match-beginning 0) 0)
16476 (and (eq (match-beginning 0) (match-end 0))
16477 (eq (match-beginning 0) start))
16478 (setq list
16479 (cons (substring string start (match-beginning 0))
16480 list)))
16481 (setq start (match-end 0)))
16482 (or (eq start (length string))
16483 (setq list
16484 (cons (substring string start)
16485 list)))
16486 (nreverse list)))
16488 (defun org-quote-vert (s)
16489 "Replace \"|\" with \"\\vert\"."
16490 (while (string-match "|" s)
16491 (setq s (replace-match "\\vert" t t s)))
16494 (defun org-uuidgen-p (s)
16495 "Is S an ID created by UUIDGEN?"
16496 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16498 (defun org-context ()
16499 "Return a list of contexts of the current cursor position.
16500 If several contexts apply, all are returned.
16501 Each context entry is a list with a symbol naming the context, and
16502 two positions indicating start and end of the context. Possible
16503 contexts are:
16505 :headline anywhere in a headline
16506 :headline-stars on the leading stars in a headline
16507 :todo-keyword on a TODO keyword (including DONE) in a headline
16508 :tags on the TAGS in a headline
16509 :priority on the priority cookie in a headline
16510 :item on the first line of a plain list item
16511 :item-bullet on the bullet/number of a plain list item
16512 :checkbox on the checkbox in a plain list item
16513 :table in an org-mode table
16514 :table-special on a special filed in a table
16515 :table-table in a table.el table
16516 :link on a hyperlink
16517 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16518 :target on a <<target>>
16519 :radio-target on a <<<radio-target>>>
16520 :latex-fragment on a LaTeX fragment
16521 :latex-preview on a LaTeX fragment with overlayed preview image
16523 This function expects the position to be visible because it uses font-lock
16524 faces as a help to recognize the following contexts: :table-special, :link,
16525 and :keyword."
16526 (let* ((f (get-text-property (point) 'face))
16527 (faces (if (listp f) f (list f)))
16528 (p (point)) clist o)
16529 ;; First the large context
16530 (cond
16531 ((org-on-heading-p t)
16532 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16533 (when (progn
16534 (beginning-of-line 1)
16535 (looking-at org-todo-line-tags-regexp))
16536 (push (org-point-in-group p 1 :headline-stars) clist)
16537 (push (org-point-in-group p 2 :todo-keyword) clist)
16538 (push (org-point-in-group p 4 :tags) clist))
16539 (goto-char p)
16540 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16541 (if (looking-at "\\[#[A-Z0-9]\\]")
16542 (push (org-point-in-group p 0 :priority) clist)))
16544 ((org-at-item-p)
16545 (push (org-point-in-group p 2 :item-bullet) clist)
16546 (push (list :item (point-at-bol)
16547 (save-excursion (org-end-of-item) (point)))
16548 clist)
16549 (and (org-at-item-checkbox-p)
16550 (push (org-point-in-group p 0 :checkbox) clist)))
16552 ((org-at-table-p)
16553 (push (list :table (org-table-begin) (org-table-end)) clist)
16554 (if (memq 'org-formula faces)
16555 (push (list :table-special
16556 (previous-single-property-change p 'face)
16557 (next-single-property-change p 'face)) clist)))
16558 ((org-at-table-p 'any)
16559 (push (list :table-table) clist)))
16560 (goto-char p)
16562 ;; Now the small context
16563 (cond
16564 ((org-at-timestamp-p)
16565 (push (org-point-in-group p 0 :timestamp) clist))
16566 ((memq 'org-link faces)
16567 (push (list :link
16568 (previous-single-property-change p 'face)
16569 (next-single-property-change p 'face)) clist))
16570 ((memq 'org-special-keyword faces)
16571 (push (list :keyword
16572 (previous-single-property-change p 'face)
16573 (next-single-property-change p 'face)) clist))
16574 ((org-on-target-p)
16575 (push (org-point-in-group p 0 :target) clist)
16576 (goto-char (1- (match-beginning 0)))
16577 (if (looking-at org-radio-target-regexp)
16578 (push (org-point-in-group p 0 :radio-target) clist))
16579 (goto-char p))
16580 ((setq o (car (delq nil
16581 (mapcar
16582 (lambda (x)
16583 (if (memq x org-latex-fragment-image-overlays) x))
16584 (org-overlays-at (point))))))
16585 (push (list :latex-fragment
16586 (org-overlay-start o) (org-overlay-end o)) clist)
16587 (push (list :latex-preview
16588 (org-overlay-start o) (org-overlay-end o)) clist))
16589 ((org-inside-LaTeX-fragment-p)
16590 ;; FIXME: positions wrong.
16591 (push (list :latex-fragment (point) (point)) clist)))
16593 (setq clist (nreverse (delq nil clist)))
16594 clist))
16596 ;; FIXME: Compare with at-regexp-p Do we need both?
16597 (defun org-in-regexp (re &optional nlines visually)
16598 "Check if point is inside a match of regexp.
16599 Normally only the current line is checked, but you can include NLINES extra
16600 lines both before and after point into the search.
16601 If VISUALLY is set, require that the cursor is not after the match but
16602 really on, so that the block visually is on the match."
16603 (catch 'exit
16604 (let ((pos (point))
16605 (eol (point-at-eol (+ 1 (or nlines 0))))
16606 (inc (if visually 1 0)))
16607 (save-excursion
16608 (beginning-of-line (- 1 (or nlines 0)))
16609 (while (re-search-forward re eol t)
16610 (if (and (<= (match-beginning 0) pos)
16611 (>= (+ inc (match-end 0)) pos))
16612 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16614 (defun org-at-regexp-p (regexp)
16615 "Is point inside a match of REGEXP in the current line?"
16616 (catch 'exit
16617 (save-excursion
16618 (let ((pos (point)) (end (point-at-eol)))
16619 (beginning-of-line 1)
16620 (while (re-search-forward regexp end t)
16621 (if (and (<= (match-beginning 0) pos)
16622 (>= (match-end 0) pos))
16623 (throw 'exit t)))
16624 nil))))
16626 (defun org-occur-in-agenda-files (regexp &optional nlines)
16627 "Call `multi-occur' with buffers for all agenda files."
16628 (interactive "sOrg-files matching: \np")
16629 (let* ((files (org-agenda-files))
16630 (tnames (mapcar 'file-truename files))
16631 (extra org-agenda-text-search-extra-files)
16633 (when (eq (car extra) 'agenda-archives)
16634 (setq extra (cdr extra))
16635 (setq files (org-add-archive-files files)))
16636 (while (setq f (pop extra))
16637 (unless (member (file-truename f) tnames)
16638 (add-to-list 'files f 'append)
16639 (add-to-list 'tnames (file-truename f) 'append)))
16640 (multi-occur
16641 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16642 regexp)))
16644 (if (boundp 'occur-mode-find-occurrence-hook)
16645 ;; Emacs 23
16646 (add-hook 'occur-mode-find-occurrence-hook
16647 (lambda ()
16648 (when (org-mode-p)
16649 (org-reveal))))
16650 ;; Emacs 22
16651 (defadvice occur-mode-goto-occurrence
16652 (after org-occur-reveal activate)
16653 (and (org-mode-p) (org-reveal)))
16654 (defadvice occur-mode-goto-occurrence-other-window
16655 (after org-occur-reveal activate)
16656 (and (org-mode-p) (org-reveal)))
16657 (defadvice occur-mode-display-occurrence
16658 (after org-occur-reveal activate)
16659 (when (org-mode-p)
16660 (let ((pos (occur-mode-find-occurrence)))
16661 (with-current-buffer (marker-buffer pos)
16662 (save-excursion
16663 (goto-char pos)
16664 (org-reveal)))))))
16666 (defun org-occur-link-in-agenda-files ()
16667 "Create a link and search for it in the agendas.
16668 The link is not stored in `org-stored-links', it is just created
16669 for the search purpose."
16670 (interactive)
16671 (let ((link (condition-case nil
16672 (org-store-link nil)
16673 (error "Unable to create a link to here"))))
16674 (org-occur-in-agenda-files (regexp-quote link))))
16676 (defun org-uniquify (list)
16677 "Remove duplicate elements from LIST."
16678 (let (res)
16679 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16680 res))
16682 (defun org-delete-all (elts list)
16683 "Remove all elements in ELTS from LIST."
16684 (while elts
16685 (setq list (delete (pop elts) list)))
16686 list)
16688 (defun org-back-over-empty-lines ()
16689 "Move backwards over whitespace, to the beginning of the first empty line.
16690 Returns the number of empty lines passed."
16691 (let ((pos (point)))
16692 (skip-chars-backward " \t\n\r")
16693 (beginning-of-line 2)
16694 (goto-char (min (point) pos))
16695 (count-lines (point) pos)))
16697 (defun org-skip-whitespace ()
16698 (skip-chars-forward " \t\n\r"))
16700 (defun org-point-in-group (point group &optional context)
16701 "Check if POINT is in match-group GROUP.
16702 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16703 match. If the match group does ot exist or point is not inside it,
16704 return nil."
16705 (and (match-beginning group)
16706 (>= point (match-beginning group))
16707 (<= point (match-end group))
16708 (if context
16709 (list context (match-beginning group) (match-end group))
16710 t)))
16712 (defun org-switch-to-buffer-other-window (&rest args)
16713 "Switch to buffer in a second window on the current frame.
16714 In particular, do not allow pop-up frames."
16715 (let (pop-up-frames special-display-buffer-names special-display-regexps
16716 special-display-function)
16717 (apply 'switch-to-buffer-other-window args)))
16719 (defun org-combine-plists (&rest plists)
16720 "Create a single property list from all plists in PLISTS.
16721 The process starts by copying the first list, and then setting properties
16722 from the other lists. Settings in the last list are the most significant
16723 ones and overrule settings in the other lists."
16724 (let ((rtn (copy-sequence (pop plists)))
16725 p v ls)
16726 (while plists
16727 (setq ls (pop plists))
16728 (while ls
16729 (setq p (pop ls) v (pop ls))
16730 (setq rtn (plist-put rtn p v))))
16731 rtn))
16733 (defun org-move-line-down (arg)
16734 "Move the current line down. With prefix argument, move it past ARG lines."
16735 (interactive "p")
16736 (let ((col (current-column))
16737 beg end pos)
16738 (beginning-of-line 1) (setq beg (point))
16739 (beginning-of-line 2) (setq end (point))
16740 (beginning-of-line (+ 1 arg))
16741 (setq pos (move-marker (make-marker) (point)))
16742 (insert (delete-and-extract-region beg end))
16743 (goto-char pos)
16744 (org-move-to-column col)))
16746 (defun org-move-line-up (arg)
16747 "Move the current line up. With prefix argument, move it past ARG lines."
16748 (interactive "p")
16749 (let ((col (current-column))
16750 beg end pos)
16751 (beginning-of-line 1) (setq beg (point))
16752 (beginning-of-line 2) (setq end (point))
16753 (beginning-of-line (- arg))
16754 (setq pos (move-marker (make-marker) (point)))
16755 (insert (delete-and-extract-region beg end))
16756 (goto-char pos)
16757 (org-move-to-column col)))
16759 (defun org-replace-escapes (string table)
16760 "Replace %-escapes in STRING with values in TABLE.
16761 TABLE is an association list with keys like \"%a\" and string values.
16762 The sequences in STRING may contain normal field width and padding information,
16763 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16764 so values can contain further %-escapes if they are define later in TABLE."
16765 (let ((case-fold-search nil)
16766 e re rpl)
16767 (while (setq e (pop table))
16768 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16769 (while (string-match re string)
16770 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16771 (cdr e)))
16772 (setq string (replace-match rpl t t string))))
16773 string))
16776 (defun org-sublist (list start end)
16777 "Return a section of LIST, from START to END.
16778 Counting starts at 1."
16779 (let (rtn (c start))
16780 (setq list (nthcdr (1- start) list))
16781 (while (and list (<= c end))
16782 (push (pop list) rtn)
16783 (setq c (1+ c)))
16784 (nreverse rtn)))
16786 (defun org-find-base-buffer-visiting (file)
16787 "Like `find-buffer-visiting' but always return the base buffer and
16788 not an indirect buffer."
16789 (let ((buf (or (get-file-buffer file)
16790 (find-buffer-visiting file))))
16791 (if buf
16792 (or (buffer-base-buffer buf) buf)
16793 nil)))
16795 (defun org-image-file-name-regexp (&optional extensions)
16796 "Return regexp matching the file names of images.
16797 If EXTENSIONS is given, only match these."
16798 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16799 (image-file-name-regexp)
16800 (let ((image-file-name-extensions
16801 (or extensions
16802 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16803 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16804 (concat "\\."
16805 (regexp-opt (nconc (mapcar 'upcase
16806 image-file-name-extensions)
16807 image-file-name-extensions)
16809 "\\'"))))
16811 (defun org-file-image-p (file &optional extensions)
16812 "Return non-nil if FILE is an image."
16813 (save-match-data
16814 (string-match (org-image-file-name-regexp extensions) file)))
16816 (defun org-get-cursor-date ()
16817 "Return the date at cursor in as a time.
16818 This works in the calendar and in the agenda, anywhere else it just
16819 returns the current time."
16820 (let (date day defd)
16821 (cond
16822 ((eq major-mode 'calendar-mode)
16823 (setq date (calendar-cursor-to-date)
16824 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16825 ((eq major-mode 'org-agenda-mode)
16826 (setq day (get-text-property (point) 'day))
16827 (if day
16828 (setq date (calendar-gregorian-from-absolute day)
16829 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16830 (nth 2 date))))))
16831 (or defd (current-time))))
16833 (defvar org-agenda-action-marker (make-marker)
16834 "Marker pointing to the entry for the next agenda action.")
16836 (defun org-mark-entry-for-agenda-action ()
16837 "Mark the current entry as target of an agenda action.
16838 Agenda actions are actions executed from the agenda with the key `k',
16839 which make use of the date at the cursor."
16840 (interactive)
16841 (move-marker org-agenda-action-marker
16842 (save-excursion (org-back-to-heading t) (point))
16843 (current-buffer))
16844 (message
16845 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16847 ;;; Paragraph filling stuff.
16848 ;; We want this to be just right, so use the full arsenal.
16850 (defun org-indent-line-function ()
16851 "Indent line like previous, but further if previous was headline or item."
16852 (interactive)
16853 (let* ((pos (point))
16854 (itemp (org-at-item-p))
16855 (case-fold-search t)
16856 (org-drawer-regexp (or org-drawer-regexp "\000"))
16857 column bpos bcol tpos tcol bullet btype bullet-type)
16858 ;; Find the previous relevant line
16859 (beginning-of-line 1)
16860 (cond
16861 ((looking-at "#") (setq column 0))
16862 ((looking-at "\\*+ ") (setq column 0))
16863 ((and (looking-at "[ \t]*:END:")
16864 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16865 (save-excursion
16866 (goto-char (1- (match-beginning 1)))
16867 (setq column (current-column))))
16868 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16869 (save-excursion
16870 (re-search-backward
16871 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16872 (setq column (org-get-indentation (match-string 0))))
16874 (beginning-of-line 0)
16875 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16876 (not (looking-at "[ \t]*:END:"))
16877 (not (looking-at org-drawer-regexp)))
16878 (beginning-of-line 0))
16879 (cond
16880 ((looking-at "\\*+[ \t]+")
16881 (if (not org-adapt-indentation)
16882 (setq column 0)
16883 (goto-char (match-end 0))
16884 (setq column (current-column))))
16885 ((looking-at org-drawer-regexp)
16886 (goto-char (1- (match-beginning 1)))
16887 (setq column (current-column)))
16888 ((looking-at "\\([ \t]*\\):END:")
16889 (goto-char (match-end 1))
16890 (setq column (current-column)))
16891 ((org-in-item-p)
16892 (org-beginning-of-item)
16893 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16894 (setq bpos (match-beginning 1) tpos (match-end 0)
16895 bcol (progn (goto-char bpos) (current-column))
16896 tcol (progn (goto-char tpos) (current-column))
16897 bullet (match-string 1)
16898 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16899 (if (> tcol (+ bcol org-description-max-indent))
16900 (setq tcol (+ bcol 5)))
16901 (if (not itemp)
16902 (setq column tcol)
16903 (goto-char pos)
16904 (beginning-of-line 1)
16905 (if (looking-at "\\S-")
16906 (progn
16907 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16908 (setq bullet (match-string 1)
16909 btype (if (string-match "[0-9]" bullet) "n" bullet))
16910 (setq column (if (equal btype bullet-type) bcol tcol)))
16911 (setq column (org-get-indentation)))))
16912 (t (setq column (org-get-indentation))))))
16913 (goto-char pos)
16914 (if (<= (current-column) (current-indentation))
16915 (org-indent-line-to column)
16916 (save-excursion (org-indent-line-to column)))
16917 (setq column (current-column))
16918 (beginning-of-line 1)
16919 (if (looking-at
16920 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16921 (replace-match (concat (match-string 1)
16922 (format org-property-format
16923 (match-string 2) (match-string 3)))
16924 t t))
16925 (org-move-to-column column)))
16927 (defun org-set-autofill-regexps ()
16928 (interactive)
16929 ;; In the paragraph separator we include headlines, because filling
16930 ;; text in a line directly attached to a headline would otherwise
16931 ;; fill the headline as well.
16932 (org-set-local 'comment-start-skip "^#+[ \t]*")
16933 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16934 ;; The paragraph starter includes hand-formatted lists.
16935 (org-set-local
16936 'paragraph-start
16937 (concat
16938 "\f" "\\|"
16939 "[ ]*$" "\\|"
16940 "\\*+ " "\\|"
16941 "[ \t]*#" "\\|"
16942 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16943 "[ \t]*[:|]" "\\|"
16944 "\\$\\$" "\\|"
16945 "\\\\\\(begin\\|end\\|[][]\\)"))
16946 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16947 ;; But only if the user has not turned off tables or fixed-width regions
16948 (org-set-local
16949 'auto-fill-inhibit-regexp
16950 (concat "\\*+ \\|#\\+"
16951 "\\|[ \t]*" org-keyword-time-regexp
16952 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16953 (concat
16954 "\\|[ \t]*["
16955 (if org-enable-table-editor "|" "")
16956 (if org-enable-fixed-width-editor ":" "")
16957 "]"))))
16958 ;; We use our own fill-paragraph function, to make sure that tables
16959 ;; and fixed-width regions are not wrapped. That function will pass
16960 ;; through to `fill-paragraph' when appropriate.
16961 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16962 ; Adaptive filling: To get full control, first make sure that
16963 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16964 (org-set-local 'adaptive-fill-regexp "\000")
16965 (org-set-local 'adaptive-fill-function
16966 'org-adaptive-fill-function)
16967 (org-set-local
16968 'align-mode-rules-list
16969 '((org-in-buffer-settings
16970 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16971 (modes . '(org-mode))))))
16973 (defun org-fill-paragraph (&optional justify)
16974 "Re-align a table, pass through to fill-paragraph if no table."
16975 (let ((table-p (org-at-table-p))
16976 (table.el-p (org-at-table.el-p)))
16977 (cond ((and (equal (char-after (point-at-bol)) ?*)
16978 (save-excursion (goto-char (point-at-bol))
16979 (looking-at outline-regexp)))
16980 t) ; skip headlines
16981 (table.el-p t) ; skip table.el tables
16982 (table-p (org-table-align) t) ; align org-mode tables
16983 (t nil)))) ; call paragraph-fill
16985 ;; For reference, this is the default value of adaptive-fill-regexp
16986 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16988 (defun org-adaptive-fill-function ()
16989 "Return a fill prefix for org-mode files.
16990 In particular, this makes sure hanging paragraphs for hand-formatted lists
16991 work correctly."
16992 (cond ((looking-at "#[ \t]+")
16993 (match-string 0))
16994 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16995 (save-excursion
16996 (if (> (match-end 1) (+ (match-beginning 1)
16997 org-description-max-indent))
16998 (goto-char (+ (match-beginning 1) 5))
16999 (goto-char (match-end 0)))
17000 (make-string (current-column) ?\ )))
17001 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17002 (save-excursion
17003 (goto-char (match-end 0))
17004 (make-string (current-column) ?\ )))
17005 (t nil)))
17007 ;;; Other stuff.
17009 (defun org-toggle-fixed-width-section (arg)
17010 "Toggle the fixed-width export.
17011 If there is no active region, the QUOTE keyword at the current headline is
17012 inserted or removed. When present, it causes the text between this headline
17013 and the next to be exported as fixed-width text, and unmodified.
17014 If there is an active region, this command adds or removes a colon as the
17015 first character of this line. If the first character of a line is a colon,
17016 this line is also exported in fixed-width font."
17017 (interactive "P")
17018 (let* ((cc 0)
17019 (regionp (org-region-active-p))
17020 (beg (if regionp (region-beginning) (point)))
17021 (end (if regionp (region-end)))
17022 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17023 (case-fold-search nil)
17024 (re "[ \t]*\\(: \\)")
17025 off)
17026 (if regionp
17027 (save-excursion
17028 (goto-char beg)
17029 (setq cc (current-column))
17030 (beginning-of-line 1)
17031 (setq off (looking-at re))
17032 (while (> nlines 0)
17033 (setq nlines (1- nlines))
17034 (beginning-of-line 1)
17035 (cond
17036 (arg
17037 (org-move-to-column cc t)
17038 (insert ": \n")
17039 (forward-line -1))
17040 ((and off (looking-at re))
17041 (replace-match "" t t nil 1))
17042 ((not off) (org-move-to-column cc t) (insert ": ")))
17043 (forward-line 1)))
17044 (save-excursion
17045 (org-back-to-heading)
17046 (if (looking-at (concat outline-regexp
17047 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17048 (replace-match "" t t nil 1)
17049 (if (looking-at outline-regexp)
17050 (progn
17051 (goto-char (match-end 0))
17052 (insert org-quote-string " "))))))))
17054 (defun org-reftex-citation ()
17055 "Use reftex-citation to insert a citation into the buffer.
17056 This looks for a line like
17058 #+BIBLIOGRAPHY: foo plain option:-d
17060 and derives from it that foo.bib is the bibliography file relevant
17061 for this document. It then installs the necessary environment for RefTeX
17062 to work in this buffer and calls `reftex-citation' to insert a citation
17063 into the buffer.
17065 Export of such citations to both LaTeX and HTML is handled by the contributed
17066 package org-exp-bibtex by Taru Karttunen."
17067 (interactive)
17068 (let ((reftex-docstruct-symbol 'rds)
17069 (reftex-cite-format "\\cite{%l}")
17070 rds bib)
17071 (save-excursion
17072 (save-restriction
17073 (widen)
17074 (let ((case-fold-search t)
17075 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17076 (if (not (save-excursion
17077 (or (re-search-forward re nil t)
17078 (re-search-backward re nil t))))
17079 (error "No bibliography defined in file")
17080 (setq bib (concat (match-string 1) ".bib")
17081 rds (list (list 'bib bib)))))))
17082 (call-interactively 'reftex-citation)))
17084 ;;;; Functions extending outline functionality
17086 (defun org-beginning-of-line (&optional arg)
17087 "Go to the beginning of the current line. If that is invisible, continue
17088 to a visible line beginning. This makes the function of C-a more intuitive.
17089 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17090 first attempt, and only move to after the tags when the cursor is already
17091 beyond the end of the headline."
17092 (interactive "P")
17093 (let ((pos (point))
17094 (special (if (consp org-special-ctrl-a/e)
17095 (car org-special-ctrl-a/e)
17096 org-special-ctrl-a/e))
17097 refpos)
17098 (if (org-bound-and-true-p line-move-visual)
17099 (beginning-of-visual-line 1)
17100 (beginning-of-line 1))
17101 (if (and arg (fboundp 'move-beginning-of-line))
17102 (call-interactively 'move-beginning-of-line)
17103 (if (bobp)
17105 (backward-char 1)
17106 (if (org-invisible-p)
17107 (while (and (not (bobp)) (org-invisible-p))
17108 (backward-char 1)
17109 (beginning-of-line 1))
17110 (forward-char 1))))
17111 (when special
17112 (cond
17113 ((and (looking-at org-complex-heading-regexp)
17114 (= (char-after (match-end 1)) ?\ ))
17115 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17116 (point-at-eol)))
17117 (goto-char
17118 (if (eq special t)
17119 (cond ((> pos refpos) refpos)
17120 ((= pos (point)) refpos)
17121 (t (point)))
17122 (cond ((> pos (point)) (point))
17123 ((not (eq last-command this-command)) (point))
17124 (t refpos)))))
17125 ((org-at-item-p)
17126 (goto-char
17127 (if (eq special t)
17128 (cond ((> pos (match-end 4)) (match-end 4))
17129 ((= pos (point)) (match-end 4))
17130 (t (point)))
17131 (cond ((> pos (point)) (point))
17132 ((not (eq last-command this-command)) (point))
17133 (t (match-end 4))))))))
17134 (org-no-warnings
17135 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17137 (defun org-end-of-line (&optional arg)
17138 "Go to the end of the line.
17139 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17140 first attempt, and only move to after the tags when the cursor is already
17141 beyond the end of the headline."
17142 (interactive "P")
17143 (let ((special (if (consp org-special-ctrl-a/e)
17144 (cdr org-special-ctrl-a/e)
17145 org-special-ctrl-a/e)))
17146 (if (or (not special)
17147 (not (org-on-heading-p))
17148 arg)
17149 (call-interactively
17150 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17151 ((fboundp 'move-end-of-line) 'move-end-of-line)
17152 (t 'end-of-line)))
17153 (let ((pos (point)))
17154 (beginning-of-line 1)
17155 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17156 (if (eq special t)
17157 (if (or (< pos (match-beginning 1))
17158 (= pos (match-end 0)))
17159 (goto-char (match-beginning 1))
17160 (goto-char (match-end 0)))
17161 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17162 (goto-char (match-end 0))
17163 (goto-char (match-beginning 1))))
17164 (call-interactively (if (fboundp 'move-end-of-line)
17165 'move-end-of-line
17166 'end-of-line)))))
17167 (org-no-warnings
17168 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17170 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17171 (define-key org-mode-map "\C-e" 'org-end-of-line)
17172 (define-key org-mode-map [home] 'org-beginning-of-line)
17173 (define-key org-mode-map [end] 'org-end-of-line)
17175 (defun org-backward-sentence (&optional arg)
17176 "Go to beginning of sentence, or beginning of table field.
17177 This will call `backward-sentence' or `org-table-beginning-of-field',
17178 depending on context."
17179 (interactive "P")
17180 (cond
17181 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17182 (t (call-interactively 'backward-sentence))))
17184 (defun org-forward-sentence (&optional arg)
17185 "Go to end of sentence, or end of table field.
17186 This will call `forward-sentence' or `org-table-end-of-field',
17187 depending on context."
17188 (interactive "P")
17189 (cond
17190 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17191 (t (call-interactively 'forward-sentence))))
17193 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17194 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17196 (defun org-kill-line (&optional arg)
17197 "Kill line, to tags or end of line."
17198 (interactive "P")
17199 (cond
17200 ((or (not org-special-ctrl-k)
17201 (bolp)
17202 (not (org-on-heading-p)))
17203 (call-interactively 'kill-line))
17204 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17205 (kill-region (point) (match-beginning 1))
17206 (org-set-tags nil t))
17207 (t (kill-region (point) (point-at-eol)))))
17209 (define-key org-mode-map "\C-k" 'org-kill-line)
17211 (defun org-yank (&optional arg)
17212 "Yank. If the kill is a subtree, treat it specially.
17213 This command will look at the current kill and check if is a single
17214 subtree, or a series of subtrees[1]. If it passes the test, and if the
17215 cursor is at the beginning of a line or after the stars of a currently
17216 empty headline, then the yank is handled specially. How exactly depends
17217 on the value of the following variables, both set by default.
17219 org-yank-folded-subtrees
17220 When set, the subtree(s) will be folded after insertion, but only
17221 if doing so would now swallow text after the yanked text.
17223 org-yank-adjusted-subtrees
17224 When set, the subtree will be promoted or demoted in order to
17225 fit into the local outline tree structure, which means that the level
17226 will be adjusted so that it becomes the smaller one of the two
17227 *visible* surrounding headings.
17229 Any prefix to this command will cause `yank' to be called directly with
17230 no special treatment. In particular, a simple `C-u' prefix will just
17231 plainly yank the text as it is.
17233 \[1] The test checks if the first non-white line is a heading
17234 and if there are no other headings with fewer stars."
17235 (interactive "P")
17236 (org-yank-generic 'yank arg))
17238 (defun org-yank-generic (command arg)
17239 "Perform some yank-like command.
17241 This function implements the behavior described in the `org-yank'
17242 documentation. However, it has been generalized to work for any
17243 interactive command with similar behavior."
17245 ;; pretend to be command COMMAND
17246 (setq this-command command)
17248 (if arg
17249 (call-interactively command)
17251 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17252 (and (org-kill-is-subtree-p)
17253 (or (bolp)
17254 (and (looking-at "[ \t]*$")
17255 (string-match
17256 "\\`\\*+\\'"
17257 (buffer-substring (point-at-bol) (point)))))))
17258 swallowp)
17259 (cond
17260 ((and subtreep org-yank-folded-subtrees)
17261 (let ((beg (point))
17262 end)
17263 (if (and subtreep org-yank-adjusted-subtrees)
17264 (org-paste-subtree nil nil 'for-yank)
17265 (call-interactively command))
17267 (setq end (point))
17268 (goto-char beg)
17269 (when (and (bolp) subtreep
17270 (not (setq swallowp
17271 (org-yank-folding-would-swallow-text beg end))))
17272 (or (looking-at outline-regexp)
17273 (re-search-forward (concat "^" outline-regexp) end t))
17274 (while (and (< (point) end) (looking-at outline-regexp))
17275 (hide-subtree)
17276 (org-cycle-show-empty-lines 'folded)
17277 (condition-case nil
17278 (outline-forward-same-level 1)
17279 (error (goto-char end)))))
17280 (when swallowp
17281 (message
17282 "Inserted text not folded because that would swallow text"))
17284 (goto-char end)
17285 (skip-chars-forward " \t\n\r")
17286 (beginning-of-line 1)
17287 (push-mark beg 'nomsg)))
17288 ((and subtreep org-yank-adjusted-subtrees)
17289 (let ((beg (point-at-bol)))
17290 (org-paste-subtree nil nil 'for-yank)
17291 (push-mark beg 'nomsg)))
17293 (call-interactively command))))))
17295 (defun org-yank-folding-would-swallow-text (beg end)
17296 "Would hide-subtree at BEG swallow any text after END?"
17297 (let (level)
17298 (save-excursion
17299 (goto-char beg)
17300 (when (or (looking-at outline-regexp)
17301 (re-search-forward (concat "^" outline-regexp) end t))
17302 (setq level (org-outline-level)))
17303 (goto-char end)
17304 (skip-chars-forward " \t\r\n\v\f")
17305 (if (or (eobp)
17306 (and (bolp) (looking-at org-outline-regexp)
17307 (<= (org-outline-level) level)))
17308 nil ; Nothing would be swallowed
17309 t)))) ; something would swallow
17311 (define-key org-mode-map "\C-y" 'org-yank)
17313 (defun org-invisible-p ()
17314 "Check if point is at a character currently not visible."
17315 ;; Early versions of noutline don't have `outline-invisible-p'.
17316 (if (fboundp 'outline-invisible-p)
17317 (outline-invisible-p)
17318 (get-char-property (point) 'invisible)))
17320 (defun org-invisible-p2 ()
17321 "Check if point is at a character currently not visible."
17322 (save-excursion
17323 (if (and (eolp) (not (bobp))) (backward-char 1))
17324 ;; Early versions of noutline don't have `outline-invisible-p'.
17325 (if (fboundp 'outline-invisible-p)
17326 (outline-invisible-p)
17327 (get-char-property (point) 'invisible))))
17329 (defun org-back-to-heading (&optional invisible-ok)
17330 "Call `outline-back-to-heading', but provide a better error message."
17331 (condition-case nil
17332 (outline-back-to-heading invisible-ok)
17333 (error (error "Before first headline at position %d in buffer %s"
17334 (point) (current-buffer)))))
17336 (defun org-before-first-heading-p ()
17337 "Before first heading?"
17338 (save-excursion
17339 (null (re-search-backward "^\\*+ " nil t))))
17341 (defun org-on-heading-p (&optional ignored)
17342 (outline-on-heading-p t))
17343 (defun org-at-heading-p (&optional ignored)
17344 (outline-on-heading-p t))
17346 (defun org-at-heading-or-item-p ()
17347 (or (org-on-heading-p) (org-at-item-p)))
17349 (defun org-on-target-p ()
17350 (or (org-in-regexp org-radio-target-regexp)
17351 (org-in-regexp org-target-regexp)))
17353 (defun org-up-heading-all (arg)
17354 "Move to the heading line of which the present line is a subheading.
17355 This function considers both visible and invisible heading lines.
17356 With argument, move up ARG levels."
17357 (if (fboundp 'outline-up-heading-all)
17358 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17359 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17361 (defun org-up-heading-safe ()
17362 "Move to the heading line of which the present line is a subheading.
17363 This version will not throw an error. It will return the level of the
17364 headline found, or nil if no higher level is found.
17366 Also, this function will be a lot faster than `outline-up-heading',
17367 because it relies on stars being the outline starters. This can really
17368 make a significant difference in outlines with very many siblings."
17369 (let (start-level re)
17370 (org-back-to-heading t)
17371 (setq start-level (funcall outline-level))
17372 (if (equal start-level 1)
17374 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17375 (if (re-search-backward re nil t)
17376 (funcall outline-level)))))
17378 (defun org-first-sibling-p ()
17379 "Is this heading the first child of its parents?"
17380 (interactive)
17381 (let ((re (concat "^" outline-regexp))
17382 level l)
17383 (unless (org-at-heading-p t)
17384 (error "Not at a heading"))
17385 (setq level (funcall outline-level))
17386 (save-excursion
17387 (if (not (re-search-backward re nil t))
17389 (setq l (funcall outline-level))
17390 (< l level)))))
17392 (defun org-goto-sibling (&optional previous)
17393 "Goto the next sibling, even if it is invisible.
17394 When PREVIOUS is set, go to the previous sibling instead. Returns t
17395 when a sibling was found. When none is found, return nil and don't
17396 move point."
17397 (let ((fun (if previous 're-search-backward 're-search-forward))
17398 (pos (point))
17399 (re (concat "^" outline-regexp))
17400 level l)
17401 (when (condition-case nil (org-back-to-heading t) (error nil))
17402 (setq level (funcall outline-level))
17403 (catch 'exit
17404 (or previous (forward-char 1))
17405 (while (funcall fun re nil t)
17406 (setq l (funcall outline-level))
17407 (when (< l level) (goto-char pos) (throw 'exit nil))
17408 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17409 (goto-char pos)
17410 nil))))
17412 (defun org-show-siblings ()
17413 "Show all siblings of the current headline."
17414 (save-excursion
17415 (while (org-goto-sibling) (org-flag-heading nil)))
17416 (save-excursion
17417 (while (org-goto-sibling 'previous)
17418 (org-flag-heading nil))))
17420 (defun org-show-hidden-entry ()
17421 "Show an entry where even the heading is hidden."
17422 (save-excursion
17423 (org-show-entry)))
17425 (defun org-flag-heading (flag &optional entry)
17426 "Flag the current heading. FLAG non-nil means make invisible.
17427 When ENTRY is non-nil, show the entire entry."
17428 (save-excursion
17429 (org-back-to-heading t)
17430 ;; Check if we should show the entire entry
17431 (if entry
17432 (progn
17433 (org-show-entry)
17434 (save-excursion
17435 (and (outline-next-heading)
17436 (org-flag-heading nil))))
17437 (outline-flag-region (max (point-min) (1- (point)))
17438 (save-excursion (outline-end-of-heading) (point))
17439 flag))))
17441 (defun org-get-next-sibling ()
17442 "Move to next heading of the same level, and return point.
17443 If there is no such heading, return nil.
17444 This is like outline-next-sibling, but invisible headings are ok."
17445 (let ((level (funcall outline-level)))
17446 (outline-next-heading)
17447 (while (and (not (eobp)) (> (funcall outline-level) level))
17448 (outline-next-heading))
17449 (if (or (eobp) (< (funcall outline-level) level))
17451 (point))))
17453 (defun org-get-last-sibling ()
17454 "Move to previous heading of the same level, and return point.
17455 If there is no such heading, return nil."
17456 (let ((opoint (point))
17457 (level (funcall outline-level)))
17458 (outline-previous-heading)
17459 (when (and (/= (point) opoint) (outline-on-heading-p t))
17460 (while (and (> (funcall outline-level) level)
17461 (not (bobp)))
17462 (outline-previous-heading))
17463 (if (< (funcall outline-level) level)
17465 (point)))))
17467 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17468 ;; This contains an exact copy of the original function, but it uses
17469 ;; `org-back-to-heading', to make it work also in invisible
17470 ;; trees. And is uses an invisible-OK argument.
17471 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17472 ;; Furthermore, when used inside Org, finding the end of a large subtree
17473 ;; with many children and grandchildren etc, this can be much faster
17474 ;; than the outline version.
17475 (org-back-to-heading invisible-OK)
17476 (let ((first t)
17477 (level (funcall outline-level)))
17478 (if (and (org-mode-p) (< level 1000))
17479 ;; A true heading (not a plain list item), in Org-mode
17480 ;; This means we can easily find the end by looking
17481 ;; only for the right number of stars. Using a regexp to do
17482 ;; this is so much faster than using a Lisp loop.
17483 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17484 (forward-char 1)
17485 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17486 ;; something else, do it the slow way
17487 (while (and (not (eobp))
17488 (or first (> (funcall outline-level) level)))
17489 (setq first nil)
17490 (outline-next-heading)))
17491 (unless to-heading
17492 (if (memq (preceding-char) '(?\n ?\^M))
17493 (progn
17494 ;; Go to end of line before heading
17495 (forward-char -1)
17496 (if (memq (preceding-char) '(?\n ?\^M))
17497 ;; leave blank line before heading
17498 (forward-char -1))))))
17499 (point))
17501 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17502 "Use Org version in org-mode, for dramatic speed-up."
17503 (if (eq major-mode 'org-mode)
17504 (progn
17505 (org-end-of-subtree nil t)
17506 (unless (eobp) (backward-char 1)))
17507 ad-do-it))
17509 (defun org-forward-same-level (arg &optional invisible-ok)
17510 "Move forward to the arg'th subheading at same level as this one.
17511 Stop at the first and last subheadings of a superior heading."
17512 (interactive "p")
17513 (org-back-to-heading invisible-ok)
17514 (org-on-heading-p)
17515 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17516 (re (format "^\\*\\{1,%d\\} " level))
17518 (forward-char 1)
17519 (while (> arg 0)
17520 (while (and (re-search-forward re nil 'move)
17521 (setq l (- (match-end 0) (match-beginning 0) 1))
17522 (= l level)
17523 (not invisible-ok)
17524 (org-invisible-p))
17525 (if (< l level) (setq arg 1)))
17526 (setq arg (1- arg)))
17527 (beginning-of-line 1)))
17529 (defun org-backward-same-level (arg &optional invisible-ok)
17530 "Move backward to the arg'th subheading at same level as this one.
17531 Stop at the first and last subheadings of a superior heading."
17532 (interactive "p")
17533 (org-back-to-heading)
17534 (org-on-heading-p)
17535 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17536 (re (format "^\\*\\{1,%d\\} " level))
17538 (while (> arg 0)
17539 (while (and (re-search-backward re nil 'move)
17540 (setq l (- (match-end 0) (match-beginning 0) 1))
17541 (= l level)
17542 (not invisible-ok)
17543 (org-invisible-p))
17544 (if (< l level) (setq arg 1)))
17545 (setq arg (1- arg)))))
17547 (defun org-show-subtree ()
17548 "Show everything after this heading at deeper levels."
17549 (outline-flag-region
17550 (point)
17551 (save-excursion
17552 (org-end-of-subtree t t))
17553 nil))
17555 (defun org-show-entry ()
17556 "Show the body directly following this heading.
17557 Show the heading too, if it is currently invisible."
17558 (interactive)
17559 (save-excursion
17560 (condition-case nil
17561 (progn
17562 (org-back-to-heading t)
17563 (outline-flag-region
17564 (max (point-min) (1- (point)))
17565 (save-excursion
17566 (if (re-search-forward
17567 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17568 (match-beginning 1)
17569 (point-max)))
17570 nil)
17571 (org-cycle-hide-drawers 'children))
17572 (error nil))))
17574 (defun org-make-options-regexp (kwds &optional extra)
17575 "Make a regular expression for keyword lines."
17576 (concat
17578 "#?[ \t]*\\+\\("
17579 (mapconcat 'regexp-quote kwds "\\|")
17580 (if extra (concat "\\|" extra))
17581 "\\):[ \t]*"
17582 "\\(.*\\)"))
17584 ;; Make isearch reveal the necessary context
17585 (defun org-isearch-end ()
17586 "Reveal context after isearch exits."
17587 (when isearch-success ; only if search was successful
17588 (if (featurep 'xemacs)
17589 ;; Under XEmacs, the hook is run in the correct place,
17590 ;; we directly show the context.
17591 (org-show-context 'isearch)
17592 ;; In Emacs the hook runs *before* restoring the overlays.
17593 ;; So we have to use a one-time post-command-hook to do this.
17594 ;; (Emacs 22 has a special variable, see function `org-mode')
17595 (unless (and (boundp 'isearch-mode-end-hook-quit)
17596 isearch-mode-end-hook-quit)
17597 ;; Only when the isearch was not quitted.
17598 (org-add-hook 'post-command-hook 'org-isearch-post-command
17599 'append 'local)))))
17601 (defun org-isearch-post-command ()
17602 "Remove self from hook, and show context."
17603 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17604 (org-show-context 'isearch))
17607 ;;;; Integration with and fixes for other packages
17609 ;;; Imenu support
17611 (defvar org-imenu-markers nil
17612 "All markers currently used by Imenu.")
17613 (make-variable-buffer-local 'org-imenu-markers)
17615 (defun org-imenu-new-marker (&optional pos)
17616 "Return a new marker for use by Imenu, and remember the marker."
17617 (let ((m (make-marker)))
17618 (move-marker m (or pos (point)))
17619 (push m org-imenu-markers)
17622 (defun org-imenu-get-tree ()
17623 "Produce the index for Imenu."
17624 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17625 (setq org-imenu-markers nil)
17626 (let* ((n org-imenu-depth)
17627 (re (concat "^" outline-regexp))
17628 (subs (make-vector (1+ n) nil))
17629 (last-level 0)
17630 m level head)
17631 (save-excursion
17632 (save-restriction
17633 (widen)
17634 (goto-char (point-max))
17635 (while (re-search-backward re nil t)
17636 (setq level (org-reduced-level (funcall outline-level)))
17637 (when (<= level n)
17638 (looking-at org-complex-heading-regexp)
17639 (setq head (org-link-display-format
17640 (org-match-string-no-properties 4))
17641 m (org-imenu-new-marker))
17642 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17643 (if (>= level last-level)
17644 (push (cons head m) (aref subs level))
17645 (push (cons head (aref subs (1+ level))) (aref subs level))
17646 (loop for i from (1+ level) to n do (aset subs i nil)))
17647 (setq last-level level)))))
17648 (aref subs 1)))
17650 (eval-after-load "imenu"
17651 '(progn
17652 (add-hook 'imenu-after-jump-hook
17653 (lambda ()
17654 (if (eq major-mode 'org-mode)
17655 (org-show-context 'org-goto))))))
17657 (defun org-link-display-format (link)
17658 "Replace a link with either the description, or the link target
17659 if no description is present"
17660 (save-match-data
17661 (if (string-match org-bracket-link-analytic-regexp link)
17662 (replace-match (if (match-end 5)
17663 (match-string 5 link)
17664 (concat (match-string 1 link)
17665 (match-string 3 link)))
17666 nil t link)
17667 link)))
17669 ;; Speedbar support
17671 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17672 "Overlay marking the agenda restriction line in speedbar.")
17673 (org-overlay-put org-speedbar-restriction-lock-overlay
17674 'face 'org-agenda-restriction-lock)
17675 (org-overlay-put org-speedbar-restriction-lock-overlay
17676 'help-echo "Agendas are currently limited to this item.")
17677 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17679 (defun org-speedbar-set-agenda-restriction ()
17680 "Restrict future agenda commands to the location at point in speedbar.
17681 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17682 (interactive)
17683 (require 'org-agenda)
17684 (let (p m tp np dir txt)
17685 (cond
17686 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17687 'org-imenu t))
17688 (setq m (get-text-property p 'org-imenu-marker))
17689 (with-current-buffer (marker-buffer m)
17690 (goto-char m)
17691 (org-agenda-set-restriction-lock 'subtree)))
17692 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17693 'speedbar-function 'speedbar-find-file))
17694 (setq tp (previous-single-property-change
17695 (1+ p) 'speedbar-function)
17696 np (next-single-property-change
17697 tp 'speedbar-function)
17698 dir (speedbar-line-directory)
17699 txt (buffer-substring-no-properties (or tp (point-min))
17700 (or np (point-max))))
17701 (with-current-buffer (find-file-noselect
17702 (let ((default-directory dir))
17703 (expand-file-name txt)))
17704 (unless (org-mode-p)
17705 (error "Cannot restrict to non-Org-mode file"))
17706 (org-agenda-set-restriction-lock 'file)))
17707 (t (error "Don't know how to restrict Org-mode's agenda")))
17708 (org-move-overlay org-speedbar-restriction-lock-overlay
17709 (point-at-bol) (point-at-eol))
17710 (setq current-prefix-arg nil)
17711 (org-agenda-maybe-redo)))
17713 (eval-after-load "speedbar"
17714 '(progn
17715 (speedbar-add-supported-extension ".org")
17716 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17717 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17718 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17719 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17720 (add-hook 'speedbar-visiting-tag-hook
17721 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17724 ;;; Fixes and Hacks for problems with other packages
17726 ;; Make flyspell not check words in links, to not mess up our keymap
17727 (defun org-mode-flyspell-verify ()
17728 "Don't let flyspell put overlays at active buttons."
17729 (and (not (get-text-property (point) 'keymap))
17730 (not (get-text-property (point) 'org-no-flyspell))))
17732 (defun org-remove-flyspell-overlays-in (beg end)
17733 "Remove flyspell overlays in region."
17734 (and (org-bound-and-true-p flyspell-mode)
17735 (fboundp 'flyspell-delete-region-overlays)
17736 (flyspell-delete-region-overlays beg end))
17737 (add-text-properties beg end '(org-no-flyspell t)))
17739 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17740 (eval-after-load "bookmark"
17741 '(if (boundp 'bookmark-after-jump-hook)
17742 ;; We can use the hook
17743 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17744 ;; Hook not available, use advice
17745 (defadvice bookmark-jump (after org-make-visible activate)
17746 "Make the position visible."
17747 (org-bookmark-jump-unhide))))
17749 ;; Make sure saveplace shows the location if it was hidden
17750 (eval-after-load "saveplace"
17751 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17752 "Make the position visible."
17753 (org-bookmark-jump-unhide)))
17755 ;; Make sure ecb shows the location if it was hidden
17756 (eval-after-load "ecb"
17757 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17758 "Make hierarchy visible when jumping into location from ECB tree buffer."
17759 (if (eq major-mode 'org-mode)
17760 (org-show-context))))
17762 (defun org-bookmark-jump-unhide ()
17763 "Unhide the current position, to show the bookmark location."
17764 (and (org-mode-p)
17765 (or (org-invisible-p)
17766 (save-excursion (goto-char (max (point-min) (1- (point))))
17767 (org-invisible-p)))
17768 (org-show-context 'bookmark-jump)))
17770 ;; Make session.el ignore our circular variable
17771 (eval-after-load "session"
17772 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17774 ;;;; Experimental code
17776 (defun org-closed-in-range ()
17777 "Sparse tree of items closed in a certain time range.
17778 Still experimental, may disappear in the future."
17779 (interactive)
17780 ;; Get the time interval from the user.
17781 (let* ((time1 (org-float-time
17782 (org-read-date nil 'to-time nil "Starting date: ")))
17783 (time2 (org-float-time
17784 (org-read-date nil 'to-time nil "End date:")))
17785 ;; callback function
17786 (callback (lambda ()
17787 (let ((time
17788 (org-float-time
17789 (apply 'encode-time
17790 (org-parse-time-string
17791 (match-string 1))))))
17792 ;; check if time in interval
17793 (and (>= time time1) (<= time time2))))))
17794 ;; make tree, check each match with the callback
17795 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17797 ;;;; Finish up
17799 (provide 'org)
17801 (run-hooks 'org-load-hook)
17803 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17805 ;;; org.el ends here