Release 6.33b
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob0c224280a6182de66a0723722b17eeaaee22727f
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.33b
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.33b"
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 An entry that is just a list with a single string will be interpreted
616 as a descriptive headline that will be added when listing the speed
617 copmmands in the Help buffer using the `?' speed command."
618 :group 'org-structure
619 :type '(repeat :value ("k" . ignore)
620 (choice :value ("k" . ignore)
621 (list :tag "Descriptive Headline" (string :tag "Headline"))
622 (cons :tag "Letter and Command"
623 (string :tag "Command letter")
624 (choice
625 (function)
626 (sexp))))))
628 (defgroup org-cycle nil
629 "Options concerning visibility cycling in Org-mode."
630 :tag "Org Cycle"
631 :group 'org-structure)
633 (defcustom org-cycle-skip-children-state-if-no-children t
634 "Non-nil means, skip CHILDREN state in entries that don't have any."
635 :group 'org-cycle
636 :type 'boolean)
638 (defcustom org-cycle-max-level nil
639 "Maximum level which should still be subject to visibility cycling.
640 Levels higher than this will, for cycling, be treated as text, not a headline.
641 When `org-odd-levels-only' is set, a value of N in this variable actually
642 means 2N-1 stars as the limiting headline.
643 When nil, cycle all levels.
644 Note that the limiting level of cycling is also influenced by
645 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
646 `org-inlinetask-min-level' is, cycling will be limited to levels one less
647 than its value."
648 :group 'org-cycle
649 :type '(choice
650 (const :tag "No limit" nil)
651 (integer :tag "Maximum level")))
653 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
654 "Names of drawers. Drawers are not opened by cycling on the headline above.
655 Drawers only open with a TAB on the drawer line itself. A drawer looks like
656 this:
657 :DRAWERNAME:
658 .....
659 :END:
660 The drawer \"PROPERTIES\" is special for capturing properties through
661 the property API.
663 Drawers can be defined on the per-file basis with a line like:
665 #+DRAWERS: HIDDEN STATE PROPERTIES"
666 :group 'org-structure
667 :group 'org-cycle
668 :type '(repeat (string :tag "Drawer Name")))
670 (defcustom org-hide-block-startup nil
671 "Non-nil means, , entering Org-mode will fold all blocks.
672 This can also be set in on a per-file basis with
674 #+STARTUP: hideblocks
675 #+STARTUP: showblocks"
676 :group 'org-startup
677 :group 'org-cycle
678 :type 'boolean)
680 (defcustom org-cycle-global-at-bob nil
681 "Cycle globally if cursor is at beginning of buffer and not at a headline.
682 This makes it possible to do global cycling without having to use S-TAB or
683 C-u TAB. For this special case to work, the first line of the buffer
684 must not be a headline - it may be empty or some other text. When used in
685 this way, `org-cycle-hook' is disables temporarily, to make sure the
686 cursor stays at the beginning of the buffer.
687 When this option is nil, don't do anything special at the beginning
688 of the buffer."
689 :group 'org-cycle
690 :type 'boolean)
692 (defcustom org-cycle-level-after-item/entry-creation t
693 "Non-nil means, cycle entry level or item indentation in new empty entries.
695 When the cursor is at the end of an empty headline, i.e with only stars
696 and maybe a TODO keyword, TAB will then switch the entry to become a child,
697 and then all possible anchestor states, before returning to the original state.
698 This makes data entry extremely fast: M-RET to create a new headline,
699 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
701 When the cursor is at the end of an empty plain list item, one TAB will
702 make it a subitem, two or more tabs will back up to make this an item
703 higher up in the item hierarchy."
704 :group 'org-cycle
705 :type 'boolean)
707 (defcustom org-cycle-emulate-tab t
708 "Where should `org-cycle' emulate TAB.
709 nil Never
710 white Only in completely white lines
711 whitestart Only at the beginning of lines, before the first non-white char
712 t Everywhere except in headlines
713 exc-hl-bol Everywhere except at the start of a headline
714 If TAB is used in a place where it does not emulate TAB, the current subtree
715 visibility is cycled."
716 :group 'org-cycle
717 :type '(choice (const :tag "Never" nil)
718 (const :tag "Only in completely white lines" white)
719 (const :tag "Before first char in a line" whitestart)
720 (const :tag "Everywhere except in headlines" t)
721 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
724 (defcustom org-cycle-separator-lines 2
725 "Number of empty lines needed to keep an empty line between collapsed trees.
726 If you leave an empty line between the end of a subtree and the following
727 headline, this empty line is hidden when the subtree is folded.
728 Org-mode will leave (exactly) one empty line visible if the number of
729 empty lines is equal or larger to the number given in this variable.
730 So the default 2 means, at least 2 empty lines after the end of a subtree
731 are needed to produce free space between a collapsed subtree and the
732 following headline.
734 If the number is negative, and the number of empty lines is at least -N,
735 all empty lines are shown.
737 Special case: when 0, never leave empty lines in collapsed view."
738 :group 'org-cycle
739 :type 'integer)
740 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
742 (defcustom org-pre-cycle-hook nil
743 "Hook that is run before visibility cycling is happening.
744 The function(s) in this hook must accept a single argument which indicates
745 the new state that will be set right after running this hook. The
746 argument is a symbol. Before a global state change, it can have the values
747 `overview', `content', or `all'. Before a local state change, it can have
748 the values `folded', `children', or `subtree'."
749 :group 'org-cycle
750 :type 'hook)
752 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
753 org-cycle-hide-drawers
754 org-cycle-show-empty-lines
755 org-optimize-window-after-visibility-change)
756 "Hook that is run after `org-cycle' has changed the buffer visibility.
757 The function(s) in this hook must accept a single argument which indicates
758 the new state that was set by the most recent `org-cycle' command. The
759 argument is a symbol. After a global state change, it can have the values
760 `overview', `content', or `all'. After a local state change, it can have
761 the values `folded', `children', or `subtree'."
762 :group 'org-cycle
763 :type 'hook)
765 (defgroup org-edit-structure nil
766 "Options concerning structure editing in Org-mode."
767 :tag "Org Edit Structure"
768 :group 'org-structure)
770 (defcustom org-odd-levels-only nil
771 "Non-nil means, skip even levels and only use odd levels for the outline.
772 This has the effect that two stars are being added/taken away in
773 promotion/demotion commands. It also influences how levels are
774 handled by the exporters.
775 Changing it requires restart of `font-lock-mode' to become effective
776 for fontification also in regions already fontified.
777 You may also set this on a per-file basis by adding one of the following
778 lines to the buffer:
780 #+STARTUP: odd
781 #+STARTUP: oddeven"
782 :group 'org-edit-structure
783 :group 'org-font-lock
784 :type 'boolean)
786 (defcustom org-adapt-indentation t
787 "Non-nil means, adapt indentation to outline node level.
789 When this variable is set, Org assumes that you write outlines by
790 indenting text in each node to align with the headline (after the stars).
791 The following issues are influenced by this variable:
793 - When this is set and the *entire* text in an entry is indented, the
794 indentation is increased by one space in a demotion command, and
795 decreased by one in a promotion command. If any line in the entry
796 body starts with text at column 0, indentation is not changed at all.
798 - Property drawers and planning information is inserted indented when
799 this variable s set. When nil, they will not be indented.
801 - TAB indents a line relative to context. The lines below a headline
802 will be indented when this variable is set.
804 Note that this is all about true indentation, by adding and removing
805 space characters. See also `org-indent.el' which does level-dependent
806 indentation in a virtual way, i.e. at display time in Emacs."
807 :group 'org-edit-structure
808 :type 'boolean)
810 (defcustom org-special-ctrl-a/e nil
811 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
813 When t, `C-a' will bring back the cursor to the beginning of the
814 headline text, i.e. after the stars and after a possible TODO keyword.
815 In an item, this will be the position after the bullet.
816 When the cursor is already at that position, another `C-a' will bring
817 it to the beginning of the line.
819 `C-e' will jump to the end of the headline, ignoring the presence of tags
820 in the headline. A second `C-e' will then jump to the true end of the
821 line, after any tags. This also means that, when this variable is
822 non-nil, `C-e' also will never jump beyond the end of the heading of a
823 folded section, i.e. not after the ellipses.
825 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
826 going to the true line boundary first. Only a directly following, identical
827 keypress will bring the cursor to the special positions.
829 This may also be a cons cell where the behavior for `C-a' and `C-e' is
830 set separately."
831 :group 'org-edit-structure
832 :type '(choice
833 (const :tag "off" nil)
834 (const :tag "on: after stars/bullet and before tags first" t)
835 (const :tag "reversed: true line boundary first" reversed)
836 (cons :tag "Set C-a and C-e separately"
837 (choice :tag "Special C-a"
838 (const :tag "off" nil)
839 (const :tag "on: after stars/bullet first" t)
840 (const :tag "reversed: before stars/bullet first" reversed))
841 (choice :tag "Special C-e"
842 (const :tag "off" nil)
843 (const :tag "on: before tags first" t)
844 (const :tag "reversed: after tags first" reversed)))))
845 (if (fboundp 'defvaralias)
846 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
848 (defcustom org-special-ctrl-k nil
849 "Non-nil means `C-k' will behave specially in headlines.
850 When nil, `C-k' will call the default `kill-line' command.
851 When t, the following will happen while the cursor is in the headline:
853 - When the cursor is at the beginning of a headline, kill the entire
854 line and possible the folded subtree below the line.
855 - When in the middle of the headline text, kill the headline up to the tags.
856 - When after the headline text, kill the tags."
857 :group 'org-edit-structure
858 :type 'boolean)
860 (defcustom org-yank-folded-subtrees t
861 "Non-nil means, when yanking subtrees, fold them.
862 If the kill is a single subtree, or a sequence of subtrees, i.e. if
863 it starts with a heading and all other headings in it are either children
864 or siblings, then fold all the subtrees. However, do this only if no
865 text after the yank would be swallowed into a folded tree by this action."
866 :group 'org-edit-structure
867 :type 'boolean)
869 (defcustom org-yank-adjusted-subtrees nil
870 "Non-nil means, when yanking subtrees, adjust the level.
871 With this setting, `org-paste-subtree' is used to insert the subtree, see
872 this function for details."
873 :group 'org-edit-structure
874 :type 'boolean)
876 (defcustom org-M-RET-may-split-line '((default . t))
877 "Non-nil means, M-RET will split the line at the cursor position.
878 When nil, it will go to the end of the line before making a
879 new line.
880 You may also set this option in a different way for different
881 contexts. Valid contexts are:
883 headline when creating a new headline
884 item when creating a new item
885 table in a table field
886 default the value to be used for all contexts not explicitly
887 customized"
888 :group 'org-structure
889 :group 'org-table
890 :type '(choice
891 (const :tag "Always" t)
892 (const :tag "Never" nil)
893 (repeat :greedy t :tag "Individual contexts"
894 (cons
895 (choice :tag "Context"
896 (const headline)
897 (const item)
898 (const table)
899 (const default))
900 (boolean)))))
903 (defcustom org-insert-heading-respect-content nil
904 "Non-nil means, insert new headings after the current subtree.
905 When nil, the new heading is created directly after the current line.
906 The commands \\[org-insert-heading-respect-content] and
907 \\[org-insert-todo-heading-respect-content] turn this variable on
908 for the duration of the command."
909 :group 'org-structure
910 :type 'boolean)
912 (defcustom org-blank-before-new-entry '((heading . auto)
913 (plain-list-item . auto))
914 "Should `org-insert-heading' leave a blank line before new heading/item?
915 The value is an alist, with `heading' and `plain-list-item' as car,
916 and a boolean flag as cdr. For plain lists, if the variable
917 `org-empty-line-terminates-plain-lists' is set, the setting here
918 is ignored and no empty line is inserted, to keep the list in tact."
919 :group 'org-edit-structure
920 :type '(list
921 (cons (const heading)
922 (choice (const :tag "Never" nil)
923 (const :tag "Always" t)
924 (const :tag "Auto" auto)))
925 (cons (const plain-list-item)
926 (choice (const :tag "Never" nil)
927 (const :tag "Always" t)
928 (const :tag "Auto" auto)))))
930 (defcustom org-insert-heading-hook nil
931 "Hook being run after inserting a new heading."
932 :group 'org-edit-structure
933 :type 'hook)
935 (defcustom org-enable-fixed-width-editor t
936 "Non-nil means, lines starting with \":\" are treated as fixed-width.
937 This currently only means, they are never auto-wrapped.
938 When nil, such lines will be treated like ordinary lines.
939 See also the QUOTE keyword."
940 :group 'org-edit-structure
941 :type 'boolean)
944 (defcustom org-goto-auto-isearch t
945 "Non-nil means, typing characters in org-goto starts incremental search."
946 :group 'org-edit-structure
947 :type 'boolean)
949 (defgroup org-sparse-trees nil
950 "Options concerning sparse trees in Org-mode."
951 :tag "Org Sparse Trees"
952 :group 'org-structure)
954 (defcustom org-highlight-sparse-tree-matches t
955 "Non-nil means, highlight all matches that define a sparse tree.
956 The highlights will automatically disappear the next time the buffer is
957 changed by an edit command."
958 :group 'org-sparse-trees
959 :type 'boolean)
961 (defcustom org-remove-highlights-with-change t
962 "Non-nil means, any change to the buffer will remove temporary highlights.
963 Such highlights are created by `org-occur' and `org-clock-display'.
964 When nil, `C-c C-c needs to be used to get rid of the highlights.
965 The highlights created by `org-preview-latex-fragment' always need
966 `C-c C-c' to be removed."
967 :group 'org-sparse-trees
968 :group 'org-time
969 :type 'boolean)
972 (defcustom org-occur-hook '(org-first-headline-recenter)
973 "Hook that is run after `org-occur' has constructed a sparse tree.
974 This can be used to recenter the window to show as much of the structure
975 as possible."
976 :group 'org-sparse-trees
977 :type 'hook)
979 (defgroup org-imenu-and-speedbar nil
980 "Options concerning imenu and speedbar in Org-mode."
981 :tag "Org Imenu and Speedbar"
982 :group 'org-structure)
984 (defcustom org-imenu-depth 2
985 "The maximum level for Imenu access to Org-mode headlines.
986 This also applied for speedbar access."
987 :group 'org-imenu-and-speedbar
988 :type 'integer)
990 (defgroup org-table nil
991 "Options concerning tables in Org-mode."
992 :tag "Org Table"
993 :group 'org)
995 (defcustom org-enable-table-editor 'optimized
996 "Non-nil means, lines starting with \"|\" are handled by the table editor.
997 When nil, such lines will be treated like ordinary lines.
999 When equal to the symbol `optimized', the table editor will be optimized to
1000 do the following:
1001 - Automatic overwrite mode in front of whitespace in table fields.
1002 This makes the structure of the table stay in tact as long as the edited
1003 field does not exceed the column width.
1004 - Minimize the number of realigns. Normally, the table is aligned each time
1005 TAB or RET are pressed to move to another field. With optimization this
1006 happens only if changes to a field might have changed the column width.
1007 Optimization requires replacing the functions `self-insert-command',
1008 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1009 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1010 very good at guessing when a re-align will be necessary, but you can always
1011 force one with \\[org-ctrl-c-ctrl-c].
1013 If you would like to use the optimized version in Org-mode, but the
1014 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1016 This variable can be used to turn on and off the table editor during a session,
1017 but in order to toggle optimization, a restart is required.
1019 See also the variable `org-table-auto-blank-field'."
1020 :group 'org-table
1021 :type '(choice
1022 (const :tag "off" nil)
1023 (const :tag "on" t)
1024 (const :tag "on, optimized" optimized)))
1026 (defcustom org-self-insert-cluster-for-undo t
1027 "Non-nil means cluster self-insert commands for undo when possible.
1028 If this is set, then, like in the Emacs command loop, 20 consecutive
1029 characters will be undone together.
1030 This is configurable, because there is some impact on typing performance."
1031 :group 'org-table
1032 :type 'boolean)
1034 (defcustom org-table-tab-recognizes-table.el t
1035 "Non-nil means, TAB will automatically notice a table.el table.
1036 When it sees such a table, it moves point into it and - if necessary -
1037 calls `table-recognize-table'."
1038 :group 'org-table-editing
1039 :type 'boolean)
1041 (defgroup org-link nil
1042 "Options concerning links in Org-mode."
1043 :tag "Org Link"
1044 :group 'org)
1046 (defvar org-link-abbrev-alist-local nil
1047 "Buffer-local version of `org-link-abbrev-alist', which see.
1048 The value of this is taken from the #+LINK lines.")
1049 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1051 (defcustom org-link-abbrev-alist nil
1052 "Alist of link abbreviations.
1053 The car of each element is a string, to be replaced at the start of a link.
1054 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1055 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1057 [[linkkey:tag][description]]
1059 The 'linkkey' must be a word word, starting with a letter, followed
1060 by letters, numbers, '-' or '_'.
1062 If REPLACE is a string, the tag will simply be appended to create the link.
1063 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1064 the placeholder \"%h\" will cause a url-encoded version of the tag to
1065 be inserted at that point (see the function `url-hexify-string').
1067 REPLACE may also be a function that will be called with the tag as the
1068 only argument to create the link, which should be returned as a string.
1070 See the manual for examples."
1071 :group 'org-link
1072 :type '(repeat
1073 (cons
1074 (string :tag "Protocol")
1075 (choice
1076 (string :tag "Format")
1077 (function)))))
1079 (defcustom org-descriptive-links t
1080 "Non-nil means, hide link part and only show description of bracket links.
1081 Bracket links are like [[link][description]]. This variable sets the initial
1082 state in new org-mode buffers. The setting can then be toggled on a
1083 per-buffer basis from the Org->Hyperlinks menu."
1084 :group 'org-link
1085 :type 'boolean)
1087 (defcustom org-link-file-path-type 'adaptive
1088 "How the path name in file links should be stored.
1089 Valid values are:
1091 relative Relative to the current directory, i.e. the directory of the file
1092 into which the link is being inserted.
1093 absolute Absolute path, if possible with ~ for home directory.
1094 noabbrev Absolute path, no abbreviation of home directory.
1095 adaptive Use relative path for files in the current directory and sub-
1096 directories of it. For other files, use an absolute path."
1097 :group 'org-link
1098 :type '(choice
1099 (const relative)
1100 (const absolute)
1101 (const noabbrev)
1102 (const adaptive)))
1104 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1105 "Types of links that should be activated in Org-mode files.
1106 This is a list of symbols, each leading to the activation of a certain link
1107 type. In principle, it does not hurt to turn on most link types - there may
1108 be a small gain when turning off unused link types. The types are:
1110 bracket The recommended [[link][description]] or [[link]] links with hiding.
1111 angular Links in angular brackets that may contain whitespace like
1112 <bbdb:Carsten Dominik>.
1113 plain Plain links in normal text, no whitespace, like http://google.com.
1114 radio Text that is matched by a radio target, see manual for details.
1115 tag Tag settings in a headline (link to tag search).
1116 date Time stamps (link to calendar).
1117 footnote Footnote labels.
1119 Changing this variable requires a restart of Emacs to become effective."
1120 :group 'org-link
1121 :type '(set :greedy t
1122 (const :tag "Double bracket links (new style)" bracket)
1123 (const :tag "Angular bracket links (old style)" angular)
1124 (const :tag "Plain text links" plain)
1125 (const :tag "Radio target matches" radio)
1126 (const :tag "Tags" tag)
1127 (const :tag "Timestamps" date)
1128 (const :tag "Footnotes" footnote)))
1130 (defcustom org-make-link-description-function nil
1131 "Function to use to generate link descriptions from links. If
1132 nil the link location will be used. This function must take two
1133 parameters; the first is the link and the second the description
1134 org-insert-link has generated, and should return the description
1135 to use."
1136 :group 'org-link
1137 :type 'function)
1139 (defgroup org-link-store nil
1140 "Options concerning storing links in Org-mode."
1141 :tag "Org Store Link"
1142 :group 'org-link)
1144 (defcustom org-email-link-description-format "Email %c: %.30s"
1145 "Format of the description part of a link to an email or usenet message.
1146 The following %-escapes will be replaced by corresponding information:
1148 %F full \"From\" field
1149 %f name, taken from \"From\" field, address if no name
1150 %T full \"To\" field
1151 %t first name in \"To\" field, address if no name
1152 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1153 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1154 %s subject
1155 %m message-id.
1157 You may use normal field width specification between the % and the letter.
1158 This is for example useful to limit the length of the subject.
1160 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1161 :group 'org-link-store
1162 :type 'string)
1164 (defcustom org-from-is-user-regexp
1165 (let (r1 r2)
1166 (when (and user-mail-address (not (string= user-mail-address "")))
1167 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1168 (when (and user-full-name (not (string= user-full-name "")))
1169 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1170 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1171 "Regexp matched against the \"From:\" header of an email or usenet message.
1172 It should match if the message is from the user him/herself."
1173 :group 'org-link-store
1174 :type 'regexp)
1176 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1177 "Non-nil means, storing a link to an Org file will use entry IDs.
1179 Note that before this variable is even considered, org-id must be loaded,
1180 so please customize `org-modules' and turn it on.
1182 The variable can have the following values:
1184 t Create an ID if needed to make a link to the current entry.
1186 create-if-interactive
1187 If `org-store-link' is called directly (interactively, as a user
1188 command), do create an ID to support the link. But when doing the
1189 job for remember, only use the ID if it already exists. The
1190 purpose of this setting is to avoid proliferation of unwanted
1191 IDs, just because you happen to be in an Org file when you
1192 call `org-remember' that automatically and preemptively
1193 creates a link. If you do want to get an ID link in a remember
1194 template to an entry not having an ID, create it first by
1195 explicitly creating a link to it, using `C-c C-l' first.
1197 create-if-interactive-and-no-custom-id
1198 Like create-if-interactive, but do not create an ID if there is
1199 a CUSTOM_ID property defined in the entry. This is the default.
1201 use-existing
1202 Use existing ID, do not create one.
1204 nil Never use an ID to make a link, instead link using a text search for
1205 the headline text."
1206 :group 'org-link-store
1207 :type '(choice
1208 (const :tag "Create ID to make link" t)
1209 (const :tag "Create if storing link interactively"
1210 create-if-interactive)
1211 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1212 create-if-interactive-and-no-custom-id)
1213 (const :tag "Only use existing" use-existing)
1214 (const :tag "Do not use ID to create link" nil)))
1216 (defcustom org-context-in-file-links t
1217 "Non-nil means, file links from `org-store-link' contain context.
1218 A search string will be added to the file name with :: as separator and
1219 used to find the context when the link is activated by the command
1220 `org-open-at-point'.
1221 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1222 negates this setting for the duration of the command."
1223 :group 'org-link-store
1224 :type 'boolean)
1226 (defcustom org-keep-stored-link-after-insertion nil
1227 "Non-nil means, keep link in list for entire session.
1229 The command `org-store-link' adds a link pointing to the current
1230 location to an internal list. These links accumulate during a session.
1231 The command `org-insert-link' can be used to insert links into any
1232 Org-mode file (offering completion for all stored links). When this
1233 option is nil, every link which has been inserted once using \\[org-insert-link]
1234 will be removed from the list, to make completing the unused links
1235 more efficient."
1236 :group 'org-link-store
1237 :type 'boolean)
1239 (defgroup org-link-follow nil
1240 "Options concerning following links in Org-mode."
1241 :tag "Org Follow Link"
1242 :group 'org-link)
1244 (defcustom org-link-translation-function nil
1245 "Function to translate links with different syntax to Org syntax.
1246 This can be used to translate links created for example by the Planner
1247 or emacs-wiki packages to Org syntax.
1248 The function must accept two parameters, a TYPE containing the link
1249 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1250 which is everything after the link protocol. It should return a cons
1251 with possibly modified values of type and path.
1252 Org contains a function for this, so if you set this variable to
1253 `org-translate-link-from-planner', you should be able follow many
1254 links created by planner."
1255 :group 'org-link-follow
1256 :type 'function)
1258 (defcustom org-follow-link-hook nil
1259 "Hook that is run after a link has been followed."
1260 :group 'org-link-follow
1261 :type 'hook)
1263 (defcustom org-tab-follows-link nil
1264 "Non-nil means, on links TAB will follow the link.
1265 Needs to be set before org.el is loaded.
1266 This really should not be used, it does not make sense, and the
1267 implementation is bad."
1268 :group 'org-link-follow
1269 :type 'boolean)
1271 (defcustom org-return-follows-link nil
1272 "Non-nil means, on links RET will follow the link.
1273 Needs to be set before org.el is loaded."
1274 :group 'org-link-follow
1275 :type 'boolean)
1277 (defcustom org-mouse-1-follows-link
1278 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1279 "Non-nil means, mouse-1 on a link will follow the link.
1280 A longer mouse click will still set point. Does not work on XEmacs.
1281 Needs to be set before org.el is loaded."
1282 :group 'org-link-follow
1283 :type 'boolean)
1285 (defcustom org-mark-ring-length 4
1286 "Number of different positions to be recorded in the ring
1287 Changing this requires a restart of Emacs to work correctly."
1288 :group 'org-link-follow
1289 :type 'integer)
1291 (defcustom org-link-frame-setup
1292 '((vm . vm-visit-folder-other-frame)
1293 (gnus . gnus-other-frame)
1294 (file . find-file-other-window))
1295 "Setup the frame configuration for following links.
1296 When following a link with Emacs, it may often be useful to display
1297 this link in another window or frame. This variable can be used to
1298 set this up for the different types of links.
1299 For VM, use any of
1300 `vm-visit-folder'
1301 `vm-visit-folder-other-frame'
1302 For Gnus, use any of
1303 `gnus'
1304 `gnus-other-frame'
1305 `org-gnus-no-new-news'
1306 For FILE, use any of
1307 `find-file'
1308 `find-file-other-window'
1309 `find-file-other-frame'
1310 For the calendar, use the variable `calendar-setup'.
1311 For BBDB, it is currently only possible to display the matches in
1312 another window."
1313 :group 'org-link-follow
1314 :type '(list
1315 (cons (const vm)
1316 (choice
1317 (const vm-visit-folder)
1318 (const vm-visit-folder-other-window)
1319 (const vm-visit-folder-other-frame)))
1320 (cons (const gnus)
1321 (choice
1322 (const gnus)
1323 (const gnus-other-frame)
1324 (const org-gnus-no-new-news)))
1325 (cons (const file)
1326 (choice
1327 (const find-file)
1328 (const find-file-other-window)
1329 (const find-file-other-frame)))))
1331 (defcustom org-display-internal-link-with-indirect-buffer nil
1332 "Non-nil means, use indirect buffer to display infile links.
1333 Activating internal links (from one location in a file to another location
1334 in the same file) normally just jumps to the location. When the link is
1335 activated with a C-u prefix (or with mouse-3), the link is displayed in
1336 another window. When this option is set, the other window actually displays
1337 an indirect buffer clone of the current buffer, to avoid any visibility
1338 changes to the current buffer."
1339 :group 'org-link-follow
1340 :type 'boolean)
1342 (defcustom org-open-non-existing-files nil
1343 "Non-nil means, `org-open-file' will open non-existing files.
1344 When nil, an error will be generated.
1345 This variable applies only to external applications because they
1346 might choke on non-existing files. If the link is to a file that
1347 will be opened in Emacs, the variable is ignored."
1348 :group 'org-link-follow
1349 :type 'boolean)
1351 (defcustom org-open-directory-means-index-dot-org nil
1352 "Non-nil means, a link to a directory really means to index.org.
1353 When nil, following a directory link will run dired or open a finder/explorer
1354 window on that directory."
1355 :group 'org-link-follow
1356 :type 'boolean)
1358 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1359 "Function and arguments to call for following mailto links.
1360 This is a list with the first element being a lisp function, and the
1361 remaining elements being arguments to the function. In string arguments,
1362 %a will be replaced by the address, and %s will be replaced by the subject
1363 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1364 :group 'org-link-follow
1365 :type '(choice
1366 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1367 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1368 (const :tag "message-mail" (message-mail "%a" "%s"))
1369 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1371 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1372 "Non-nil means, ask for confirmation before executing shell links.
1373 Shell links can be dangerous: just think about a link
1375 [[shell:rm -rf ~/*][Google Search]]
1377 This link would show up in your Org-mode document as \"Google Search\",
1378 but really it would remove your entire home directory.
1379 Therefore we advise against setting this variable to nil.
1380 Just change it to `y-or-n-p' if you want to confirm with a
1381 single keystroke rather than having to type \"yes\"."
1382 :group 'org-link-follow
1383 :type '(choice
1384 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1385 (const :tag "with y-or-n (faster)" y-or-n-p)
1386 (const :tag "no confirmation (dangerous)" nil)))
1388 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1389 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1390 Elisp links can be dangerous: just think about a link
1392 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1394 This link would show up in your Org-mode document as \"Google Search\",
1395 but really it would remove your entire home directory.
1396 Therefore we advise against setting this variable to nil.
1397 Just change it to `y-or-n-p' if you want to confirm with a
1398 single keystroke rather than having to type \"yes\"."
1399 :group 'org-link-follow
1400 :type '(choice
1401 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1402 (const :tag "with y-or-n (faster)" y-or-n-p)
1403 (const :tag "no confirmation (dangerous)" nil)))
1405 (defconst org-file-apps-defaults-gnu
1406 '((remote . emacs)
1407 (system . mailcap)
1408 (t . mailcap))
1409 "Default file applications on a UNIX or GNU/Linux system.
1410 See `org-file-apps'.")
1412 (defconst org-file-apps-defaults-macosx
1413 '((remote . emacs)
1414 (t . "open %s")
1415 (system . "open %s")
1416 ("ps.gz" . "gv %s")
1417 ("eps.gz" . "gv %s")
1418 ("dvi" . "xdvi %s")
1419 ("fig" . "xfig %s"))
1420 "Default file applications on a MacOS X system.
1421 The system \"open\" is known as a default, but we use X11 applications
1422 for some files for which the OS does not have a good default.
1423 See `org-file-apps'.")
1425 (defconst org-file-apps-defaults-windowsnt
1426 (list
1427 '(remote . emacs)
1428 (cons t
1429 (list (if (featurep 'xemacs)
1430 'mswindows-shell-execute
1431 'w32-shell-execute)
1432 "open" 'file))
1433 (cons 'system
1434 (list (if (featurep 'xemacs)
1435 'mswindows-shell-execute
1436 'w32-shell-execute)
1437 "open" 'file)))
1438 "Default file applications on a Windows NT system.
1439 The system \"open\" is used for most files.
1440 See `org-file-apps'.")
1442 (defcustom org-file-apps
1444 (auto-mode . emacs)
1445 ("\\.mm\\'" . default)
1446 ("\\.x?html?\\'" . default)
1447 ("\\.pdf\\'" . default)
1449 "External applications for opening `file:path' items in a document.
1450 Org-mode uses system defaults for different file types, but
1451 you can use this variable to set the application for a given file
1452 extension. The entries in this list are cons cells where the car identifies
1453 files and the cdr the corresponding command. Possible values for the
1454 file identifier are
1455 \"regex\" Regular expression matched against the file name. For backward
1456 compatibility, this can also be a string with only alphanumeric
1457 characters, which is then interpreted as an extension.
1458 `directory' Matches a directory
1459 `remote' Matches a remote file, accessible through tramp or efs.
1460 Remote files most likely should be visited through Emacs
1461 because external applications cannot handle such paths.
1462 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1463 so all files Emacs knows how to handle. Using this with
1464 command `emacs' will open most files in Emacs. Beware that this
1465 will also open html files inside Emacs, unless you add
1466 (\"html\" . default) to the list as well.
1467 t Default for files not matched by any of the other options.
1468 `system' The system command to open files, like `open' on Windows
1469 and Mac OS X, and mailcap under GNU/Linux. This is the command
1470 that will be selected if you call `C-c C-o' with a double
1471 `C-u C-u' prefix.
1473 Possible values for the command are:
1474 `emacs' The file will be visited by the current Emacs process.
1475 `default' Use the default application for this file type, which is the
1476 association for t in the list, most likely in the system-specific
1477 part.
1478 This can be used to overrule an unwanted setting in the
1479 system-specific variable.
1480 `system' Use the system command for opening files, like \"open\".
1481 This command is specified by the entry whose car is `system'.
1482 Most likely, the system-specific version of this variable
1483 does define this command, but you can overrule/replace it
1484 here.
1485 string A command to be executed by a shell; %s will be replaced
1486 by the path to the file.
1487 sexp A Lisp form which will be evaluated. The file path will
1488 be available in the Lisp variable `file'.
1489 For more examples, see the system specific constants
1490 `org-file-apps-defaults-macosx'
1491 `org-file-apps-defaults-windowsnt'
1492 `org-file-apps-defaults-gnu'."
1493 :group 'org-link-follow
1494 :type '(repeat
1495 (cons (choice :value ""
1496 (string :tag "Extension")
1497 (const :tag "System command to open files" system)
1498 (const :tag "Default for unrecognized files" t)
1499 (const :tag "Remote file" remote)
1500 (const :tag "Links to a directory" directory)
1501 (const :tag "Any files that have Emacs modes"
1502 auto-mode))
1503 (choice :value ""
1504 (const :tag "Visit with Emacs" emacs)
1505 (const :tag "Use default" default)
1506 (const :tag "Use the system command" system)
1507 (string :tag "Command")
1508 (sexp :tag "Lisp form")))))
1510 (defgroup org-refile nil
1511 "Options concerning refiling entries in Org-mode."
1512 :tag "Org Refile"
1513 :group 'org)
1515 (defcustom org-directory "~/org"
1516 "Directory with org files.
1517 This is just a default location to look for Org files. There is no need
1518 at all to put your files into this directory. It is only used in the
1519 following situations:
1521 1. When a remember template specifies a target file that is not an
1522 absolute path. The path will then be interpreted relative to
1523 `org-directory'
1524 2. When a remember note is filed away in an interactive way (when exiting the
1525 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1526 with `org-directory' as the default path."
1527 :group 'org-refile
1528 :group 'org-remember
1529 :type 'directory)
1531 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1532 "Default target for storing notes.
1533 Used by the hooks for remember.el. This can be a string, or nil to mean
1534 the value of `remember-data-file'.
1535 You can set this on a per-template basis with the variable
1536 `org-remember-templates'."
1537 :group 'org-refile
1538 :group 'org-remember
1539 :type '(choice
1540 (const :tag "Default from remember-data-file" nil)
1541 file))
1543 (defcustom org-goto-interface 'outline
1544 "The default interface to be used for `org-goto'.
1545 Allowed values are:
1546 outline The interface shows an outline of the relevant file
1547 and the correct heading is found by moving through
1548 the outline or by searching with incremental search.
1549 outline-path-completion Headlines in the current buffer are offered via
1550 completion. This is the interface also used by
1551 the refile command."
1552 :group 'org-refile
1553 :type '(choice
1554 (const :tag "Outline" outline)
1555 (const :tag "Outline-path-completion" outline-path-completion)))
1557 (defcustom org-goto-max-level 5
1558 "Maximum level to be considered when running org-goto with refile interface."
1559 :group 'org-refile
1560 :type 'integer)
1562 (defcustom org-reverse-note-order nil
1563 "Non-nil means, store new notes at the beginning of a file or entry.
1564 When nil, new notes will be filed to the end of a file or entry.
1565 This can also be a list with cons cells of regular expressions that
1566 are matched against file names, and values."
1567 :group 'org-remember
1568 :group 'org-refile
1569 :type '(choice
1570 (const :tag "Reverse always" t)
1571 (const :tag "Reverse never" nil)
1572 (repeat :tag "By file name regexp"
1573 (cons regexp boolean))))
1575 (defcustom org-refile-targets nil
1576 "Targets for refiling entries with \\[org-refile].
1577 This is list of cons cells. Each cell contains:
1578 - a specification of the files to be considered, either a list of files,
1579 or a symbol whose function or variable value will be used to retrieve
1580 a file name or a list of file names. If you use `org-agenda-files' for
1581 that, all agenda files will be scanned for targets. Nil means, consider
1582 headings in the current buffer.
1583 - A specification of how to find candidate refile targets. This may be
1584 any of:
1585 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1586 This tag has to be present in all target headlines, inheritance will
1587 not be considered.
1588 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1589 todo keyword.
1590 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1591 headlines that are refiling targets.
1592 - a cons cell (:level . N). Any headline of level N is considered a target.
1593 Note that, when `org-odd-levels-only' is set, level corresponds to
1594 order in hierarchy, not to the number of stars.
1595 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1596 Note that, when `org-odd-levels-only' is set, level corresponds to
1597 order in hierarchy, not to the number of stars.
1599 You can set the variable `org-refile-target-verify-function' to a function
1600 to verify each headline found by the simple critery above.
1602 When this variable is nil, all top-level headlines in the current buffer
1603 are used, equivalent to the value `((nil . (:level . 1))'."
1604 :group 'org-refile
1605 :type '(repeat
1606 (cons
1607 (choice :value org-agenda-files
1608 (const :tag "All agenda files" org-agenda-files)
1609 (const :tag "Current buffer" nil)
1610 (function) (variable) (file))
1611 (choice :tag "Identify target headline by"
1612 (cons :tag "Specific tag" (const :value :tag) (string))
1613 (cons :tag "TODO keyword" (const :value :todo) (string))
1614 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1615 (cons :tag "Level number" (const :value :level) (integer))
1616 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1618 (defcustom org-refile-target-verify-function nil
1619 "Function to verify if the headline at point should be a refile target.
1620 The function will be called without arguments, with point at the
1621 beginning of the headline. It should return t and leave point
1622 where it is if the headline is a valid target for refiling.
1624 If the target should not be selected, the function must return nil.
1625 In addition to this, it may move point to a place from where the search
1626 should be continued. For example, the function may decide that the entire
1627 subtree of the current entry should be excluded and move point to the end
1628 of the subtree."
1629 :group 'org-refile
1630 :type 'function)
1632 (defcustom org-refile-use-outline-path nil
1633 "Non-nil means, provide refile targets as paths.
1634 So a level 3 headline will be available as level1/level2/level3.
1636 When the value is `file', also include the file name (without directory)
1637 into the path. In this case, you can also stop the completion after
1638 the file name, to get entries inserted as top level in the file.
1640 When `full-file-path', include the full file path."
1641 :group 'org-refile
1642 :type '(choice
1643 (const :tag "Not" nil)
1644 (const :tag "Yes" t)
1645 (const :tag "Start with file name" file)
1646 (const :tag "Start with full file path" full-file-path)))
1648 (defcustom org-outline-path-complete-in-steps t
1649 "Non-nil means, complete the outline path in hierarchical steps.
1650 When Org-mode uses the refile interface to select an outline path
1651 \(see variable `org-refile-use-outline-path'), the completion of
1652 the path can be done is a single go, or if can be done in steps down
1653 the headline hierarchy. Going in steps is probably the best if you
1654 do not use a special completion package like `ido' or `icicles'.
1655 However, when using these packages, going in one step can be very
1656 fast, while still showing the whole path to the entry."
1657 :group 'org-refile
1658 :type 'boolean)
1660 (defcustom org-refile-allow-creating-parent-nodes nil
1661 "Non-nil means, allow to create new nodes as refile targets.
1662 New nodes are then created by adding \"/new node name\" to the completion
1663 of an existing node. When the value of this variable is `confirm',
1664 new node creation must be confirmed by the user (recommended)
1665 When nil, the completion must match an existing entry.
1667 Note that, if the new heading is not seen by the criteria
1668 listed in `org-refile-targets', multiple instances of the same
1669 heading would be created by trying again to file under the new
1670 heading."
1671 :group 'org-refile
1672 :type '(choice
1673 (const :tag "Never" nil)
1674 (const :tag "Always" t)
1675 (const :tag "Prompt for confirmation" confirm)))
1677 (defgroup org-todo nil
1678 "Options concerning TODO items in Org-mode."
1679 :tag "Org TODO"
1680 :group 'org)
1682 (defgroup org-progress nil
1683 "Options concerning Progress logging in Org-mode."
1684 :tag "Org Progress"
1685 :group 'org-time)
1687 (defvar org-todo-interpretation-widgets
1689 (:tag "Sequence (cycling hits every state)" sequence)
1690 (:tag "Type (cycling directly to DONE)" type))
1691 "The available interpretation symbols for customizing
1692 `org-todo-keywords'.
1693 Interested libraries should add to this list.")
1695 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1696 "List of TODO entry keyword sequences and their interpretation.
1697 \\<org-mode-map>This is a list of sequences.
1699 Each sequence starts with a symbol, either `sequence' or `type',
1700 indicating if the keywords should be interpreted as a sequence of
1701 action steps, or as different types of TODO items. The first
1702 keywords are states requiring action - these states will select a headline
1703 for inclusion into the global TODO list Org-mode produces. If one of
1704 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1705 signify that no further action is necessary. If \"|\" is not found,
1706 the last keyword is treated as the only DONE state of the sequence.
1708 The command \\[org-todo] cycles an entry through these states, and one
1709 additional state where no keyword is present. For details about this
1710 cycling, see the manual.
1712 TODO keywords and interpretation can also be set on a per-file basis with
1713 the special #+SEQ_TODO and #+TYP_TODO lines.
1715 Each keyword can optionally specify a character for fast state selection
1716 \(in combination with the variable `org-use-fast-todo-selection')
1717 and specifiers for state change logging, using the same syntax
1718 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1719 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1720 indicates to record a time stamp each time this state is selected.
1722 Each keyword may also specify if a timestamp or a note should be
1723 recorded when entering or leaving the state, by adding additional
1724 characters in the parenthesis after the keyword. This looks like this:
1725 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1726 record only the time of the state change. With X and Y being either
1727 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1728 Y when leaving the state if and only if the *target* state does not
1729 define X. You may omit any of the fast-selection key or X or /Y,
1730 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1732 For backward compatibility, this variable may also be just a list
1733 of keywords - in this case the interpretation (sequence or type) will be
1734 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1735 :group 'org-todo
1736 :group 'org-keywords
1737 :type '(choice
1738 (repeat :tag "Old syntax, just keywords"
1739 (string :tag "Keyword"))
1740 (repeat :tag "New syntax"
1741 (cons
1742 (choice
1743 :tag "Interpretation"
1744 ;;Quick and dirty way to see
1745 ;;`org-todo-interpretations'. This takes the
1746 ;;place of item arguments
1747 :convert-widget
1748 (lambda (widget)
1749 (widget-put widget
1750 :args (mapcar
1751 #'(lambda (x)
1752 (widget-convert
1753 (cons 'const x)))
1754 org-todo-interpretation-widgets))
1755 widget))
1756 (repeat
1757 (string :tag "Keyword"))))))
1759 (defvar org-todo-keywords-1 nil
1760 "All TODO and DONE keywords active in a buffer.")
1761 (make-variable-buffer-local 'org-todo-keywords-1)
1762 (defvar org-todo-keywords-for-agenda nil)
1763 (defvar org-done-keywords-for-agenda nil)
1764 (defvar org-drawers-for-agenda nil)
1765 (defvar org-todo-keyword-alist-for-agenda nil)
1766 (defvar org-tag-alist-for-agenda nil)
1767 (defvar org-agenda-contributing-files nil)
1768 (defvar org-not-done-keywords nil)
1769 (make-variable-buffer-local 'org-not-done-keywords)
1770 (defvar org-done-keywords nil)
1771 (make-variable-buffer-local 'org-done-keywords)
1772 (defvar org-todo-heads nil)
1773 (make-variable-buffer-local 'org-todo-heads)
1774 (defvar org-todo-sets nil)
1775 (make-variable-buffer-local 'org-todo-sets)
1776 (defvar org-todo-log-states nil)
1777 (make-variable-buffer-local 'org-todo-log-states)
1778 (defvar org-todo-kwd-alist nil)
1779 (make-variable-buffer-local 'org-todo-kwd-alist)
1780 (defvar org-todo-key-alist nil)
1781 (make-variable-buffer-local 'org-todo-key-alist)
1782 (defvar org-todo-key-trigger nil)
1783 (make-variable-buffer-local 'org-todo-key-trigger)
1785 (defcustom org-todo-interpretation 'sequence
1786 "Controls how TODO keywords are interpreted.
1787 This variable is in principle obsolete and is only used for
1788 backward compatibility, if the interpretation of todo keywords is
1789 not given already in `org-todo-keywords'. See that variable for
1790 more information."
1791 :group 'org-todo
1792 :group 'org-keywords
1793 :type '(choice (const sequence)
1794 (const type)))
1796 (defcustom org-use-fast-todo-selection t
1797 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1798 This variable describes if and under what circumstances the cycling
1799 mechanism for TODO keywords will be replaced by a single-key, direct
1800 selection scheme.
1802 When nil, fast selection is never used.
1804 When the symbol `prefix', it will be used when `org-todo' is called with
1805 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1806 in an agenda buffer.
1808 When t, fast selection is used by default. In this case, the prefix
1809 argument forces cycling instead.
1811 In all cases, the special interface is only used if access keys have actually
1812 been assigned by the user, i.e. if keywords in the configuration are followed
1813 by a letter in parenthesis, like TODO(t)."
1814 :group 'org-todo
1815 :type '(choice
1816 (const :tag "Never" nil)
1817 (const :tag "By default" t)
1818 (const :tag "Only with C-u C-c C-t" prefix)))
1820 (defcustom org-provide-todo-statistics t
1821 "Non-nil means, update todo statistics after insert and toggle.
1822 ALL-HEADLINES means update todo statistics by including headlines
1823 with no TODO keyword as well, counting them as not done.
1824 A list of TODO keywords means the same, but skip keywords that are
1825 not in this list.
1827 When this is set, todo statistics is updated in the parent of the
1828 current entry each time a todo state is changed."
1829 :group 'org-todo
1830 :type '(choice
1831 (const :tag "Yes, only for TODO entries" t)
1832 (const :tag "Yes, including all entries" 'all-headlines)
1833 (repeat :tag "Yes, for TODOs in this list"
1834 (string :tag "TODO keyword"))
1835 (other :tag "No TODO statistics" nil)))
1837 (defcustom org-hierarchical-todo-statistics t
1838 "Non-nil means, TODO statistics covers just direct children.
1839 When nil, all entries in the subtree are considered.
1840 This has only an effect if `org-provide-todo-statistics' is set.
1841 To set this to nil for only a single subtree, use a COOKIE_DATA
1842 property and include the word \"recursive\" into the value."
1843 :group 'org-todo
1844 :type 'boolean)
1846 (defcustom org-after-todo-state-change-hook nil
1847 "Hook which is run after the state of a TODO item was changed.
1848 The new state (a string with a TODO keyword, or nil) is available in the
1849 Lisp variable `state'."
1850 :group 'org-todo
1851 :type 'hook)
1853 (defvar org-blocker-hook nil
1854 "Hook for functions that are allowed to block a state change.
1856 Each function gets as its single argument a property list, see
1857 `org-trigger-hook' for more information about this list.
1859 If any of the functions in this hook returns nil, the state change
1860 is blocked.")
1862 (defvar org-trigger-hook nil
1863 "Hook for functions that are triggered by a state change.
1865 Each function gets as its single argument a property list with at least
1866 the following elements:
1868 (:type type-of-change :position pos-at-entry-start
1869 :from old-state :to new-state)
1871 Depending on the type, more properties may be present.
1873 This mechanism is currently implemented for:
1875 TODO state changes
1876 ------------------
1877 :type todo-state-change
1878 :from previous state (keyword as a string), or nil, or a symbol
1879 'todo' or 'done', to indicate the general type of state.
1880 :to new state, like in :from")
1882 (defcustom org-enforce-todo-dependencies nil
1883 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1884 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1885 be blocked if any prior sibling is not yet done.
1886 Finally, if the parent is blocked because of ordered siblings of its own,
1887 the child will also be blocked.
1888 This variable needs to be set before org.el is loaded, and you need to
1889 restart Emacs after a change to make the change effective. The only way
1890 to change is while Emacs is running is through the customize interface."
1891 :set (lambda (var val)
1892 (set var val)
1893 (if val
1894 (add-hook 'org-blocker-hook
1895 'org-block-todo-from-children-or-siblings-or-parent)
1896 (remove-hook 'org-blocker-hook
1897 'org-block-todo-from-children-or-siblings-or-parent)))
1898 :group 'org-todo
1899 :type 'boolean)
1901 (defcustom org-enforce-todo-checkbox-dependencies nil
1902 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1903 When this is nil, checkboxes have no influence on switching TODO states.
1904 When non-nil, you first need to check off all check boxes before the TODO
1905 entry can be switched to DONE.
1906 This variable needs to be set before org.el is loaded, and you need to
1907 restart Emacs after a change to make the change effective. The only way
1908 to change is while Emacs is running is through the customize interface."
1909 :set (lambda (var val)
1910 (set var val)
1911 (if val
1912 (add-hook 'org-blocker-hook
1913 'org-block-todo-from-checkboxes)
1914 (remove-hook 'org-blocker-hook
1915 'org-block-todo-from-checkboxes)))
1916 :group 'org-todo
1917 :type 'boolean)
1919 (defcustom org-treat-insert-todo-heading-as-state-change nil
1920 "Non-nil means, inserting a TODO heading is treated as state change.
1921 So when the command \\[org-insert-todo-heading] is used, state change
1922 logging will apply if appropriate. When nil, the new TODO item will
1923 be inserted directly, and no logging will take place."
1924 :group 'org-todo
1925 :type 'boolean)
1927 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1928 "Non-nil means, switching TODO states with S-cursor counts as state change.
1929 This is the default behavior. However, setting this to nil allows a
1930 convenient way to select a TODO state and bypass any logging associated
1931 with that."
1932 :group 'org-todo
1933 :type 'boolean)
1935 (defcustom org-todo-state-tags-triggers nil
1936 "Tag changes that should be triggered by TODO state changes.
1937 This is a list. Each entry is
1939 (state-change (tag . flag) .......)
1941 State-change can be a string with a state, and empty string to indicate the
1942 state that has no TODO keyword, or it can be one of the symbols `todo'
1943 or `done', meaning any not-done or done state, respectively."
1944 :group 'org-todo
1945 :group 'org-tags
1946 :type '(repeat
1947 (cons (choice :tag "When changing to"
1948 (const :tag "Not-done state" todo)
1949 (const :tag "Done state" done)
1950 (string :tag "State"))
1951 (repeat
1952 (cons :tag "Tag action"
1953 (string :tag "Tag")
1954 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1956 (defcustom org-log-done nil
1957 "Information to record when a task moves to the DONE state.
1959 Possible values are:
1961 nil Don't add anything, just change the keyword
1962 time Add a time stamp to the task
1963 note Prompt for a note and add it with template `org-log-note-headings'
1965 This option can also be set with on a per-file-basis with
1967 #+STARTUP: nologdone
1968 #+STARTUP: logdone
1969 #+STARTUP: lognotedone
1971 You can have local logging settings for a subtree by setting the LOGGING
1972 property to one or more of these keywords."
1973 :group 'org-todo
1974 :group 'org-progress
1975 :type '(choice
1976 (const :tag "No logging" nil)
1977 (const :tag "Record CLOSED timestamp" time)
1978 (const :tag "Record CLOSED timestamp with note." note)))
1980 ;; Normalize old uses of org-log-done.
1981 (cond
1982 ((eq org-log-done t) (setq org-log-done 'time))
1983 ((and (listp org-log-done) (memq 'done org-log-done))
1984 (setq org-log-done 'note)))
1986 (defcustom org-log-reschedule nil
1987 "Information to record when the scheduling date of a tasks is modified.
1989 Possible values are:
1991 nil Don't add anything, just change the date
1992 time Add a time stamp to the task
1993 note Prompt for a note and add it with template `org-log-note-headings'
1995 This option can also be set with on a per-file-basis with
1997 #+STARTUP: nologreschedule
1998 #+STARTUP: logreschedule
1999 #+STARTUP: lognotereschedule"
2000 :group 'org-todo
2001 :group 'org-progress
2002 :type '(choice
2003 (const :tag "No logging" nil)
2004 (const :tag "Record timestamp" time)
2005 (const :tag "Record timestamp with note." note)))
2007 (defcustom org-log-redeadline nil
2008 "Information to record when the deadline date of a tasks is modified.
2010 Possible values are:
2012 nil Don't add anything, just change the date
2013 time Add a time stamp to the task
2014 note Prompt for a note and add it with template `org-log-note-headings'
2016 This option can also be set with on a per-file-basis with
2018 #+STARTUP: nologredeadline
2019 #+STARTUP: logredeadline
2020 #+STARTUP: lognoteredeadline
2022 You can have local logging settings for a subtree by setting the LOGGING
2023 property to one or more of these keywords."
2024 :group 'org-todo
2025 :group 'org-progress
2026 :type '(choice
2027 (const :tag "No logging" nil)
2028 (const :tag "Record timestamp" time)
2029 (const :tag "Record timestamp with note." note)))
2031 (defcustom org-log-note-clock-out nil
2032 "Non-nil means, record a note when clocking out of an item.
2033 This can also be configured on a per-file basis by adding one of
2034 the following lines anywhere in the buffer:
2036 #+STARTUP: lognoteclock-out
2037 #+STARTUP: nolognoteclock-out"
2038 :group 'org-todo
2039 :group 'org-progress
2040 :type 'boolean)
2042 (defcustom org-log-done-with-time t
2043 "Non-nil means, the CLOSED time stamp will contain date and time.
2044 When nil, only the date will be recorded."
2045 :group 'org-progress
2046 :type 'boolean)
2048 (defcustom org-log-note-headings
2049 '((done . "CLOSING NOTE %t")
2050 (state . "State %-12s from %-12S %t")
2051 (note . "Note taken on %t")
2052 (reschedule . "Rescheduled from %S on %t")
2053 (redeadline . "New deadline from %S on %t")
2054 (clock-out . ""))
2055 "Headings for notes added to entries.
2056 The value is an alist, with the car being a symbol indicating the note
2057 context, and the cdr is the heading to be used. The heading may also be the
2058 empty string.
2059 %t in the heading will be replaced by a time stamp.
2060 %s will be replaced by the new TODO state, in double quotes.
2061 %S will be replaced by the old TODO state, in double quotes.
2062 %u will be replaced by the user name.
2063 %U will be replaced by the full user name."
2064 :group 'org-todo
2065 :group 'org-progress
2066 :type '(list :greedy t
2067 (cons (const :tag "Heading when closing an item" done) string)
2068 (cons (const :tag
2069 "Heading when changing todo state (todo sequence only)"
2070 state) string)
2071 (cons (const :tag "Heading when just taking a note" note) string)
2072 (cons (const :tag "Heading when clocking out" clock-out) string)
2073 (cons (const :tag "Heading when rescheduling" reschedule) string)
2074 (cons (const :tag "Heading when changing deadline" redeadline) string)))
2076 (unless (assq 'note org-log-note-headings)
2077 (push '(note . "%t") org-log-note-headings))
2079 (defcustom org-log-into-drawer nil
2080 "Non-nil means, insert state change notes and time stamps into a drawer.
2081 When nil, state changes notes will be inserted after the headline and
2082 any scheduling and clock lines, but not inside a drawer.
2084 The value of this variable should be the name of the drawer to use.
2085 LOGBOOK is proposed at the default drawer for this purpose, you can
2086 also set this to a string to define the drawer of your choice.
2088 A value of t is also allowed, representing \"LOGBOOK\".
2090 If this variable is set, `org-log-state-notes-insert-after-drawers'
2091 will be ignored.
2093 You can set the property LOG_INTO_DRAWER to overrule this setting for
2094 a subtree."
2095 :group 'org-todo
2096 :group 'org-progress
2097 :type '(choice
2098 (const :tag "Not into a drawer" nil)
2099 (const :tag "LOGBOOK" t)
2100 (string :tag "Other")))
2102 (if (fboundp 'defvaralias)
2103 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2105 (defun org-log-into-drawer ()
2106 "Return the value of `org-log-into-drawer', but let properties overrule.
2107 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2108 used instead of the default value."
2109 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2110 (cond
2111 ((or (not p) (equal p "nil")) org-log-into-drawer)
2112 ((equal p "t") "LOGBOOK")
2113 (t p))))
2115 (defcustom org-log-state-notes-insert-after-drawers nil
2116 "Non-nil means, insert state change notes after any drawers in entry.
2117 Only the drawers that *immediately* follow the headline and the
2118 deadline/scheduled line are skipped.
2119 When nil, insert notes right after the heading and perhaps the line
2120 with deadline/scheduling if present.
2122 This variable will have no effect if `org-log-into-drawer' is
2123 set."
2124 :group 'org-todo
2125 :group 'org-progress
2126 :type 'boolean)
2128 (defcustom org-log-states-order-reversed t
2129 "Non-nil means, the latest state change note will be directly after heading.
2130 When nil, the notes will be orderer according to time."
2131 :group 'org-todo
2132 :group 'org-progress
2133 :type 'boolean)
2135 (defcustom org-log-repeat 'time
2136 "Non-nil means, record moving through the DONE state when triggering repeat.
2137 An auto-repeating task is immediately switched back to TODO when
2138 marked DONE. If you are not logging state changes (by adding \"@\"
2139 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2140 record a closing note, there will be no record of the task moving
2141 through DONE. This variable forces taking a note anyway.
2143 nil Don't force a record
2144 time Record a time stamp
2145 note Record a note
2147 This option can also be set with on a per-file-basis with
2149 #+STARTUP: logrepeat
2150 #+STARTUP: lognoterepeat
2151 #+STARTUP: nologrepeat
2153 You can have local logging settings for a subtree by setting the LOGGING
2154 property to one or more of these keywords."
2155 :group 'org-todo
2156 :group 'org-progress
2157 :type '(choice
2158 (const :tag "Don't force a record" nil)
2159 (const :tag "Force recording the DONE state" time)
2160 (const :tag "Force recording a note with the DONE state" note)))
2163 (defgroup org-priorities nil
2164 "Priorities in Org-mode."
2165 :tag "Org Priorities"
2166 :group 'org-todo)
2168 (defcustom org-enable-priority-commands t
2169 "Non-nil means, priority commands are active.
2170 When nil, these commands will be disabled, so that you never accidentally
2171 set a priority."
2172 :group 'org-priorities
2173 :type 'boolean)
2175 (defcustom org-highest-priority ?A
2176 "The highest priority of TODO items. A character like ?A, ?B etc.
2177 Must have a smaller ASCII number than `org-lowest-priority'."
2178 :group 'org-priorities
2179 :type 'character)
2181 (defcustom org-lowest-priority ?C
2182 "The lowest priority of TODO items. A character like ?A, ?B etc.
2183 Must have a larger ASCII number than `org-highest-priority'."
2184 :group 'org-priorities
2185 :type 'character)
2187 (defcustom org-default-priority ?B
2188 "The default priority of TODO items.
2189 This is the priority an item get if no explicit priority is given."
2190 :group 'org-priorities
2191 :type 'character)
2193 (defcustom org-priority-start-cycle-with-default t
2194 "Non-nil means, start with default priority when starting to cycle.
2195 When this is nil, the first step in the cycle will be (depending on the
2196 command used) one higher or lower that the default priority."
2197 :group 'org-priorities
2198 :type 'boolean)
2200 (defgroup org-time nil
2201 "Options concerning time stamps and deadlines in Org-mode."
2202 :tag "Org Time"
2203 :group 'org)
2205 (defcustom org-insert-labeled-timestamps-at-point nil
2206 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2207 When nil, these labeled time stamps are forces into the second line of an
2208 entry, just after the headline. When scheduling from the global TODO list,
2209 the time stamp will always be forced into the second line."
2210 :group 'org-time
2211 :type 'boolean)
2213 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2214 "Formats for `format-time-string' which are used for time stamps.
2215 It is not recommended to change this constant.")
2217 (defcustom org-time-stamp-rounding-minutes '(0 5)
2218 "Number of minutes to round time stamps to.
2219 These are two values, the first applies when first creating a time stamp.
2220 The second applies when changing it with the commands `S-up' and `S-down'.
2221 When changing the time stamp, this means that it will change in steps
2222 of N minutes, as given by the second value.
2224 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2225 numbers should be factors of 60, so for example 5, 10, 15.
2227 When this is larger than 1, you can still force an exact time-stamp by using
2228 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2229 and by using a prefix arg to `S-up/down' to specify the exact number
2230 of minutes to shift."
2231 :group 'org-time
2232 :get '(lambda (var) ; Make sure all entries have 5 elements
2233 (if (integerp (default-value var))
2234 (list (default-value var) 5)
2235 (default-value var)))
2236 :type '(list
2237 (integer :tag "when inserting times")
2238 (integer :tag "when modifying times")))
2240 ;; Normalize old customizations of this variable.
2241 (when (integerp org-time-stamp-rounding-minutes)
2242 (setq org-time-stamp-rounding-minutes
2243 (list org-time-stamp-rounding-minutes
2244 org-time-stamp-rounding-minutes)))
2246 (defcustom org-display-custom-times nil
2247 "Non-nil means, overlay custom formats over all time stamps.
2248 The formats are defined through the variable `org-time-stamp-custom-formats'.
2249 To turn this on on a per-file basis, insert anywhere in the file:
2250 #+STARTUP: customtime"
2251 :group 'org-time
2252 :set 'set-default
2253 :type 'sexp)
2254 (make-variable-buffer-local 'org-display-custom-times)
2256 (defcustom org-time-stamp-custom-formats
2257 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2258 "Custom formats for time stamps. See `format-time-string' for the syntax.
2259 These are overlayed over the default ISO format if the variable
2260 `org-display-custom-times' is set. Time like %H:%M should be at the
2261 end of the second format. The custom formats are also honored by export
2262 commands, if custom time display is turned on at the time of export."
2263 :group 'org-time
2264 :type 'sexp)
2266 (defun org-time-stamp-format (&optional long inactive)
2267 "Get the right format for a time string."
2268 (let ((f (if long (cdr org-time-stamp-formats)
2269 (car org-time-stamp-formats))))
2270 (if inactive
2271 (concat "[" (substring f 1 -1) "]")
2272 f)))
2274 (defcustom org-time-clocksum-format "%d:%02d"
2275 "The format string used when creating CLOCKSUM lines, or when
2276 org-mode generates a time duration."
2277 :group 'org-time
2278 :type 'string)
2280 (defcustom org-time-clocksum-use-fractional nil
2281 "If non-nil, \\[org-clock-display] uses fractional times.
2282 org-mode generates a time duration."
2283 :group 'org-time
2284 :type 'boolean)
2286 (defcustom org-time-clocksum-fractional-format "%.2f"
2287 "The format string used when creating CLOCKSUM lines, or when
2288 org-mode generates a time duration."
2289 :group 'org-time
2290 :type 'string)
2292 (defcustom org-deadline-warning-days 14
2293 "No. of days before expiration during which a deadline becomes active.
2294 This variable governs the display in sparse trees and in the agenda.
2295 When 0 or negative, it means use this number (the absolute value of it)
2296 even if a deadline has a different individual lead time specified.
2298 Custom commands can set this variable in the options section."
2299 :group 'org-time
2300 :group 'org-agenda-daily/weekly
2301 :type 'integer)
2303 (defcustom org-read-date-prefer-future t
2304 "Non-nil means, assume future for incomplete date input from user.
2305 This affects the following situations:
2306 1. The user gives a month but not a year.
2307 For example, if it is april and you enter \"feb 2\", this will be read
2308 as feb 2, *next* year. \"May 5\", however, will be this year.
2309 2. The user gives a day, but no month.
2310 For example, if today is the 15th, and you enter \"3\", Org-mode will
2311 read this as the third of *next* month. However, if you enter \"17\",
2312 it will be considered as *this* month.
2314 If you set this variable to the symbol `time', then also the following
2315 will work:
2317 3. If the user gives a time, but no day. If the time is before now,
2318 to will be interpreted as tomorrow.
2320 Currently none of this works for ISO week specifications.
2322 When this option is nil, the current day, month and year will always be
2323 used as defaults."
2324 :group 'org-time
2325 :type '(choice
2326 (const :tag "Never" nil)
2327 (const :tag "Check month and day" t)
2328 (const :tag "Check month, day, and time" time)))
2330 (defcustom org-read-date-display-live t
2331 "Non-nil means, display current interpretation of date prompt live.
2332 This display will be in an overlay, in the minibuffer."
2333 :group 'org-time
2334 :type 'boolean)
2336 (defcustom org-read-date-popup-calendar t
2337 "Non-nil means, pop up a calendar when prompting for a date.
2338 In the calendar, the date can be selected with mouse-1. However, the
2339 minibuffer will also be active, and you can simply enter the date as well.
2340 When nil, only the minibuffer will be available."
2341 :group 'org-time
2342 :type 'boolean)
2343 (if (fboundp 'defvaralias)
2344 (defvaralias 'org-popup-calendar-for-date-prompt
2345 'org-read-date-popup-calendar))
2347 (defcustom org-read-date-minibuffer-setup-hook nil
2348 "Hook to be used to set up keys for the date/time interface.
2349 Add key definitions to `minibuffer-local-map', which will be a temporary
2350 copy."
2351 :group 'org-time
2352 :type 'hook)
2354 (defcustom org-extend-today-until 0
2355 "The hour when your day really ends. Must be an integer.
2356 This has influence for the following applications:
2357 - When switching the agenda to \"today\". It it is still earlier than
2358 the time given here, the day recognized as TODAY is actually yesterday.
2359 - When a date is read from the user and it is still before the time given
2360 here, the current date and time will be assumed to be yesterday, 23:59.
2361 Also, timestamps inserted in remember templates follow this rule.
2363 IMPORTANT: This is a feature whose implementation is and likely will
2364 remain incomplete. Really, it is only here because past midnight seems to
2365 be the favorite working time of John Wiegley :-)"
2366 :group 'org-time
2367 :type 'integer)
2369 (defcustom org-edit-timestamp-down-means-later nil
2370 "Non-nil means, S-down will increase the time in a time stamp.
2371 When nil, S-up will increase."
2372 :group 'org-time
2373 :type 'boolean)
2375 (defcustom org-calendar-follow-timestamp-change t
2376 "Non-nil means, make the calendar window follow timestamp changes.
2377 When a timestamp is modified and the calendar window is visible, it will be
2378 moved to the new date."
2379 :group 'org-time
2380 :type 'boolean)
2382 (defgroup org-tags nil
2383 "Options concerning tags in Org-mode."
2384 :tag "Org Tags"
2385 :group 'org)
2387 (defcustom org-tag-alist nil
2388 "List of tags allowed in Org-mode files.
2389 When this list is nil, Org-mode will base TAG input on what is already in the
2390 buffer.
2391 The value of this variable is an alist, the car of each entry must be a
2392 keyword as a string, the cdr may be a character that is used to select
2393 that tag through the fast-tag-selection interface.
2394 See the manual for details."
2395 :group 'org-tags
2396 :type '(repeat
2397 (choice
2398 (cons (string :tag "Tag name")
2399 (character :tag "Access char"))
2400 (list :tag "Start radio group"
2401 (const :startgroup)
2402 (option (string :tag "Group description")))
2403 (list :tag "End radio group"
2404 (const :endgroup)
2405 (option (string :tag "Group description")))
2406 (const :tag "New line" (:newline)))))
2408 (defcustom org-tag-persistent-alist nil
2409 "List of tags that will always appear in all Org-mode files.
2410 This is in addition to any in buffer settings or customizations
2411 of `org-tag-alist'.
2412 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2413 The value of this variable is an alist, the car of each entry must be a
2414 keyword as a string, the cdr may be a character that is used to select
2415 that tag through the fast-tag-selection interface.
2416 See the manual for details.
2417 To disable these tags on a per-file basis, insert anywhere in the file:
2418 #+STARTUP: noptag"
2419 :group 'org-tags
2420 :type '(repeat
2421 (choice
2422 (cons (string :tag "Tag name")
2423 (character :tag "Access char"))
2424 (const :tag "Start radio group" (:startgroup))
2425 (const :tag "End radio group" (:endgroup))
2426 (const :tag "New line" (:newline)))))
2428 (defvar org-file-tags nil
2429 "List of tags that can be inherited by all entries in the file.
2430 The tags will be inherited if the variable `org-use-tag-inheritance'
2431 says they should be.
2432 This variable is populated from #+FILETAGS lines.")
2434 (defcustom org-use-fast-tag-selection 'auto
2435 "Non-nil means, use fast tag selection scheme.
2436 This is a special interface to select and deselect tags with single keys.
2437 When nil, fast selection is never used.
2438 When the symbol `auto', fast selection is used if and only if selection
2439 characters for tags have been configured, either through the variable
2440 `org-tag-alist' or through a #+TAGS line in the buffer.
2441 When t, fast selection is always used and selection keys are assigned
2442 automatically if necessary."
2443 :group 'org-tags
2444 :type '(choice
2445 (const :tag "Always" t)
2446 (const :tag "Never" nil)
2447 (const :tag "When selection characters are configured" 'auto)))
2449 (defcustom org-fast-tag-selection-single-key nil
2450 "Non-nil means, fast tag selection exits after first change.
2451 When nil, you have to press RET to exit it.
2452 During fast tag selection, you can toggle this flag with `C-c'.
2453 This variable can also have the value `expert'. In this case, the window
2454 displaying the tags menu is not even shown, until you press C-c again."
2455 :group 'org-tags
2456 :type '(choice
2457 (const :tag "No" nil)
2458 (const :tag "Yes" t)
2459 (const :tag "Expert" expert)))
2461 (defvar org-fast-tag-selection-include-todo nil
2462 "Non-nil means, fast tags selection interface will also offer TODO states.
2463 This is an undocumented feature, you should not rely on it.")
2465 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2466 "The column to which tags should be indented in a headline.
2467 If this number is positive, it specifies the column. If it is negative,
2468 it means that the tags should be flushright to that column. For example,
2469 -80 works well for a normal 80 character screen."
2470 :group 'org-tags
2471 :type 'integer)
2473 (defcustom org-auto-align-tags t
2474 "Non-nil means, realign tags after pro/demotion of TODO state change.
2475 These operations change the length of a headline and therefore shift
2476 the tags around. With this options turned on, after each such operation
2477 the tags are again aligned to `org-tags-column'."
2478 :group 'org-tags
2479 :type 'boolean)
2481 (defcustom org-use-tag-inheritance t
2482 "Non-nil means, tags in levels apply also for sublevels.
2483 When nil, only the tags directly given in a specific line apply there.
2484 This may also be a list of tags that should be inherited, or a regexp that
2485 matches tags that should be inherited. Additional control is possible
2486 with the variable `org-tags-exclude-from-inheritance' which gives an
2487 explicit list of tags to be excluded from inheritance., even if the value of
2488 `org-use-tag-inheritance' would select it for inheritance.
2490 If this option is t, a match early-on in a tree can lead to a large
2491 number of matches in the subtree when constructing the agenda or creating
2492 a sparse tree. If you only want to see the first match in a tree during
2493 a search, check out the variable `org-tags-match-list-sublevels'."
2494 :group 'org-tags
2495 :type '(choice
2496 (const :tag "Not" nil)
2497 (const :tag "Always" t)
2498 (repeat :tag "Specific tags" (string :tag "Tag"))
2499 (regexp :tag "Tags matched by regexp")))
2501 (defcustom org-tags-exclude-from-inheritance nil
2502 "List of tags that should never be inherited.
2503 This is a way to exclude a few tags from inheritance. For way to do
2504 the opposite, to actively allow inheritance for selected tags,
2505 see the variable `org-use-tag-inheritance'."
2506 :group 'org-tags
2507 :type '(repeat (string :tag "Tag")))
2509 (defun org-tag-inherit-p (tag)
2510 "Check if TAG is one that should be inherited."
2511 (cond
2512 ((member tag org-tags-exclude-from-inheritance) nil)
2513 ((eq org-use-tag-inheritance t) t)
2514 ((not org-use-tag-inheritance) nil)
2515 ((stringp org-use-tag-inheritance)
2516 (string-match org-use-tag-inheritance tag))
2517 ((listp org-use-tag-inheritance)
2518 (member tag org-use-tag-inheritance))
2519 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2521 (defcustom org-tags-match-list-sublevels t
2522 "Non-nil means list also sublevels of headlines matching a search.
2523 This variable applies to tags/property searches, and also to stuck
2524 projects because this search is based on a tags match as well.
2526 When set to the symbol `indented', sublevels are indented with
2527 leading dots.
2529 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2530 the sublevels of a headline matching a tag search often also match
2531 the same search. Listing all of them can create very long lists.
2532 Setting this variable to nil causes subtrees of a match to be skipped.
2534 This variable is semi-obsolete and probably should always be true. It
2535 is better to limit inheritance to certain tags using the variables
2536 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2537 :group 'org-tags
2538 :type '(choice
2539 (const :tag "No, don't list them" nil)
2540 (const :tag "Yes, do list them" t)
2541 (const :tag "List them, indented with leading dots" indented)))
2543 (defcustom org-tags-sort-function nil
2544 "When set, tags are sorted using this function as a comparator"
2545 :group 'org-tags
2546 :type '(choice
2547 (const :tag "No sorting" nil)
2548 (const :tag "Alphabetical" string<)
2549 (const :tag "Reverse alphabetical" string>)
2550 (function :tag "Custom function" nil)))
2552 (defvar org-tags-history nil
2553 "History of minibuffer reads for tags.")
2554 (defvar org-last-tags-completion-table nil
2555 "The last used completion table for tags.")
2556 (defvar org-after-tags-change-hook nil
2557 "Hook that is run after the tags in a line have changed.")
2559 (defgroup org-properties nil
2560 "Options concerning properties in Org-mode."
2561 :tag "Org Properties"
2562 :group 'org)
2564 (defcustom org-property-format "%-10s %s"
2565 "How property key/value pairs should be formatted by `indent-line'.
2566 When `indent-line' hits a property definition, it will format the line
2567 according to this format, mainly to make sure that the values are
2568 lined-up with respect to each other."
2569 :group 'org-properties
2570 :type 'string)
2572 (defcustom org-use-property-inheritance nil
2573 "Non-nil means, properties apply also for sublevels.
2575 This setting is chiefly used during property searches. Turning it on can
2576 cause significant overhead when doing a search, which is why it is not
2577 on by default.
2579 When nil, only the properties directly given in the current entry count.
2580 When t, every property is inherited. The value may also be a list of
2581 properties that should have inheritance, or a regular expression matching
2582 properties that should be inherited.
2584 However, note that some special properties use inheritance under special
2585 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2586 and the properties ending in \"_ALL\" when they are used as descriptor
2587 for valid values of a property.
2589 Note for programmers:
2590 When querying an entry with `org-entry-get', you can control if inheritance
2591 should be used. By default, `org-entry-get' looks only at the local
2592 properties. You can request inheritance by setting the inherit argument
2593 to t (to force inheritance) or to `selective' (to respect the setting
2594 in this variable)."
2595 :group 'org-properties
2596 :type '(choice
2597 (const :tag "Not" nil)
2598 (const :tag "Always" t)
2599 (repeat :tag "Specific properties" (string :tag "Property"))
2600 (regexp :tag "Properties matched by regexp")))
2602 (defun org-property-inherit-p (property)
2603 "Check if PROPERTY is one that should be inherited."
2604 (cond
2605 ((eq org-use-property-inheritance t) t)
2606 ((not org-use-property-inheritance) nil)
2607 ((stringp org-use-property-inheritance)
2608 (string-match org-use-property-inheritance property))
2609 ((listp org-use-property-inheritance)
2610 (member property org-use-property-inheritance))
2611 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2613 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2614 "The default column format, if no other format has been defined.
2615 This variable can be set on the per-file basis by inserting a line
2617 #+COLUMNS: %25ITEM ....."
2618 :group 'org-properties
2619 :type 'string)
2621 (defcustom org-columns-ellipses ".."
2622 "The ellipses to be used when a field in column view is truncated.
2623 When this is the empty string, as many characters as possible are shown,
2624 but then there will be no visual indication that the field has been truncated.
2625 When this is a string of length N, the last N characters of a truncated
2626 field are replaced by this string. If the column is narrower than the
2627 ellipses string, only part of the ellipses string will be shown."
2628 :group 'org-properties
2629 :type 'string)
2631 (defcustom org-columns-modify-value-for-display-function nil
2632 "Function that modifies values for display in column view.
2633 For example, it can be used to cut out a certain part from a time stamp.
2634 The function must take 2 arguments:
2636 column-title The title of the column (*not* the property name)
2637 value The value that should be modified.
2639 The function should return the value that should be displayed,
2640 or nil if the normal value should be used."
2641 :group 'org-properties
2642 :type 'function)
2644 (defcustom org-effort-property "Effort"
2645 "The property that is being used to keep track of effort estimates.
2646 Effort estimates given in this property need to have the format H:MM."
2647 :group 'org-properties
2648 :group 'org-progress
2649 :type '(string :tag "Property"))
2651 (defconst org-global-properties-fixed
2652 '(("VISIBILITY_ALL" . "folded children content all")
2653 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2654 "List of property/value pairs that can be inherited by any entry.
2656 These are fixed values, for the preset properties. The user variable
2657 that can be used to add to this list is `org-global-properties'.
2659 The entries in this list are cons cells where the car is a property
2660 name and cdr is a string with the value. If the value represents
2661 multiple items like an \"_ALL\" property, separate the items by
2662 spaces.")
2664 (defcustom org-global-properties nil
2665 "List of property/value pairs that can be inherited by any entry.
2667 This list will be combined with the constant `org-global-properties-fixed'.
2669 The entries in this list are cons cells where the car is a property
2670 name and cdr is a string with the value.
2672 You can set buffer-local values for the same purpose in the variable
2673 `org-file-properties' this by adding lines like
2675 #+PROPERTY: NAME VALUE"
2676 :group 'org-properties
2677 :type '(repeat
2678 (cons (string :tag "Property")
2679 (string :tag "Value"))))
2681 (defvar org-file-properties nil
2682 "List of property/value pairs that can be inherited by any entry.
2683 Valid for the current buffer.
2684 This variable is populated from #+PROPERTY lines.")
2685 (make-variable-buffer-local 'org-file-properties)
2687 (defgroup org-agenda nil
2688 "Options concerning agenda views in Org-mode."
2689 :tag "Org Agenda"
2690 :group 'org)
2692 (defvar org-category nil
2693 "Variable used by org files to set a category for agenda display.
2694 Such files should use a file variable to set it, for example
2696 # -*- mode: org; org-category: \"ELisp\"
2698 or contain a special line
2700 #+CATEGORY: ELisp
2702 If the file does not specify a category, then file's base name
2703 is used instead.")
2704 (make-variable-buffer-local 'org-category)
2705 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2707 (defcustom org-agenda-files nil
2708 "The files to be used for agenda display.
2709 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2710 \\[org-remove-file]. You can also use customize to edit the list.
2712 If an entry is a directory, all files in that directory that are matched by
2713 `org-agenda-file-regexp' will be part of the file list.
2715 If the value of the variable is not a list but a single file name, then
2716 the list of agenda files is actually stored and maintained in that file, one
2717 agenda file per line."
2718 :group 'org-agenda
2719 :type '(choice
2720 (repeat :tag "List of files and directories" file)
2721 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2723 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2724 "Regular expression to match files for `org-agenda-files'.
2725 If any element in the list in that variable contains a directory instead
2726 of a normal file, all files in that directory that are matched by this
2727 regular expression will be included."
2728 :group 'org-agenda
2729 :type 'regexp)
2731 (defcustom org-agenda-text-search-extra-files nil
2732 "List of extra files to be searched by text search commands.
2733 These files will be search in addition to the agenda files by the
2734 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2735 Note that these files will only be searched for text search commands,
2736 not for the other agenda views like todo lists, tag searches or the weekly
2737 agenda. This variable is intended to list notes and possibly archive files
2738 that should also be searched by these two commands.
2739 In fact, if the first element in the list is the symbol `agenda-archives',
2740 than all archive files of all agenda files will be added to the search
2741 scope."
2742 :group 'org-agenda
2743 :type '(set :greedy t
2744 (const :tag "Agenda Archives" agenda-archives)
2745 (repeat :inline t (file))))
2747 (if (fboundp 'defvaralias)
2748 (defvaralias 'org-agenda-multi-occur-extra-files
2749 'org-agenda-text-search-extra-files))
2751 (defcustom org-agenda-skip-unavailable-files nil
2752 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2753 A nil value means to remove them, after a query, from the list."
2754 :group 'org-agenda
2755 :type 'boolean)
2757 (defcustom org-calendar-to-agenda-key [?c]
2758 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2759 The command `org-calendar-goto-agenda' will be bound to this key. The
2760 default is the character `c' because then `c' can be used to switch back and
2761 forth between agenda and calendar."
2762 :group 'org-agenda
2763 :type 'sexp)
2765 (defcustom org-calendar-agenda-action-key [?k]
2766 "The key to be installed in `calendar-mode-map' for agenda-action.
2767 The command `org-agenda-action' will be bound to this key. The
2768 default is the character `k' because we use the same key in the agenda."
2769 :group 'org-agenda
2770 :type 'sexp)
2772 (defcustom org-calendar-insert-diary-entry-key [?i]
2773 "The key to be installed in `calendar-mode-map' for adding diary entries.
2774 This option is irrelevant until `org-agenda-diary-file' has been configured
2775 to point to an Org-mode file. When that is the case, the command
2776 `org-agenda-diary-entry' will be bound to the key given here, by default
2777 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2778 if you want to continue doing this, you need to change this to a different
2779 key."
2780 :group 'org-agenda
2781 :type 'sexp)
2783 (defcustom org-agenda-diary-file 'diary-file
2784 "File to which to add new entries with the `i' key in agenda and calendar.
2785 When this is the symbol `diary-file', the functionality in the Emacs
2786 calendar will be used to add entries to the `diary-file'. But when this
2787 points to a file, `org-agenda-diary-entry' will be used instead."
2788 :group 'org-agenda
2789 :type '(choice
2790 (const :tag "The standard Emacs diary file" diary-file)
2791 (file :tag "Special Org file diary entries")))
2793 (eval-after-load "calendar"
2794 '(progn
2795 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2796 'org-calendar-goto-agenda)
2797 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2798 'org-agenda-action)
2799 (add-hook 'calendar-mode-hook
2800 (lambda ()
2801 (unless (eq org-agenda-diary-file 'diary-file)
2802 (define-key calendar-mode-map
2803 org-calendar-insert-diary-entry-key
2804 'org-agenda-diary-entry))))))
2806 (defgroup org-latex nil
2807 "Options for embedding LaTeX code into Org-mode."
2808 :tag "Org LaTeX"
2809 :group 'org)
2811 (defcustom org-format-latex-options
2812 '(:foreground default :background default :scale 1.0
2813 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2814 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2815 "Options for creating images from LaTeX fragments.
2816 This is a property list with the following properties:
2817 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2818 `default' means use the foreground of the default face.
2819 :background the background color, or \"Transparent\".
2820 `default' means use the background of the default face.
2821 :scale a scaling factor for the size of the images.
2822 :html-foreground, :html-background, :html-scale
2823 the same numbers for HTML export.
2824 :matchers a list indicating which matchers should be used to
2825 find LaTeX fragments. Valid members of this list are:
2826 \"begin\" find environments
2827 \"$1\" find single characters surrounded by $.$
2828 \"$\" find math expressions surrounded by $...$
2829 \"$$\" find math expressions surrounded by $$....$$
2830 \"\\(\" find math expressions surrounded by \\(...\\)
2831 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2832 :group 'org-latex
2833 :type 'plist)
2835 (defcustom org-format-latex-header "\\documentclass{article}
2836 \\usepackage{amssymb}
2837 \\usepackage[usenames]{color}
2838 \\usepackage{amsmath}
2839 \\usepackage{latexsym}
2840 \\usepackage[mathscr]{eucal}
2841 \\pagestyle{empty} % do not remove
2842 % The settings below are copied from fullpage.sty
2843 \\setlength{\\textwidth}{\\paperwidth}
2844 \\addtolength{\\textwidth}{-3cm}
2845 \\setlength{\\oddsidemargin}{1.5cm}
2846 \\addtolength{\\oddsidemargin}{-2.54cm}
2847 \\setlength{\\evensidemargin}{\\oddsidemargin}
2848 \\setlength{\\textheight}{\\paperheight}
2849 \\addtolength{\\textheight}{-\\headheight}
2850 \\addtolength{\\textheight}{-\\headsep}
2851 \\addtolength{\\textheight}{-\\footskip}
2852 \\addtolength{\\textheight}{-3cm}
2853 \\setlength{\\topmargin}{1.5cm}
2854 \\addtolength{\\topmargin}{-2.54cm}"
2855 "The document header used for processing LaTeX fragments.
2856 It is imperative that this header make sure that no page number
2857 appears on the page."
2858 :group 'org-latex
2859 :type 'string)
2862 (defgroup org-font-lock nil
2863 "Font-lock settings for highlighting in Org-mode."
2864 :tag "Org Font Lock"
2865 :group 'org)
2867 (defcustom org-level-color-stars-only nil
2868 "Non-nil means fontify only the stars in each headline.
2869 When nil, the entire headline is fontified.
2870 Changing it requires restart of `font-lock-mode' to become effective
2871 also in regions already fontified."
2872 :group 'org-font-lock
2873 :type 'boolean)
2875 (defcustom org-hide-leading-stars nil
2876 "Non-nil means, hide the first N-1 stars in a headline.
2877 This works by using the face `org-hide' for these stars. This
2878 face is white for a light background, and black for a dark
2879 background. You may have to customize the face `org-hide' to
2880 make this work.
2881 Changing it requires restart of `font-lock-mode' to become effective
2882 also in regions already fontified.
2883 You may also set this on a per-file basis by adding one of the following
2884 lines to the buffer:
2886 #+STARTUP: hidestars
2887 #+STARTUP: showstars"
2888 :group 'org-font-lock
2889 :type 'boolean)
2891 (defcustom org-fontify-done-headline nil
2892 "Non-nil means, change the face of a headline if it is marked DONE.
2893 Normally, only the TODO/DONE keyword indicates the state of a headline.
2894 When this is non-nil, the headline after the keyword is set to the
2895 `org-headline-done' as an additional indication."
2896 :group 'org-font-lock
2897 :type 'boolean)
2899 (defcustom org-fontify-emphasized-text t
2900 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2901 Changing this variable requires a restart of Emacs to take effect."
2902 :group 'org-font-lock
2903 :type 'boolean)
2905 (defcustom org-fontify-whole-heading-line nil
2906 "Non-nil means fontify the whole line for headings.
2907 This is useful when setting a background color for the
2908 org-level-* faces."
2909 :group 'org-font-lock
2910 :type 'boolean)
2912 (defcustom org-highlight-latex-fragments-and-specials nil
2913 "Non-nil means, fontify what is treated specially by the exporters."
2914 :group 'org-font-lock
2915 :type 'boolean)
2917 (defcustom org-hide-emphasis-markers nil
2918 "Non-nil mean font-lock should hide the emphasis marker characters."
2919 :group 'org-font-lock
2920 :type 'boolean)
2922 (defvar org-emph-re nil
2923 "Regular expression for matching emphasis.")
2924 (defvar org-verbatim-re nil
2925 "Regular expression for matching verbatim text.")
2926 (defvar org-emphasis-regexp-components) ; defined just below
2927 (defvar org-emphasis-alist) ; defined just below
2928 (defun org-set-emph-re (var val)
2929 "Set variable and compute the emphasis regular expression."
2930 (set var val)
2931 (when (and (boundp 'org-emphasis-alist)
2932 (boundp 'org-emphasis-regexp-components)
2933 org-emphasis-alist org-emphasis-regexp-components)
2934 (let* ((e org-emphasis-regexp-components)
2935 (pre (car e))
2936 (post (nth 1 e))
2937 (border (nth 2 e))
2938 (body (nth 3 e))
2939 (nl (nth 4 e))
2940 (body1 (concat body "*?"))
2941 (markers (mapconcat 'car org-emphasis-alist ""))
2942 (vmarkers (mapconcat
2943 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2944 org-emphasis-alist "")))
2945 ;; make sure special characters appear at the right position in the class
2946 (if (string-match "\\^" markers)
2947 (setq markers (concat (replace-match "" t t markers) "^")))
2948 (if (string-match "-" markers)
2949 (setq markers (concat (replace-match "" t t markers) "-")))
2950 (if (string-match "\\^" vmarkers)
2951 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2952 (if (string-match "-" vmarkers)
2953 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2954 (if (> nl 0)
2955 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2956 (int-to-string nl) "\\}")))
2957 ;; Make the regexp
2958 (setq org-emph-re
2959 (concat "\\([" pre "]\\|^\\)"
2960 "\\("
2961 "\\([" markers "]\\)"
2962 "\\("
2963 "[^" border "]\\|"
2964 "[^" border "]"
2965 body1
2966 "[^" border "]"
2967 "\\)"
2968 "\\3\\)"
2969 "\\([" post "]\\|$\\)"))
2970 (setq org-verbatim-re
2971 (concat "\\([" pre "]\\|^\\)"
2972 "\\("
2973 "\\([" vmarkers "]\\)"
2974 "\\("
2975 "[^" border "]\\|"
2976 "[^" border "]"
2977 body1
2978 "[^" border "]"
2979 "\\)"
2980 "\\3\\)"
2981 "\\([" post "]\\|$\\)")))))
2983 (defcustom org-emphasis-regexp-components
2984 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2985 "Components used to build the regular expression for emphasis.
2986 This is a list with 6 entries. Terminology: In an emphasis string
2987 like \" *strong word* \", we call the initial space PREMATCH, the final
2988 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2989 and \"trong wor\" is the body. The different components in this variable
2990 specify what is allowed/forbidden in each part:
2992 pre Chars allowed as prematch. Beginning of line will be allowed too.
2993 post Chars allowed as postmatch. End of line will be allowed too.
2994 border The chars *forbidden* as border characters.
2995 body-regexp A regexp like \".\" to match a body character. Don't use
2996 non-shy groups here, and don't allow newline here.
2997 newline The maximum number of newlines allowed in an emphasis exp.
2999 Use customize to modify this, or restart Emacs after changing it."
3000 :group 'org-font-lock
3001 :set 'org-set-emph-re
3002 :type '(list
3003 (sexp :tag "Allowed chars in pre ")
3004 (sexp :tag "Allowed chars in post ")
3005 (sexp :tag "Forbidden chars in border ")
3006 (sexp :tag "Regexp for body ")
3007 (integer :tag "number of newlines allowed")
3008 (option (boolean :tag "Please ignore this button"))))
3010 (defcustom org-emphasis-alist
3011 `(("*" bold "<b>" "</b>")
3012 ("/" italic "<i>" "</i>")
3013 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3014 ("=" org-code "<code>" "</code>" verbatim)
3015 ("~" org-verbatim "<code>" "</code>" verbatim)
3016 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3017 "<del>" "</del>")
3019 "Special syntax for emphasized text.
3020 Text starting and ending with a special character will be emphasized, for
3021 example *bold*, _underlined_ and /italic/. This variable sets the marker
3022 characters, the face to be used by font-lock for highlighting in Org-mode
3023 Emacs buffers, and the HTML tags to be used for this.
3024 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3025 Use customize to modify this, or restart Emacs after changing it."
3026 :group 'org-font-lock
3027 :set 'org-set-emph-re
3028 :type '(repeat
3029 (list
3030 (string :tag "Marker character")
3031 (choice
3032 (face :tag "Font-lock-face")
3033 (plist :tag "Face property list"))
3034 (string :tag "HTML start tag")
3035 (string :tag "HTML end tag")
3036 (option (const verbatim)))))
3038 (defvar org-protecting-blocks
3039 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3040 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3041 This is needed for font-lock setup.")
3043 ;;; Miscellaneous options
3045 (defgroup org-completion nil
3046 "Completion in Org-mode."
3047 :tag "Org Completion"
3048 :group 'org)
3050 (defcustom org-completion-use-ido nil
3051 "Non-nil means, use ido completion wherever possible.
3052 Note that `ido-mode' must be active for this variable to be relevant.
3053 If you decide to turn this variable on, you might well want to turn off
3054 `org-outline-path-complete-in-steps'.
3055 See also `org-completion-use-iswitchb'."
3056 :group 'org-completion
3057 :type 'boolean)
3059 (defcustom org-completion-use-iswitchb nil
3060 "Non-nil means, use iswitchb completion wherever possible.
3061 Note that `iswitchb-mode' must be active for this variable to be relevant.
3062 If you decide to turn this variable on, you might well want to turn off
3063 `org-outline-path-complete-in-steps'.
3064 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3065 :group 'org-completion
3066 :type 'boolean)
3068 (defcustom org-completion-fallback-command 'hippie-expand
3069 "The expansion command called by \\[org-complete] in normal context.
3070 Normal means, no org-mode-specific context."
3071 :group 'org-completion
3072 :type 'function)
3074 ;;; Functions and variables from their packages
3075 ;; Declared here to avoid compiler warnings
3077 ;; XEmacs only
3078 (defvar outline-mode-menu-heading)
3079 (defvar outline-mode-menu-show)
3080 (defvar outline-mode-menu-hide)
3081 (defvar zmacs-regions) ; XEmacs regions
3083 ;; Emacs only
3084 (defvar mark-active)
3086 ;; Various packages
3087 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3088 (declare-function calendar-forward-day "cal-move" (arg))
3089 (declare-function calendar-goto-date "cal-move" (date))
3090 (declare-function calendar-goto-today "cal-move" ())
3091 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3092 (defvar calc-embedded-close-formula)
3093 (defvar calc-embedded-open-formula)
3094 (declare-function cdlatex-tab "ext:cdlatex" ())
3095 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3096 (defvar font-lock-unfontify-region-function)
3097 (declare-function iswitchb-read-buffer "iswitchb"
3098 (prompt &optional default require-match start matches-set))
3099 (defvar iswitchb-temp-buflist)
3100 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3101 (defvar org-agenda-tags-todo-honor-ignore-options)
3102 (declare-function org-agenda-skip "org-agenda" ())
3103 (declare-function org-format-agenda-item "org-agenda"
3104 (extra txt &optional category tags dotime noprefix remove-re))
3105 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3106 (declare-function org-agenda-change-all-lines "org-agenda"
3107 (newhead hdmarker &optional fixface just-this))
3108 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3109 (declare-function org-agenda-maybe-redo "org-agenda" ())
3110 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3111 (beg end))
3112 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3113 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3114 "org-agenda" (&optional end))
3115 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3116 (declare-function org-indent-mode "org-indent" (&optional arg))
3117 (declare-function parse-time-string "parse-time" (string))
3118 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3119 (defvar remember-data-file)
3120 (defvar texmathp-why)
3121 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3122 (declare-function table--at-cell-p "table" (position &optional object at-column))
3124 (defvar w3m-current-url)
3125 (defvar w3m-current-title)
3127 (defvar org-latex-regexps)
3129 ;;; Autoload and prepare some org modules
3131 ;; Some table stuff that needs to be defined here, because it is used
3132 ;; by the functions setting up org-mode or checking for table context.
3134 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3135 "Detects an org-type or table-type table.")
3136 (defconst org-table-line-regexp "^[ \t]*|"
3137 "Detects an org-type table line.")
3138 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3139 "Detects an org-type table line.")
3140 (defconst org-table-hline-regexp "^[ \t]*|-"
3141 "Detects an org-type table hline.")
3142 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3143 "Detects a table-type table hline.")
3144 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3145 "Searching from within a table (any type) this finds the first line
3146 outside the table.")
3148 ;; Autoload the functions in org-table.el that are needed by functions here.
3150 (eval-and-compile
3151 (org-autoload "org-table"
3152 '(org-table-align org-table-begin org-table-blank-field
3153 org-table-convert org-table-convert-region org-table-copy-down
3154 org-table-copy-region org-table-create
3155 org-table-create-or-convert-from-region
3156 org-table-create-with-table.el org-table-current-dline
3157 org-table-cut-region org-table-delete-column org-table-edit-field
3158 org-table-edit-formulas org-table-end org-table-eval-formula
3159 org-table-export org-table-field-info
3160 org-table-get-stored-formulas org-table-goto-column
3161 org-table-hline-and-move org-table-import org-table-insert-column
3162 org-table-insert-hline org-table-insert-row org-table-iterate
3163 org-table-justify-field-maybe org-table-kill-row
3164 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3165 org-table-move-column org-table-move-column-left
3166 org-table-move-column-right org-table-move-row
3167 org-table-move-row-down org-table-move-row-up
3168 org-table-next-field org-table-next-row org-table-paste-rectangle
3169 org-table-previous-field org-table-recalculate
3170 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3171 org-table-toggle-coordinate-overlays
3172 org-table-toggle-formula-debugger org-table-wrap-region
3173 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3175 (defun org-at-table-p (&optional table-type)
3176 "Return t if the cursor is inside an org-type table.
3177 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3178 (if org-enable-table-editor
3179 (save-excursion
3180 (beginning-of-line 1)
3181 (looking-at (if table-type org-table-any-line-regexp
3182 org-table-line-regexp)))
3183 nil))
3184 (defsubst org-table-p () (org-at-table-p))
3186 (defun org-at-table.el-p ()
3187 "Return t if and only if we are at a table.el table."
3188 (and (org-at-table-p 'any)
3189 (save-excursion
3190 (goto-char (org-table-begin 'any))
3191 (looking-at org-table1-hline-regexp))))
3192 (defun org-table-recognize-table.el ()
3193 "If there is a table.el table nearby, recognize it and move into it."
3194 (if org-table-tab-recognizes-table.el
3195 (if (org-at-table.el-p)
3196 (progn
3197 (beginning-of-line 1)
3198 (if (looking-at org-table-dataline-regexp)
3200 (if (looking-at org-table1-hline-regexp)
3201 (progn
3202 (beginning-of-line 2)
3203 (if (looking-at org-table-any-border-regexp)
3204 (beginning-of-line -1)))))
3205 (if (re-search-forward "|" (org-table-end t) t)
3206 (progn
3207 (require 'table)
3208 (if (table--at-cell-p (point))
3210 (message "recognizing table.el table...")
3211 (table-recognize-table)
3212 (message "recognizing table.el table...done")))
3213 (error "This should not happen..."))
3215 nil)
3216 nil))
3218 (defun org-at-table-hline-p ()
3219 "Return t if the cursor is inside a hline in a table."
3220 (if org-enable-table-editor
3221 (save-excursion
3222 (beginning-of-line 1)
3223 (looking-at org-table-hline-regexp))
3224 nil))
3226 (defvar org-table-clean-did-remove-column nil)
3228 (defun org-table-map-tables (function)
3229 "Apply FUNCTION to the start of all tables in the buffer."
3230 (save-excursion
3231 (save-restriction
3232 (widen)
3233 (goto-char (point-min))
3234 (while (re-search-forward org-table-any-line-regexp nil t)
3235 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3236 (beginning-of-line 1)
3237 (when (looking-at org-table-line-regexp)
3238 (save-excursion (funcall function))
3239 (or (looking-at org-table-line-regexp)
3240 (forward-char 1)))
3241 (re-search-forward org-table-any-border-regexp nil 1))))
3242 (message "Mapping tables: done"))
3244 ;; Declare and autoload functions from org-exp.el & Co
3246 (declare-function org-default-export-plist "org-exp")
3247 (declare-function org-infile-export-plist "org-exp")
3248 (declare-function org-get-current-options "org-exp")
3249 (eval-and-compile
3250 (org-autoload "org-exp"
3251 '(org-export org-export-visible
3252 org-insert-export-options-template
3253 org-table-clean-before-export))
3254 (org-autoload "org-ascii"
3255 '(org-export-as-ascii org-export-ascii-preprocess
3256 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3257 org-export-region-as-ascii))
3258 (org-autoload "org-html"
3259 '(org-export-as-html-and-open
3260 org-export-as-html-batch org-export-as-html-to-buffer
3261 org-replace-region-by-html org-export-region-as-html
3262 org-export-as-html))
3263 (org-autoload "org-icalendar"
3264 '(org-export-icalendar-this-file
3265 org-export-icalendar-all-agenda-files
3266 org-export-icalendar-combine-agenda-files))
3267 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3269 ;; Declare and autoload functions from org-agenda.el
3271 (eval-and-compile
3272 (org-autoload "org-agenda"
3273 '(org-agenda org-agenda-list org-search-view
3274 org-todo-list org-tags-view org-agenda-list-stuck-projects
3275 org-diary org-agenda-to-appt
3276 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3278 ;; Autoload org-remember
3280 (eval-and-compile
3281 (org-autoload "org-remember"
3282 '(org-remember-insinuate org-remember-annotation
3283 org-remember-apply-template org-remember org-remember-handler)))
3285 ;; Autoload org-clock.el
3288 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3289 (beg end))
3290 (declare-function org-clock-update-mode-line "org-clock" ())
3291 (declare-function org-resolve-clocks "org-clock"
3292 (&optional also-non-dangling-p prompt last-valid))
3293 (defvar org-clock-start-time)
3294 (defvar org-clock-marker (make-marker)
3295 "Marker recording the last clock-in.")
3296 (defvar org-clock-hd-marker (make-marker)
3297 "Marker recording the last clock-in, but the headline position.")
3298 (defvar org-clock-heading ""
3299 "The heading of the current clock entry.")
3300 (defun org-clock-is-active ()
3301 "Return non-nil if clock is currently running.
3302 The return value is actually the clock marker."
3303 (marker-buffer org-clock-marker))
3305 (eval-and-compile
3306 (org-autoload
3307 "org-clock"
3308 '(org-clock-in org-clock-out org-clock-cancel
3309 org-clock-goto org-clock-sum org-clock-display
3310 org-clock-remove-overlays org-clock-report
3311 org-clocktable-shift org-dblock-write:clocktable
3312 org-get-clocktable org-resolve-clocks)))
3314 (defun org-clock-update-time-maybe ()
3315 "If this is a CLOCK line, update it and return t.
3316 Otherwise, return nil."
3317 (interactive)
3318 (save-excursion
3319 (beginning-of-line 1)
3320 (skip-chars-forward " \t")
3321 (when (looking-at org-clock-string)
3322 (let ((re (concat "[ \t]*" org-clock-string
3323 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3324 "\\([ \t]*=>.*\\)?\\)?"))
3325 ts te h m s neg)
3326 (cond
3327 ((not (looking-at re))
3328 nil)
3329 ((not (match-end 2))
3330 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3331 (> org-clock-marker (point))
3332 (<= org-clock-marker (point-at-eol)))
3333 ;; The clock is running here
3334 (setq org-clock-start-time
3335 (apply 'encode-time
3336 (org-parse-time-string (match-string 1))))
3337 (org-clock-update-mode-line)))
3339 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3340 (end-of-line 1)
3341 (setq ts (match-string 1)
3342 te (match-string 3))
3343 (setq s (- (org-float-time
3344 (apply 'encode-time (org-parse-time-string te)))
3345 (org-float-time
3346 (apply 'encode-time (org-parse-time-string ts))))
3347 neg (< s 0)
3348 s (abs s)
3349 h (floor (/ s 3600))
3350 s (- s (* 3600 h))
3351 m (floor (/ s 60))
3352 s (- s (* 60 s)))
3353 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3354 t))))))
3356 (defun org-check-running-clock ()
3357 "Check if the current buffer contains the running clock.
3358 If yes, offer to stop it and to save the buffer with the changes."
3359 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3360 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3361 (buffer-name))))
3362 (org-clock-out)
3363 (when (y-or-n-p "Save changed buffer?")
3364 (save-buffer))))
3366 (defun org-clocktable-try-shift (dir n)
3367 "Check if this line starts a clock table, if yes, shift the time block."
3368 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3369 (org-clocktable-shift dir n)))
3371 ;; Autoload org-timer.el
3373 (eval-and-compile
3374 (org-autoload
3375 "org-timer"
3376 '(org-timer-start org-timer org-timer-item
3377 org-timer-change-times-in-region
3378 org-timer-set-timer
3379 org-timer-reset-timers
3380 org-timer-show-remaining-time)))
3382 ;; Autoload org-feed.el
3384 (eval-and-compile
3385 (org-autoload
3386 "org-feed"
3387 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3390 ;; Autoload org-indent.el
3392 ;; Define the variable already here, to make sure we have it.
3393 (defvar org-indent-mode nil
3394 "Non-nil if Org-Indent mode is enabled.
3395 Use the command `org-indent-mode' to change this variable.")
3397 (eval-and-compile
3398 (org-autoload
3399 "org-indent"
3400 '(org-indent-mode)))
3402 ;; Autoload org-mobile.el
3404 (eval-and-compile
3405 (org-autoload
3406 "org-mobile"
3407 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3409 ;; Autoload archiving code
3410 ;; The stuff that is needed for cycling and tags has to be defined here.
3412 (defgroup org-archive nil
3413 "Options concerning archiving in Org-mode."
3414 :tag "Org Archive"
3415 :group 'org-structure)
3417 (defcustom org-archive-location "%s_archive::"
3418 "The location where subtrees should be archived.
3420 The value of this variable is a string, consisting of two parts,
3421 separated by a double-colon. The first part is a filename and
3422 the second part is a headline.
3424 When the filename is omitted, archiving happens in the same file.
3425 %s in the filename will be replaced by the current file
3426 name (without the directory part). Archiving to a different file
3427 is useful to keep archived entries from contributing to the
3428 Org-mode Agenda.
3430 The archived entries will be filed as subtrees of the specified
3431 headline. When the headline is omitted, the subtrees are simply
3432 filed away at the end of the file, as top-level entries. Also in
3433 the heading you can use %s to represent the file name, this can be
3434 useful when using the same archive for a number of different files.
3436 Here are a few examples:
3437 \"%s_archive::\"
3438 If the current file is Projects.org, archive in file
3439 Projects.org_archive, as top-level trees. This is the default.
3441 \"::* Archived Tasks\"
3442 Archive in the current file, under the top-level headline
3443 \"* Archived Tasks\".
3445 \"~/org/archive.org::\"
3446 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3448 \"~/org/archive.org::From %s\"
3449 Archive in file ~/org/archive.org (absolute path), under headlines
3450 \"From FILENAME\" where file name is the current file name.
3452 \"basement::** Finished Tasks\"
3453 Archive in file ./basement (relative path), as level 3 trees
3454 below the level 2 heading \"** Finished Tasks\".
3456 You may set this option on a per-file basis by adding to the buffer a
3457 line like
3459 #+ARCHIVE: basement::** Finished Tasks
3461 You may also define it locally for a subtree by setting an ARCHIVE property
3462 in the entry. If such a property is found in an entry, or anywhere up
3463 the hierarchy, it will be used."
3464 :group 'org-archive
3465 :type 'string)
3467 (defcustom org-archive-tag "ARCHIVE"
3468 "The tag that marks a subtree as archived.
3469 An archived subtree does not open during visibility cycling, and does
3470 not contribute to the agenda listings.
3471 After changing this, font-lock must be restarted in the relevant buffers to
3472 get the proper fontification."
3473 :group 'org-archive
3474 :group 'org-keywords
3475 :type 'string)
3477 (defcustom org-agenda-skip-archived-trees t
3478 "Non-nil means, the agenda will skip any items located in archived trees.
3479 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3480 variable is no longer recommended, you should leave it at the value t.
3481 Instead, use the key `v' to cycle the archives-mode in the agenda."
3482 :group 'org-archive
3483 :group 'org-agenda-skip
3484 :type 'boolean)
3486 (defcustom org-columns-skip-archived-trees t
3487 "Non-nil means, ignore archived trees when creating column view."
3488 :group 'org-archive
3489 :group 'org-properties
3490 :type 'boolean)
3492 (defcustom org-cycle-open-archived-trees nil
3493 "Non-nil means, `org-cycle' will open archived trees.
3494 An archived tree is a tree marked with the tag ARCHIVE.
3495 When nil, archived trees will stay folded. You can still open them with
3496 normal outline commands like `show-all', but not with the cycling commands."
3497 :group 'org-archive
3498 :group 'org-cycle
3499 :type 'boolean)
3501 (defcustom org-sparse-tree-open-archived-trees nil
3502 "Non-nil means sparse tree construction shows matches in archived trees.
3503 When nil, matches in these trees are highlighted, but the trees are kept in
3504 collapsed state."
3505 :group 'org-archive
3506 :group 'org-sparse-trees
3507 :type 'boolean)
3509 (defun org-cycle-hide-archived-subtrees (state)
3510 "Re-hide all archived subtrees after a visibility state change."
3511 (when (and (not org-cycle-open-archived-trees)
3512 (not (memq state '(overview folded))))
3513 (save-excursion
3514 (let* ((globalp (memq state '(contents all)))
3515 (beg (if globalp (point-min) (point)))
3516 (end (if globalp (point-max) (org-end-of-subtree t))))
3517 (org-hide-archived-subtrees beg end)
3518 (goto-char beg)
3519 (if (looking-at (concat ".*:" org-archive-tag ":"))
3520 (message "%s" (substitute-command-keys
3521 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3523 (defun org-force-cycle-archived ()
3524 "Cycle subtree even if it is archived."
3525 (interactive)
3526 (setq this-command 'org-cycle)
3527 (let ((org-cycle-open-archived-trees t))
3528 (call-interactively 'org-cycle)))
3530 (defun org-hide-archived-subtrees (beg end)
3531 "Re-hide all archived subtrees after a visibility state change."
3532 (save-excursion
3533 (let* ((re (concat ":" org-archive-tag ":")))
3534 (goto-char beg)
3535 (while (re-search-forward re end t)
3536 (and (org-on-heading-p) (org-flag-subtree t))
3537 (org-end-of-subtree t)))))
3539 (defun org-flag-subtree (flag)
3540 (save-excursion
3541 (org-back-to-heading t)
3542 (outline-end-of-heading)
3543 (outline-flag-region (point)
3544 (progn (org-end-of-subtree t) (point))
3545 flag)))
3547 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3549 (eval-and-compile
3550 (org-autoload "org-archive"
3551 '(org-add-archive-files org-archive-subtree
3552 org-archive-to-archive-sibling org-toggle-archive-tag)))
3554 ;; Autoload Column View Code
3556 (declare-function org-columns-number-to-string "org-colview")
3557 (declare-function org-columns-get-format-and-top-level "org-colview")
3558 (declare-function org-columns-compute "org-colview")
3560 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3561 '(org-columns-number-to-string org-columns-get-format-and-top-level
3562 org-columns-compute org-agenda-columns org-columns-remove-overlays
3563 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3565 ;; Autoload ID code
3567 (declare-function org-id-store-link "org-id")
3568 (declare-function org-id-locations-load "org-id")
3569 (declare-function org-id-locations-save "org-id")
3570 (defvar org-id-track-globally)
3571 (org-autoload "org-id"
3572 '(org-id-get-create org-id-new org-id-copy org-id-get
3573 org-id-get-with-outline-path-completion
3574 org-id-get-with-outline-drilling
3575 org-id-goto org-id-find org-id-store-link))
3577 ;; Autoload Plotting Code
3579 (org-autoload "org-plot"
3580 '(org-plot/gnuplot))
3582 ;;; Variables for pre-computed regular expressions, all buffer local
3584 (defvar org-drawer-regexp nil
3585 "Matches first line of a hidden block.")
3586 (make-variable-buffer-local 'org-drawer-regexp)
3587 (defvar org-todo-regexp nil
3588 "Matches any of the TODO state keywords.")
3589 (make-variable-buffer-local 'org-todo-regexp)
3590 (defvar org-not-done-regexp nil
3591 "Matches any of the TODO state keywords except the last one.")
3592 (make-variable-buffer-local 'org-not-done-regexp)
3593 (defvar org-not-done-heading-regexp nil
3594 "Matches a TODO headline that is not done.")
3595 (make-variable-buffer-local 'org-not-done-regexp)
3596 (defvar org-todo-line-regexp nil
3597 "Matches a headline and puts TODO state into group 2 if present.")
3598 (make-variable-buffer-local 'org-todo-line-regexp)
3599 (defvar org-complex-heading-regexp nil
3600 "Matches a headline and puts everything into groups:
3601 group 1: the stars
3602 group 2: The todo keyword, maybe
3603 group 3: Priority cookie
3604 group 4: True headline
3605 group 5: Tags")
3606 (make-variable-buffer-local 'org-complex-heading-regexp)
3607 (defvar org-complex-heading-regexp-format nil)
3608 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3609 (defvar org-todo-line-tags-regexp nil
3610 "Matches a headline and puts TODO state into group 2 if present.
3611 Also put tags into group 4 if tags are present.")
3612 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3613 (defvar org-nl-done-regexp nil
3614 "Matches newline followed by a headline with the DONE keyword.")
3615 (make-variable-buffer-local 'org-nl-done-regexp)
3616 (defvar org-looking-at-done-regexp nil
3617 "Matches the DONE keyword a point.")
3618 (make-variable-buffer-local 'org-looking-at-done-regexp)
3619 (defvar org-ds-keyword-length 12
3620 "Maximum length of the Deadline and SCHEDULED keywords.")
3621 (make-variable-buffer-local 'org-ds-keyword-length)
3622 (defvar org-deadline-regexp nil
3623 "Matches the DEADLINE keyword.")
3624 (make-variable-buffer-local 'org-deadline-regexp)
3625 (defvar org-deadline-time-regexp nil
3626 "Matches the DEADLINE keyword together with a time stamp.")
3627 (make-variable-buffer-local 'org-deadline-time-regexp)
3628 (defvar org-deadline-line-regexp nil
3629 "Matches the DEADLINE keyword and the rest of the line.")
3630 (make-variable-buffer-local 'org-deadline-line-regexp)
3631 (defvar org-scheduled-regexp nil
3632 "Matches the SCHEDULED keyword.")
3633 (make-variable-buffer-local 'org-scheduled-regexp)
3634 (defvar org-scheduled-time-regexp nil
3635 "Matches the SCHEDULED keyword together with a time stamp.")
3636 (make-variable-buffer-local 'org-scheduled-time-regexp)
3637 (defvar org-closed-time-regexp nil
3638 "Matches the CLOSED keyword together with a time stamp.")
3639 (make-variable-buffer-local 'org-closed-time-regexp)
3641 (defvar org-keyword-time-regexp nil
3642 "Matches any of the 4 keywords, together with the time stamp.")
3643 (make-variable-buffer-local 'org-keyword-time-regexp)
3644 (defvar org-keyword-time-not-clock-regexp nil
3645 "Matches any of the 3 keywords, together with the time stamp.")
3646 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3647 (defvar org-maybe-keyword-time-regexp nil
3648 "Matches a timestamp, possibly preceeded by a keyword.")
3649 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3650 (defvar org-planning-or-clock-line-re nil
3651 "Matches a line with planning or clock info.")
3652 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3654 (defconst org-plain-time-of-day-regexp
3655 (concat
3656 "\\(\\<[012]?[0-9]"
3657 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3658 "\\(--?"
3659 "\\(\\<[012]?[0-9]"
3660 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3661 "\\)?")
3662 "Regular expression to match a plain time or time range.
3663 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3664 groups carry important information:
3665 0 the full match
3666 1 the first time, range or not
3667 8 the second time, if it is a range.")
3669 (defconst org-plain-time-extension-regexp
3670 (concat
3671 "\\(\\<[012]?[0-9]"
3672 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3673 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3674 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3675 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3676 groups carry important information:
3677 0 the full match
3678 7 hours of duration
3679 9 minutes of duration")
3681 (defconst org-stamp-time-of-day-regexp
3682 (concat
3683 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3684 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3685 "\\(--?"
3686 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3687 "Regular expression to match a timestamp time or time range.
3688 After a match, the following groups carry important information:
3689 0 the full match
3690 1 date plus weekday, for back referencing to make sure both times are on the same day
3691 2 the first time, range or not
3692 4 the second time, if it is a range.")
3694 (defconst org-startup-options
3695 '(("fold" org-startup-folded t)
3696 ("overview" org-startup-folded t)
3697 ("nofold" org-startup-folded nil)
3698 ("showall" org-startup-folded nil)
3699 ("showeverything" org-startup-folded showeverything)
3700 ("content" org-startup-folded content)
3701 ("indent" org-startup-indented t)
3702 ("noindent" org-startup-indented nil)
3703 ("hidestars" org-hide-leading-stars t)
3704 ("showstars" org-hide-leading-stars nil)
3705 ("odd" org-odd-levels-only t)
3706 ("oddeven" org-odd-levels-only nil)
3707 ("align" org-startup-align-all-tables t)
3708 ("noalign" org-startup-align-all-tables nil)
3709 ("customtime" org-display-custom-times t)
3710 ("logdone" org-log-done time)
3711 ("lognotedone" org-log-done note)
3712 ("nologdone" org-log-done nil)
3713 ("lognoteclock-out" org-log-note-clock-out t)
3714 ("nolognoteclock-out" org-log-note-clock-out nil)
3715 ("logrepeat" org-log-repeat state)
3716 ("lognoterepeat" org-log-repeat note)
3717 ("nologrepeat" org-log-repeat nil)
3718 ("logreschedule" org-log-reschedule time)
3719 ("lognotereschedule" org-log-reschedule note)
3720 ("nologreschedule" org-log-reschedule nil)
3721 ("logredeadline" org-log-redeadline time)
3722 ("lognoteredeadline" org-log-redeadline note)
3723 ("nologredeadline" org-log-redeadline nil)
3724 ("fninline" org-footnote-define-inline t)
3725 ("nofninline" org-footnote-define-inline nil)
3726 ("fnlocal" org-footnote-section nil)
3727 ("fnauto" org-footnote-auto-label t)
3728 ("fnprompt" org-footnote-auto-label nil)
3729 ("fnconfirm" org-footnote-auto-label confirm)
3730 ("fnplain" org-footnote-auto-label plain)
3731 ("fnadjust" org-footnote-auto-adjust t)
3732 ("nofnadjust" org-footnote-auto-adjust nil)
3733 ("constcgs" constants-unit-system cgs)
3734 ("constSI" constants-unit-system SI)
3735 ("noptag" org-tag-persistent-alist nil)
3736 ("hideblocks" org-hide-block-startup t)
3737 ("nohideblocks" org-hide-block-startup nil))
3738 "Variable associated with STARTUP options for org-mode.
3739 Each element is a list of three items: The startup options as written
3740 in the #+STARTUP line, the corresponding variable, and the value to
3741 set this variable to if the option is found. An optional forth element PUSH
3742 means to push this value onto the list in the variable.")
3744 (defun org-set-regexps-and-options ()
3745 "Precompute regular expressions for current buffer."
3746 (when (org-mode-p)
3747 (org-set-local 'org-todo-kwd-alist nil)
3748 (org-set-local 'org-todo-key-alist nil)
3749 (org-set-local 'org-todo-key-trigger nil)
3750 (org-set-local 'org-todo-keywords-1 nil)
3751 (org-set-local 'org-done-keywords nil)
3752 (org-set-local 'org-todo-heads nil)
3753 (org-set-local 'org-todo-sets nil)
3754 (org-set-local 'org-todo-log-states nil)
3755 (org-set-local 'org-file-properties nil)
3756 (org-set-local 'org-file-tags nil)
3757 (let ((re (org-make-options-regexp
3758 '("CATEGORY" "TODO" "COLUMNS"
3759 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3760 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3761 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3762 (splitre "[ \t]+")
3763 kwds kws0 kwsa key log value cat arch tags const links hw dws
3764 tail sep kws1 prio props ftags drawers
3765 ext-setup-or-nil setup-contents (start 0))
3766 (save-excursion
3767 (save-restriction
3768 (widen)
3769 (goto-char (point-min))
3770 (while (or (and ext-setup-or-nil
3771 (string-match re ext-setup-or-nil start)
3772 (setq start (match-end 0)))
3773 (and (setq ext-setup-or-nil nil start 0)
3774 (re-search-forward re nil t)))
3775 (setq key (upcase (match-string 1 ext-setup-or-nil))
3776 value (org-match-string-no-properties 2 ext-setup-or-nil))
3777 (cond
3778 ((equal key "CATEGORY")
3779 (if (string-match "[ \t]+$" value)
3780 (setq value (replace-match "" t t value)))
3781 (setq cat value))
3782 ((member key '("SEQ_TODO" "TODO"))
3783 (push (cons 'sequence (org-split-string value splitre)) kwds))
3784 ((equal key "TYP_TODO")
3785 (push (cons 'type (org-split-string value splitre)) kwds))
3786 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3787 ;; general TODO-like setup
3788 (push (cons (intern (downcase (match-string 1 key)))
3789 (org-split-string value splitre)) kwds))
3790 ((equal key "TAGS")
3791 (setq tags (append tags (if tags '("\\n") nil)
3792 (org-split-string value splitre))))
3793 ((equal key "COLUMNS")
3794 (org-set-local 'org-columns-default-format value))
3795 ((equal key "LINK")
3796 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3797 (push (cons (match-string 1 value)
3798 (org-trim (match-string 2 value)))
3799 links)))
3800 ((equal key "PRIORITIES")
3801 (setq prio (org-split-string value " +")))
3802 ((equal key "PROPERTY")
3803 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3804 (push (cons (match-string 1 value) (match-string 2 value))
3805 props)))
3806 ((equal key "FILETAGS")
3807 (when (string-match "\\S-" value)
3808 (setq ftags
3809 (append
3810 ftags
3811 (apply 'append
3812 (mapcar (lambda (x) (org-split-string x ":"))
3813 (org-split-string value)))))))
3814 ((equal key "DRAWERS")
3815 (setq drawers (org-split-string value splitre)))
3816 ((equal key "CONSTANTS")
3817 (setq const (append const (org-split-string value splitre))))
3818 ((equal key "STARTUP")
3819 (let ((opts (org-split-string value splitre))
3820 l var val)
3821 (while (setq l (pop opts))
3822 (when (setq l (assoc l org-startup-options))
3823 (setq var (nth 1 l) val (nth 2 l))
3824 (if (not (nth 3 l))
3825 (set (make-local-variable var) val)
3826 (if (not (listp (symbol-value var)))
3827 (set (make-local-variable var) nil))
3828 (set (make-local-variable var) (symbol-value var))
3829 (add-to-list var val))))))
3830 ((equal key "ARCHIVE")
3831 (string-match " *$" value)
3832 (setq arch (replace-match "" t t value))
3833 (remove-text-properties 0 (length arch)
3834 '(face t fontified t) arch))
3835 ((equal key "SETUPFILE")
3836 (setq setup-contents (org-file-contents
3837 (expand-file-name
3838 (org-remove-double-quotes value))
3839 'noerror))
3840 (if (not ext-setup-or-nil)
3841 (setq ext-setup-or-nil setup-contents start 0)
3842 (setq ext-setup-or-nil
3843 (concat (substring ext-setup-or-nil 0 start)
3844 "\n" setup-contents "\n"
3845 (substring ext-setup-or-nil start)))))
3846 ))))
3847 (when cat
3848 (org-set-local 'org-category (intern cat))
3849 (push (cons "CATEGORY" cat) props))
3850 (when prio
3851 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3852 (setq prio (mapcar 'string-to-char prio))
3853 (org-set-local 'org-highest-priority (nth 0 prio))
3854 (org-set-local 'org-lowest-priority (nth 1 prio))
3855 (org-set-local 'org-default-priority (nth 2 prio)))
3856 (and props (org-set-local 'org-file-properties (nreverse props)))
3857 (and ftags (org-set-local 'org-file-tags
3858 (mapcar 'org-add-prop-inherited ftags)))
3859 (and drawers (org-set-local 'org-drawers drawers))
3860 (and arch (org-set-local 'org-archive-location arch))
3861 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3862 ;; Process the TODO keywords
3863 (unless kwds
3864 ;; Use the global values as if they had been given locally.
3865 (setq kwds (default-value 'org-todo-keywords))
3866 (if (stringp (car kwds))
3867 (setq kwds (list (cons org-todo-interpretation
3868 (default-value 'org-todo-keywords)))))
3869 (setq kwds (reverse kwds)))
3870 (setq kwds (nreverse kwds))
3871 (let (inter kws kw)
3872 (while (setq kws (pop kwds))
3873 (let ((kws (or
3874 (run-hook-with-args-until-success
3875 'org-todo-setup-filter-hook kws)
3876 kws)))
3877 (setq inter (pop kws) sep (member "|" kws)
3878 kws0 (delete "|" (copy-sequence kws))
3879 kwsa nil
3880 kws1 (mapcar
3881 (lambda (x)
3882 ;; 1 2
3883 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3884 (progn
3885 (setq kw (match-string 1 x)
3886 key (and (match-end 2) (match-string 2 x))
3887 log (org-extract-log-state-settings x))
3888 (push (cons kw (and key (string-to-char key))) kwsa)
3889 (and log (push log org-todo-log-states))
3891 (error "Invalid TODO keyword %s" x)))
3892 kws0)
3893 kwsa (if kwsa (append '((:startgroup))
3894 (nreverse kwsa)
3895 '((:endgroup))))
3896 hw (car kws1)
3897 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3898 tail (list inter hw (car dws) (org-last dws))))
3899 (add-to-list 'org-todo-heads hw 'append)
3900 (push kws1 org-todo-sets)
3901 (setq org-done-keywords (append org-done-keywords dws nil))
3902 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3903 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3904 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3905 (setq org-todo-sets (nreverse org-todo-sets)
3906 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3907 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3908 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3909 ;; Process the constants
3910 (when const
3911 (let (e cst)
3912 (while (setq e (pop const))
3913 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3914 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3915 (setq org-table-formula-constants-local cst)))
3917 ;; Process the tags.
3918 (when tags
3919 (let (e tgs)
3920 (while (setq e (pop tags))
3921 (cond
3922 ((equal e "{") (push '(:startgroup) tgs))
3923 ((equal e "}") (push '(:endgroup) tgs))
3924 ((equal e "\\n") (push '(:newline) tgs))
3925 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3926 (push (cons (match-string 1 e)
3927 (string-to-char (match-string 2 e)))
3928 tgs))
3929 (t (push (list e) tgs))))
3930 (org-set-local 'org-tag-alist nil)
3931 (while (setq e (pop tgs))
3932 (or (and (stringp (car e))
3933 (assoc (car e) org-tag-alist))
3934 (push e org-tag-alist)))))
3936 ;; Compute the regular expressions and other local variables
3937 (if (not org-done-keywords)
3938 (setq org-done-keywords (and org-todo-keywords-1
3939 (list (org-last org-todo-keywords-1)))))
3940 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3941 (length org-scheduled-string)
3942 (length org-clock-string)
3943 (length org-closed-string)))
3944 org-drawer-regexp
3945 (concat "^[ \t]*:\\("
3946 (mapconcat 'regexp-quote org-drawers "\\|")
3947 "\\):[ \t]*$")
3948 org-not-done-keywords
3949 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3950 org-todo-regexp
3951 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3952 "\\|") "\\)\\>")
3953 org-not-done-regexp
3954 (concat "\\<\\("
3955 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3956 "\\)\\>")
3957 org-not-done-heading-regexp
3958 (concat "^\\(\\*+\\)[ \t]+\\("
3959 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3960 "\\)\\>")
3961 org-todo-line-regexp
3962 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3963 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3964 "\\)\\>\\)?[ \t]*\\(.*\\)")
3965 org-complex-heading-regexp
3966 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3967 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3968 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3969 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3970 org-complex-heading-regexp-format
3971 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3972 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3973 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3974 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3975 org-nl-done-regexp
3976 (concat "\n\\*+[ \t]+"
3977 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3978 "\\)" "\\>")
3979 org-todo-line-tags-regexp
3980 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3981 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3982 (org-re
3983 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3984 org-looking-at-done-regexp
3985 (concat "^" "\\(?:"
3986 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3987 "\\>")
3988 org-deadline-regexp (concat "\\<" org-deadline-string)
3989 org-deadline-time-regexp
3990 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3991 org-deadline-line-regexp
3992 (concat "\\<\\(" org-deadline-string "\\).*")
3993 org-scheduled-regexp
3994 (concat "\\<" org-scheduled-string)
3995 org-scheduled-time-regexp
3996 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3997 org-closed-time-regexp
3998 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3999 org-keyword-time-regexp
4000 (concat "\\<\\(" org-scheduled-string
4001 "\\|" org-deadline-string
4002 "\\|" org-closed-string
4003 "\\|" org-clock-string "\\)"
4004 " *[[<]\\([^]>]+\\)[]>]")
4005 org-keyword-time-not-clock-regexp
4006 (concat "\\<\\(" org-scheduled-string
4007 "\\|" org-deadline-string
4008 "\\|" org-closed-string
4009 "\\)"
4010 " *[[<]\\([^]>]+\\)[]>]")
4011 org-maybe-keyword-time-regexp
4012 (concat "\\(\\<\\(" org-scheduled-string
4013 "\\|" org-deadline-string
4014 "\\|" org-closed-string
4015 "\\|" org-clock-string "\\)\\)?"
4016 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4017 org-planning-or-clock-line-re
4018 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4019 "\\|" org-deadline-string
4020 "\\|" org-closed-string "\\|" org-clock-string
4021 "\\)\\>\\)")
4023 (org-compute-latex-and-specials-regexp)
4024 (org-set-font-lock-defaults))))
4026 (defun org-file-contents (file &optional noerror)
4027 "Return the contents of FILE, as a string."
4028 (if (or (not file)
4029 (not (file-readable-p file)))
4030 (if noerror
4031 (progn
4032 (message "Cannot read file %s" file)
4033 (ding) (sit-for 2)
4035 (error "Cannot read file %s" file))
4036 (with-temp-buffer
4037 (insert-file-contents file)
4038 (buffer-string))))
4040 (defun org-extract-log-state-settings (x)
4041 "Extract the log state setting from a TODO keyword string.
4042 This will extract info from a string like \"WAIT(w@/!)\"."
4043 (let (kw key log1 log2)
4044 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4045 (setq kw (match-string 1 x)
4046 key (and (match-end 2) (match-string 2 x))
4047 log1 (and (match-end 3) (match-string 3 x))
4048 log2 (and (match-end 4) (match-string 4 x)))
4049 (and (or log1 log2)
4050 (list kw
4051 (and log1 (if (equal log1 "!") 'time 'note))
4052 (and log2 (if (equal log2 "!") 'time 'note)))))))
4054 (defun org-remove-keyword-keys (list)
4055 "Remove a pair of parenthesis at the end of each string in LIST."
4056 (mapcar (lambda (x)
4057 (if (string-match "(.*)$" x)
4058 (substring x 0 (match-beginning 0))
4060 list))
4062 ;; FIXME: this could be done much better, using second characters etc.
4063 (defun org-assign-fast-keys (alist)
4064 "Assign fast keys to a keyword-key alist.
4065 Respect keys that are already there."
4066 (let (new e k c c1 c2 (char ?a))
4067 (while (setq e (pop alist))
4068 (cond
4069 ((equal e '(:startgroup)) (push e new))
4070 ((equal e '(:endgroup)) (push e new))
4071 ((equal e '(:newline)) (push e new))
4073 (setq k (car e) c2 nil)
4074 (if (cdr e)
4075 (setq c (cdr e))
4076 ;; automatically assign a character.
4077 (setq c1 (string-to-char
4078 (downcase (substring
4079 k (if (= (string-to-char k) ?@) 1 0)))))
4080 (if (or (rassoc c1 new) (rassoc c1 alist))
4081 (while (or (rassoc char new) (rassoc char alist))
4082 (setq char (1+ char)))
4083 (setq c2 c1))
4084 (setq c (or c2 char)))
4085 (push (cons k c) new))))
4086 (nreverse new)))
4088 ;;; Some variables used in various places
4090 (defvar org-window-configuration nil
4091 "Used in various places to store a window configuration.")
4092 (defvar org-selected-window nil
4093 "Used in various places to store a window configuration.")
4094 (defvar org-finish-function nil
4095 "Function to be called when `C-c C-c' is used.
4096 This is for getting out of special buffers like remember.")
4099 ;; FIXME: Occasionally check by commenting these, to make sure
4100 ;; no other functions uses these, forgetting to let-bind them.
4101 (defvar entry)
4102 (defvar last-state)
4103 (defvar date)
4105 ;; Defined somewhere in this file, but used before definition.
4106 (defvar org-html-entities)
4107 (defvar org-struct-menu)
4108 (defvar org-org-menu)
4109 (defvar org-tbl-menu)
4111 ;;;; Define the Org-mode
4113 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4114 (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."))
4117 ;; We use a before-change function to check if a table might need
4118 ;; an update.
4119 (defvar org-table-may-need-update t
4120 "Indicates that a table might need an update.
4121 This variable is set by `org-before-change-function'.
4122 `org-table-align' sets it back to nil.")
4123 (defun org-before-change-function (beg end)
4124 "Every change indicates that a table might need an update."
4125 (setq org-table-may-need-update t))
4126 (defvar org-mode-map)
4127 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4128 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4129 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4130 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4131 (defvar org-table-buffer-is-an nil)
4132 (defconst org-outline-regexp "\\*+ ")
4134 ;;;###autoload
4135 (define-derived-mode org-mode outline-mode "Org"
4136 "Outline-based notes management and organizer, alias
4137 \"Carsten's outline-mode for keeping track of everything.\"
4139 Org-mode develops organizational tasks around a NOTES file which
4140 contains information about projects as plain text. Org-mode is
4141 implemented on top of outline-mode, which is ideal to keep the content
4142 of large files well structured. It supports ToDo items, deadlines and
4143 time stamps, which magically appear in the diary listing of the Emacs
4144 calendar. Tables are easily created with a built-in table editor.
4145 Plain text URL-like links connect to websites, emails (VM), Usenet
4146 messages (Gnus), BBDB entries, and any files related to the project.
4147 For printing and sharing of notes, an Org-mode file (or a part of it)
4148 can be exported as a structured ASCII or HTML file.
4150 The following commands are available:
4152 \\{org-mode-map}"
4154 ;; Get rid of Outline menus, they are not needed
4155 ;; Need to do this here because define-derived-mode sets up
4156 ;; the keymap so late. Still, it is a waste to call this each time
4157 ;; we switch another buffer into org-mode.
4158 (if (featurep 'xemacs)
4159 (when (boundp 'outline-mode-menu-heading)
4160 ;; Assume this is Greg's port, it used easymenu
4161 (easy-menu-remove outline-mode-menu-heading)
4162 (easy-menu-remove outline-mode-menu-show)
4163 (easy-menu-remove outline-mode-menu-hide))
4164 (define-key org-mode-map [menu-bar headings] 'undefined)
4165 (define-key org-mode-map [menu-bar hide] 'undefined)
4166 (define-key org-mode-map [menu-bar show] 'undefined))
4168 (org-load-modules-maybe)
4169 (easy-menu-add org-org-menu)
4170 (easy-menu-add org-tbl-menu)
4171 (org-install-agenda-files-menu)
4172 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4173 (org-add-to-invisibility-spec '(org-cwidth))
4174 (org-add-to-invisibility-spec '(org-hide-block . t))
4175 (when (featurep 'xemacs)
4176 (org-set-local 'line-move-ignore-invisible t))
4177 (org-set-local 'outline-regexp org-outline-regexp)
4178 (org-set-local 'outline-level 'org-outline-level)
4179 (when (and org-ellipsis
4180 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4181 (fboundp 'make-glyph-code))
4182 (unless org-display-table
4183 (setq org-display-table (make-display-table)))
4184 (set-display-table-slot
4185 org-display-table 4
4186 (vconcat (mapcar
4187 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4188 org-ellipsis)))
4189 (if (stringp org-ellipsis) org-ellipsis "..."))))
4190 (setq buffer-display-table org-display-table))
4191 (org-set-regexps-and-options)
4192 (when (and org-tag-faces (not org-tags-special-faces-re))
4193 ;; tag faces set outside customize.... force initialization.
4194 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4195 ;; Calc embedded
4196 (org-set-local 'calc-embedded-open-mode "# ")
4197 (modify-syntax-entry ?# "<")
4198 (modify-syntax-entry ?@ "w")
4199 (if org-startup-truncated (setq truncate-lines t))
4200 (org-set-local 'font-lock-unfontify-region-function
4201 'org-unfontify-region)
4202 ;; Activate before-change-function
4203 (org-set-local 'org-table-may-need-update t)
4204 (org-add-hook 'before-change-functions 'org-before-change-function nil
4205 'local)
4206 ;; Check for running clock before killing a buffer
4207 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4208 ;; Paragraphs and auto-filling
4209 (org-set-autofill-regexps)
4210 (setq indent-line-function 'org-indent-line-function)
4211 (org-update-radio-target-regexp)
4212 ;; Make sure dependence stuff works reliably, even for users who set it
4213 ;; too late :-(
4214 (if org-enforce-todo-dependencies
4215 (add-hook 'org-blocker-hook
4216 'org-block-todo-from-children-or-siblings-or-parent)
4217 (remove-hook 'org-blocker-hook
4218 'org-block-todo-from-children-or-siblings-or-parent))
4219 (if org-enforce-todo-checkbox-dependencies
4220 (add-hook 'org-blocker-hook
4221 'org-block-todo-from-checkboxes)
4222 (remove-hook 'org-blocker-hook
4223 'org-block-todo-from-checkboxes))
4225 ;; Comment characters
4226 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4227 (org-set-local 'comment-padding " ")
4229 ;; Align options lines
4230 (org-set-local
4231 'align-mode-rules-list
4232 '((org-in-buffer-settings
4233 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4234 (modes . '(org-mode)))))
4236 ;; Imenu
4237 (org-set-local 'imenu-create-index-function
4238 'org-imenu-get-tree)
4240 ;; Make isearch reveal context
4241 (if (or (featurep 'xemacs)
4242 (not (boundp 'outline-isearch-open-invisible-function)))
4243 ;; Emacs 21 and XEmacs make use of the hook
4244 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4245 ;; Emacs 22 deals with this through a special variable
4246 (org-set-local 'outline-isearch-open-invisible-function
4247 (lambda (&rest ignore) (org-show-context 'isearch))))
4249 ;; If empty file that did not turn on org-mode automatically, make it to.
4250 (if (and org-insert-mode-line-in-empty-file
4251 (interactive-p)
4252 (= (point-min) (point-max)))
4253 (insert "# -*- mode: org -*-\n\n"))
4255 (unless org-inhibit-startup
4256 (when org-startup-align-all-tables
4257 (let ((bmp (buffer-modified-p)))
4258 (org-table-map-tables 'org-table-align)
4259 (set-buffer-modified-p bmp)))
4260 (when org-startup-indented
4261 (require 'org-indent)
4262 (org-indent-mode 1))
4263 (org-set-startup-visibility)))
4265 (when (fboundp 'abbrev-table-put)
4266 (abbrev-table-put org-mode-abbrev-table
4267 :parents (list text-mode-abbrev-table)))
4269 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4271 (defun org-current-time ()
4272 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4273 (if (> (car org-time-stamp-rounding-minutes) 1)
4274 (let ((r (car org-time-stamp-rounding-minutes))
4275 (time (decode-time)))
4276 (apply 'encode-time
4277 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4278 (nthcdr 2 time))))
4279 (current-time)))
4281 ;;;; Font-Lock stuff, including the activators
4283 (defvar org-mouse-map (make-sparse-keymap))
4284 (org-defkey org-mouse-map
4285 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4286 (org-defkey org-mouse-map
4287 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4288 (when org-mouse-1-follows-link
4289 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4290 (when org-tab-follows-link
4291 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4292 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4294 (require 'font-lock)
4296 (defconst org-non-link-chars "]\t\n\r<>")
4297 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4298 "shell" "elisp"))
4299 (defvar org-link-types-re nil
4300 "Matches a link that has a url-like prefix like \"http:\"")
4301 (defvar org-link-re-with-space nil
4302 "Matches a link with spaces, optional angular brackets around it.")
4303 (defvar org-link-re-with-space2 nil
4304 "Matches a link with spaces, optional angular brackets around it.")
4305 (defvar org-link-re-with-space3 nil
4306 "Matches a link with spaces, only for internal part in bracket links.")
4307 (defvar org-angle-link-re nil
4308 "Matches link with angular brackets, spaces are allowed.")
4309 (defvar org-plain-link-re nil
4310 "Matches plain link, without spaces.")
4311 (defvar org-bracket-link-regexp nil
4312 "Matches a link in double brackets.")
4313 (defvar org-bracket-link-analytic-regexp nil
4314 "Regular expression used to analyze links.
4315 Here is what the match groups contain after a match:
4316 1: http:
4317 2: http
4318 3: path
4319 4: [desc]
4320 5: desc")
4321 (defvar org-bracket-link-analytic-regexp++ nil
4322 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4323 (defvar org-any-link-re nil
4324 "Regular expression matching any link.")
4326 (defun org-make-link-regexps ()
4327 "Update the link regular expressions.
4328 This should be called after the variable `org-link-types' has changed."
4329 (setq org-link-types-re
4330 (concat
4331 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4332 org-link-re-with-space
4333 (concat
4334 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4335 "\\([^" org-non-link-chars " ]"
4336 "[^" org-non-link-chars "]*"
4337 "[^" org-non-link-chars " ]\\)>?")
4338 org-link-re-with-space2
4339 (concat
4340 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4341 "\\([^" org-non-link-chars " ]"
4342 "[^\t\n\r]*"
4343 "[^" org-non-link-chars " ]\\)>?")
4344 org-link-re-with-space3
4345 (concat
4346 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4347 "\\([^" org-non-link-chars " ]"
4348 "[^\t\n\r]*\\)")
4349 org-angle-link-re
4350 (concat
4351 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4352 "\\([^" org-non-link-chars " ]"
4353 "[^" org-non-link-chars "]*"
4354 "\\)>")
4355 org-plain-link-re
4356 (concat
4357 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4358 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4359 org-bracket-link-regexp
4360 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4361 org-bracket-link-analytic-regexp
4362 (concat
4363 "\\[\\["
4364 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4365 "\\([^]]+\\)"
4366 "\\]"
4367 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4368 "\\]")
4369 org-bracket-link-analytic-regexp++
4370 (concat
4371 "\\[\\["
4372 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4373 "\\([^]]+\\)"
4374 "\\]"
4375 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4376 "\\]")
4377 org-any-link-re
4378 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4379 org-angle-link-re "\\)\\|\\("
4380 org-plain-link-re "\\)")))
4382 (org-make-link-regexps)
4384 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4385 "Regular expression for fast time stamp matching.")
4386 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4387 "Regular expression for fast time stamp matching.")
4388 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4389 "Regular expression matching time strings for analysis.
4390 This one does not require the space after the date, so it can be used
4391 on a string that terminates immediately after the date.")
4392 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4393 "Regular expression matching time strings for analysis.")
4394 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4395 "Regular expression matching time stamps, with groups.")
4396 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4397 "Regular expression matching time stamps (also [..]), with groups.")
4398 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4399 "Regular expression matching a time stamp range.")
4400 (defconst org-tr-regexp-both
4401 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4402 "Regular expression matching a time stamp range.")
4403 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4404 org-ts-regexp "\\)?")
4405 "Regular expression matching a time stamp or time stamp range.")
4406 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4407 org-ts-regexp-both "\\)?")
4408 "Regular expression matching a time stamp or time stamp range.
4409 The time stamps may be either active or inactive.")
4411 (defvar org-emph-face nil)
4413 (defun org-do-emphasis-faces (limit)
4414 "Run through the buffer and add overlays to links."
4415 (let (rtn a)
4416 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4417 (if (not (= (char-after (match-beginning 3))
4418 (char-after (match-beginning 4))))
4419 (progn
4420 (setq rtn t)
4421 (setq a (assoc (match-string 3) org-emphasis-alist))
4422 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4423 'face
4424 (nth 1 a))
4425 (and (nth 4 a)
4426 (org-remove-flyspell-overlays-in
4427 (match-beginning 0) (match-end 0)))
4428 (add-text-properties (match-beginning 2) (match-end 2)
4429 '(font-lock-multiline t))
4430 (when org-hide-emphasis-markers
4431 (add-text-properties (match-end 4) (match-beginning 5)
4432 '(invisible org-link))
4433 (add-text-properties (match-beginning 3) (match-end 3)
4434 '(invisible org-link)))))
4435 (backward-char 1))
4436 rtn))
4438 (defun org-emphasize (&optional char)
4439 "Insert or change an emphasis, i.e. a font like bold or italic.
4440 If there is an active region, change that region to a new emphasis.
4441 If there is no region, just insert the marker characters and position
4442 the cursor between them.
4443 CHAR should be either the marker character, or the first character of the
4444 HTML tag associated with that emphasis. If CHAR is a space, the means
4445 to remove the emphasis of the selected region.
4446 If char is not given (for example in an interactive call) it
4447 will be prompted for."
4448 (interactive)
4449 (let ((eal org-emphasis-alist) e det
4450 (erc org-emphasis-regexp-components)
4451 (prompt "")
4452 (string "") beg end move tag c s)
4453 (if (org-region-active-p)
4454 (setq beg (region-beginning) end (region-end)
4455 string (buffer-substring beg end))
4456 (setq move t))
4458 (while (setq e (pop eal))
4459 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4460 c (aref tag 0))
4461 (push (cons c (string-to-char (car e))) det)
4462 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4463 (substring tag 1)))))
4464 (setq det (nreverse det))
4465 (unless char
4466 (message "%s" (concat "Emphasis marker or tag:" prompt))
4467 (setq char (read-char-exclusive)))
4468 (setq char (or (cdr (assoc char det)) char))
4469 (if (equal char ?\ )
4470 (setq s "" move nil)
4471 (unless (assoc (char-to-string char) org-emphasis-alist)
4472 (error "No such emphasis marker: \"%c\"" char))
4473 (setq s (char-to-string char)))
4474 (while (and (> (length string) 1)
4475 (equal (substring string 0 1) (substring string -1))
4476 (assoc (substring string 0 1) org-emphasis-alist))
4477 (setq string (substring string 1 -1)))
4478 (setq string (concat s string s))
4479 (if beg (delete-region beg end))
4480 (unless (or (bolp)
4481 (string-match (concat "[" (nth 0 erc) "\n]")
4482 (char-to-string (char-before (point)))))
4483 (insert " "))
4484 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4485 (char-to-string (char-after (point))))
4486 (insert " ") (backward-char 1))
4487 (insert string)
4488 (and move (backward-char 1))))
4490 (defconst org-nonsticky-props
4491 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4493 (defsubst org-rear-nonsticky-at (pos)
4494 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4496 (defun org-activate-plain-links (limit)
4497 "Run through the buffer and add overlays to links."
4498 (catch 'exit
4499 (let (f)
4500 (if (re-search-forward org-plain-link-re limit t)
4501 (progn
4502 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4503 (setq f (get-text-property (match-beginning 0) 'face))
4504 (if (or (eq f 'org-tag)
4505 (and (listp f) (memq 'org-tag f)))
4507 (add-text-properties (match-beginning 0) (match-end 0)
4508 (list 'mouse-face 'highlight
4509 'keymap org-mouse-map))
4510 (org-rear-nonsticky-at (match-end 0)))
4511 t)))))
4513 (defun org-activate-code (limit)
4514 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4515 (progn
4516 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4517 (remove-text-properties (match-beginning 0) (match-end 0)
4518 '(display t invisible t intangible t))
4519 t)))
4521 (defun org-fontify-meta-lines-and-blocks (limit)
4522 "Fontify #+ lines and blocks, in the correct ways."
4523 (let ((case-fold-search t))
4524 (if (re-search-forward
4525 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4526 limit t)
4527 (let ((beg (match-beginning 0))
4528 (beg1 (line-beginning-position 2))
4529 (dc1 (downcase (match-string 2)))
4530 (dc3 (downcase (match-string 3)))
4531 end end1 quoting)
4532 (cond
4533 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4534 ;; a single line of backend-specific content
4535 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4536 (remove-text-properties (match-beginning 0) (match-end 0)
4537 '(display t invisible t intangible t))
4538 (add-text-properties (match-beginning 1) (match-end 3)
4539 '(font-lock-fontified t face org-meta-line))
4540 (add-text-properties (match-beginning 6) (match-end 6)
4541 '(font-lock-fontified t face org-block))
4543 ((and (match-end 4) (equal dc3 "begin"))
4544 ;; Truely a block
4545 (setq quoting (member (downcase (match-string 5))
4546 org-protecting-blocks))
4547 (when (re-search-forward
4548 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4549 nil t) ;; on purpose, we look further than LIMIT
4550 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4551 (when quoting
4552 (remove-text-properties beg end
4553 '(display t invisible t intangible t)))
4554 (add-text-properties
4555 beg end
4556 '(font-lock-fontified t font-lock-multiline t))
4557 (add-text-properties beg beg1 '(face org-meta-line))
4558 (add-text-properties end1 end '(face org-meta-line))
4559 (when quoting
4560 (add-text-properties beg1 end1 '(face org-block)))
4562 ((not (member (char-after beg) '(?\ ?\t)))
4563 ;; just any other in-buffer setting, but not indented
4564 (add-text-properties
4565 beg (match-end 0)
4566 '(font-lock-fontified t face org-meta-line))
4568 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4569 "orgtbl:" "tblfm:" "tblname:"))
4570 (and (match-end 4) (equal dc3 "attr")))
4571 (add-text-properties
4572 beg (match-end 0)
4573 '(font-lock-fontified t face org-meta-line))
4575 ((member dc3 '(" " ""))
4576 (add-text-properties
4577 beg (match-end 0)
4578 '(font-lock-fontified t face font-lock-comment-face)))
4579 (t nil))))))
4581 (defun org-activate-angle-links (limit)
4582 "Run through the buffer and add overlays to links."
4583 (if (re-search-forward org-angle-link-re limit t)
4584 (progn
4585 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4586 (add-text-properties (match-beginning 0) (match-end 0)
4587 (list 'mouse-face 'highlight
4588 'keymap org-mouse-map))
4589 (org-rear-nonsticky-at (match-end 0))
4590 t)))
4592 (defun org-activate-footnote-links (limit)
4593 "Run through the buffer and add overlays to links."
4594 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4595 limit t)
4596 (progn
4597 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4598 (add-text-properties (match-beginning 2) (match-end 2)
4599 (list 'mouse-face 'highlight
4600 'keymap org-mouse-map
4601 'help-echo
4602 (if (= (point-at-bol) (match-beginning 2))
4603 "Footnote definition"
4604 "Footnote reference")
4606 (org-rear-nonsticky-at (match-end 2))
4607 t)))
4609 (defun org-activate-bracket-links (limit)
4610 "Run through the buffer and add overlays to bracketed links."
4611 (if (re-search-forward org-bracket-link-regexp limit t)
4612 (let* ((help (concat "LINK: "
4613 (org-match-string-no-properties 1)))
4614 ;; FIXME: above we should remove the escapes.
4615 ;; but that requires another match, protecting match data,
4616 ;; a lot of overhead for font-lock.
4617 (ip (org-maybe-intangible
4618 (list 'invisible 'org-link
4619 'keymap org-mouse-map 'mouse-face 'highlight
4620 'font-lock-multiline t 'help-echo help)))
4621 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4622 'font-lock-multiline t 'help-echo help)))
4623 ;; We need to remove the invisible property here. Table narrowing
4624 ;; may have made some of this invisible.
4625 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4626 (remove-text-properties (match-beginning 0) (match-end 0)
4627 '(invisible nil))
4628 (if (match-end 3)
4629 (progn
4630 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4631 (org-rear-nonsticky-at (match-beginning 3))
4632 (add-text-properties (match-beginning 3) (match-end 3) vp)
4633 (org-rear-nonsticky-at (match-end 3))
4634 (add-text-properties (match-end 3) (match-end 0) ip)
4635 (org-rear-nonsticky-at (match-end 0)))
4636 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4637 (org-rear-nonsticky-at (match-beginning 1))
4638 (add-text-properties (match-beginning 1) (match-end 1) vp)
4639 (org-rear-nonsticky-at (match-end 1))
4640 (add-text-properties (match-end 1) (match-end 0) ip)
4641 (org-rear-nonsticky-at (match-end 0)))
4642 t)))
4644 (defun org-activate-dates (limit)
4645 "Run through the buffer and add overlays to dates."
4646 (if (re-search-forward org-tsr-regexp-both limit t)
4647 (progn
4648 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4649 (add-text-properties (match-beginning 0) (match-end 0)
4650 (list 'mouse-face 'highlight
4651 'keymap org-mouse-map))
4652 (org-rear-nonsticky-at (match-end 0))
4653 (when org-display-custom-times
4654 (if (match-end 3)
4655 (org-display-custom-time (match-beginning 3) (match-end 3)))
4656 (org-display-custom-time (match-beginning 1) (match-end 1)))
4657 t)))
4659 (defvar org-target-link-regexp nil
4660 "Regular expression matching radio targets in plain text.")
4661 (make-variable-buffer-local 'org-target-link-regexp)
4662 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4663 "Regular expression matching a link target.")
4664 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4665 "Regular expression matching a radio target.")
4666 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4667 "Regular expression matching any target.")
4669 (defun org-activate-target-links (limit)
4670 "Run through the buffer and add overlays to target matches."
4671 (when org-target-link-regexp
4672 (let ((case-fold-search t))
4673 (if (re-search-forward org-target-link-regexp limit t)
4674 (progn
4675 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4676 (add-text-properties (match-beginning 0) (match-end 0)
4677 (list 'mouse-face 'highlight
4678 'keymap org-mouse-map
4679 'help-echo "Radio target link"
4680 'org-linked-text t))
4681 (org-rear-nonsticky-at (match-end 0))
4682 t)))))
4684 (defun org-update-radio-target-regexp ()
4685 "Find all radio targets in this file and update the regular expression."
4686 (interactive)
4687 (when (memq 'radio org-activate-links)
4688 (setq org-target-link-regexp
4689 (org-make-target-link-regexp (org-all-targets 'radio)))
4690 (org-restart-font-lock)))
4692 (defun org-hide-wide-columns (limit)
4693 (let (s e)
4694 (setq s (text-property-any (point) (or limit (point-max))
4695 'org-cwidth t))
4696 (when s
4697 (setq e (next-single-property-change s 'org-cwidth))
4698 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4699 (goto-char e)
4700 t)))
4702 (defvar org-latex-and-specials-regexp nil
4703 "Regular expression for highlighting export special stuff.")
4704 (defvar org-match-substring-regexp)
4705 (defvar org-match-substring-with-braces-regexp)
4707 ;; This should be with the exporter code, but we also use if for font-locking
4708 (defconst org-export-html-special-string-regexps
4709 '(("\\\\-" . "&shy;")
4710 ("---\\([^-]\\)" . "&mdash;\\1")
4711 ("--\\([^-]\\)" . "&ndash;\\1")
4712 ("\\.\\.\\." . "&hellip;"))
4713 "Regular expressions for special string conversion.")
4716 (defun org-compute-latex-and-specials-regexp ()
4717 "Compute regular expression for stuff treated specially by exporters."
4718 (if (not org-highlight-latex-fragments-and-specials)
4719 (org-set-local 'org-latex-and-specials-regexp nil)
4720 (require 'org-exp)
4721 (let*
4722 ((matchers (plist-get org-format-latex-options :matchers))
4723 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4724 org-latex-regexps)))
4725 (options (org-combine-plists (org-default-export-plist)
4726 (org-infile-export-plist)))
4727 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4728 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4729 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4730 (org-export-html-expand (plist-get options :expand-quoted-html))
4731 (org-export-with-special-strings (plist-get options :special-strings))
4732 (re-sub
4733 (cond
4734 ((equal org-export-with-sub-superscripts '{})
4735 (list org-match-substring-with-braces-regexp))
4736 (org-export-with-sub-superscripts
4737 (list org-match-substring-regexp))
4738 (t nil)))
4739 (re-latex
4740 (if org-export-with-LaTeX-fragments
4741 (mapcar (lambda (x) (nth 1 x)) latexs)))
4742 (re-macros
4743 (if org-export-with-TeX-macros
4744 (list (concat "\\\\"
4745 (regexp-opt
4746 (append (mapcar 'car org-html-entities)
4747 (if (boundp 'org-latex-entities)
4748 (mapcar (lambda (x)
4749 (or (car-safe x) x))
4750 org-latex-entities)
4751 nil))
4752 'words))) ; FIXME
4754 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4755 (re-special (if org-export-with-special-strings
4756 (mapcar (lambda (x) (car x))
4757 org-export-html-special-string-regexps)))
4758 (re-rest
4759 (delq nil
4760 (list
4761 (if org-export-html-expand "@<[^>\n]+>")
4762 ))))
4763 (org-set-local
4764 'org-latex-and-specials-regexp
4765 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4766 re-rest) "\\|")))))
4768 (defun org-do-latex-and-special-faces (limit)
4769 "Run through the buffer and add overlays to links."
4770 (when org-latex-and-specials-regexp
4771 (let (rtn d)
4772 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4773 limit t))
4774 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4775 'face))
4776 '(org-code org-verbatim underline)))
4777 (progn
4778 (setq rtn t
4779 d (cond ((member (char-after (1+ (match-beginning 0)))
4780 '(?_ ?^)) 1)
4781 (t 0)))
4782 (font-lock-prepend-text-property
4783 (+ d (match-beginning 0)) (match-end 0)
4784 'face 'org-latex-and-export-specials)
4785 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4786 '(font-lock-multiline t)))))
4787 rtn)))
4789 (defun org-restart-font-lock ()
4790 "Restart font-lock-mode, to force refontification."
4791 (when (and (boundp 'font-lock-mode) font-lock-mode)
4792 (font-lock-mode -1)
4793 (font-lock-mode 1)))
4795 (defun org-all-targets (&optional radio)
4796 "Return a list of all targets in this file.
4797 With optional argument RADIO, only find radio targets."
4798 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4799 rtn)
4800 (save-excursion
4801 (goto-char (point-min))
4802 (while (re-search-forward re nil t)
4803 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4804 rtn)))
4806 (defun org-make-target-link-regexp (targets)
4807 "Make regular expression matching all strings in TARGETS.
4808 The regular expression finds the targets also if there is a line break
4809 between words."
4810 (and targets
4811 (concat
4812 "\\<\\("
4813 (mapconcat
4814 (lambda (x)
4815 (while (string-match " +" x)
4816 (setq x (replace-match "\\s-+" t t x)))
4818 targets
4819 "\\|")
4820 "\\)\\>")))
4822 (defun org-activate-tags (limit)
4823 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4824 (progn
4825 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4826 (add-text-properties (match-beginning 1) (match-end 1)
4827 (list 'mouse-face 'highlight
4828 'keymap org-mouse-map))
4829 (org-rear-nonsticky-at (match-end 1))
4830 t)))
4832 (defun org-outline-level ()
4833 "Compute the outline level of the heading at point.
4834 This function assumes that the cursor is at the beginning of a line matched
4835 by outline-regexp. Otherwise it returns garbage.
4836 If this is called at a normal headline, the level is the number of stars.
4837 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4838 For plain list items, if they are matched by `outline-regexp', this returns
4839 1000 plus the line indentation."
4840 (save-excursion
4841 (looking-at outline-regexp)
4842 (if (match-beginning 1)
4843 (+ (org-get-string-indentation (match-string 1)) 1000)
4844 (1- (- (match-end 0) (match-beginning 0))))))
4846 (defvar org-font-lock-keywords nil)
4848 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4849 "Regular expression matching a property line.")
4851 (defvar org-font-lock-hook nil
4852 "Functions to be called for special font lock stuff.")
4854 (defun org-font-lock-hook (limit)
4855 (run-hook-with-args 'org-font-lock-hook limit))
4857 (defun org-set-font-lock-defaults ()
4858 (let* ((em org-fontify-emphasized-text)
4859 (lk org-activate-links)
4860 (org-font-lock-extra-keywords
4861 (list
4862 ;; Call the hook
4863 '(org-font-lock-hook)
4864 ;; Headlines
4865 `(,(if org-fontify-whole-heading-line
4866 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4867 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4868 (1 (org-get-level-face 1))
4869 (2 (org-get-level-face 2))
4870 (3 (org-get-level-face 3)))
4871 ;; Table lines
4872 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4873 (1 'org-table t))
4874 ;; Table internals
4875 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4876 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4877 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4878 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4879 ;; Drawers
4880 (list org-drawer-regexp '(0 'org-special-keyword t))
4881 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4882 ;; Properties
4883 (list org-property-re
4884 '(1 'org-special-keyword t)
4885 '(3 'org-property-value t))
4886 ;; Links
4887 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4888 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4889 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4890 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4891 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4892 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4893 (if (memq 'footnote lk) '(org-activate-footnote-links
4894 (2 'org-footnote t)))
4895 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4896 '(org-hide-wide-columns (0 nil append))
4897 ;; TODO lines
4898 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4899 '(1 (org-get-todo-face 1) t))
4900 ;; DONE
4901 (if org-fontify-done-headline
4902 (list (concat "^[*]+ +\\<\\("
4903 (mapconcat 'regexp-quote org-done-keywords "\\|")
4904 "\\)\\(.*\\)")
4905 '(2 'org-headline-done t))
4906 nil)
4907 ;; Priorities
4908 '(org-font-lock-add-priority-faces)
4909 ;; Tags
4910 '(org-font-lock-add-tag-faces)
4911 ;; Special keywords
4912 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4913 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4914 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4915 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4916 ;; Emphasis
4917 (if em
4918 (if (featurep 'xemacs)
4919 '(org-do-emphasis-faces (0 nil append))
4920 '(org-do-emphasis-faces)))
4921 ;; Checkboxes
4922 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4923 2 'org-checkbox prepend)
4924 (if org-provide-checkbox-statistics
4925 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4926 (0 (org-get-checkbox-statistics-face) t)))
4927 ;; Description list items
4928 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4929 2 'bold prepend)
4930 ;; ARCHIVEd headings
4931 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4932 '(1 'org-archived prepend))
4933 ;; Specials
4934 '(org-do-latex-and-special-faces)
4935 ;; Code
4936 '(org-activate-code (1 'org-code t))
4937 ;; COMMENT
4938 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4939 "\\|" org-quote-string "\\)\\>")
4940 '(1 'org-special-keyword t))
4941 '("^#.*" (0 'font-lock-comment-face t))
4942 ;; Blocks and meta lines
4943 '(org-fontify-meta-lines-and-blocks)
4945 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4946 ;; Now set the full font-lock-keywords
4947 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4948 (org-set-local 'font-lock-defaults
4949 '(org-font-lock-keywords t nil nil backward-paragraph))
4950 (kill-local-variable 'font-lock-keywords) nil))
4952 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4953 "Fontify string S like in Org-mode"
4954 (with-temp-buffer
4955 (insert s)
4956 (let ((org-odd-levels-only odd-levels))
4957 (org-mode)
4958 (font-lock-fontify-buffer)
4959 (buffer-string))))
4961 (defvar org-m nil)
4962 (defvar org-l nil)
4963 (defvar org-f nil)
4964 (defun org-get-level-face (n)
4965 "Get the right face for match N in font-lock matching of headlines."
4966 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4967 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4968 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4969 (cond
4970 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4971 ((eq n 2) org-f)
4972 (t (if org-level-color-stars-only nil org-f))))
4974 (defun org-get-todo-face (kwd)
4975 "Get the right face for a TODO keyword KWD.
4976 If KWD is a number, get the corresponding match group."
4977 (if (numberp kwd) (setq kwd (match-string kwd)))
4978 (or (cdr (assoc kwd org-todo-keyword-faces))
4979 (and (member kwd org-done-keywords) 'org-done)
4980 'org-todo))
4982 (defun org-font-lock-add-tag-faces (limit)
4983 "Add the special tag faces."
4984 (when (and org-tag-faces org-tags-special-faces-re)
4985 (while (re-search-forward org-tags-special-faces-re limit t)
4986 (add-text-properties (match-beginning 1) (match-end 1)
4987 (list 'face (org-get-tag-face 1)
4988 'font-lock-fontified t))
4989 (backward-char 1))))
4991 (defun org-font-lock-add-priority-faces (limit)
4992 "Add the special priority faces."
4993 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4994 (add-text-properties
4995 (match-beginning 0) (match-end 0)
4996 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4997 org-priority-faces))
4998 'org-special-keyword)
4999 'font-lock-fontified t))))
5001 (defun org-get-tag-face (kwd)
5002 "Get the right face for a TODO keyword KWD.
5003 If KWD is a number, get the corresponding match group."
5004 (if (numberp kwd) (setq kwd (match-string kwd)))
5005 (or (cdr (assoc kwd org-tag-faces))
5006 'org-tag))
5008 (defun org-unfontify-region (beg end &optional maybe_loudly)
5009 "Remove fontification and activation overlays from links."
5010 (font-lock-default-unfontify-region beg end)
5011 (let* ((buffer-undo-list t)
5012 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5013 (inhibit-modification-hooks t)
5014 deactivate-mark buffer-file-name buffer-file-truename)
5015 (remove-text-properties
5016 beg end
5017 (if org-indent-mode
5018 ;; also remove line-prefix and wrap-prefix properties
5019 '(mouse-face t keymap t org-linked-text t
5020 invisible t intangible t
5021 line-prefix t wrap-prefix t
5022 org-no-flyspell t)
5023 '(mouse-face t keymap t org-linked-text t
5024 invisible t intangible t
5025 org-no-flyspell t)))))
5027 ;;;; Visibility cycling, including org-goto and indirect buffer
5029 ;;; Cycling
5031 (defvar org-cycle-global-status nil)
5032 (make-variable-buffer-local 'org-cycle-global-status)
5033 (defvar org-cycle-subtree-status nil)
5034 (make-variable-buffer-local 'org-cycle-subtree-status)
5036 ;;;###autoload
5038 (defvar org-inlinetask-min-level)
5040 (defun org-cycle (&optional arg)
5041 "TAB-action and visibility cycling for Org-mode.
5043 This is the command invoked in Org-mode by the TAB key. Its main purpose
5044 is outline visibility cycling, but it also invokes other actions
5045 in special contexts.
5047 - When this function is called with a prefix argument, rotate the entire
5048 buffer through 3 states (global cycling)
5049 1. OVERVIEW: Show only top-level headlines.
5050 2. CONTENTS: Show all headlines of all levels, but no body text.
5051 3. SHOW ALL: Show everything.
5052 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5053 determined by the variable `org-startup-folded', and by any VISIBILITY
5054 properties in the buffer.
5055 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5056 including any drawers.
5058 - When inside a table, re-align the table and move to the next field.
5060 - When point is at the beginning of a headline, rotate the subtree started
5061 by this line through 3 different states (local cycling)
5062 1. FOLDED: Only the main headline is shown.
5063 2. CHILDREN: The main headline and the direct children are shown.
5064 From this state, you can move to one of the children
5065 and zoom in further.
5066 3. SUBTREE: Show the entire subtree, including body text.
5067 If there is no subtree, switch directly from CHILDREN to FOLDED.
5069 - When there is a numeric prefix, go up to a heading with level ARG, do
5070 a `show-subtree' and return to the previous cursor position. If ARG
5071 is negative, go up that many levels.
5073 - When point is not at the beginning of a headline, execute the global
5074 binding for TAB, which is re-indenting the line. See the option
5075 `org-cycle-emulate-tab' for details.
5077 - Special case: if point is at the beginning of the buffer and there is
5078 no headline in line 1, this function will act as if called with prefix arg.
5079 But only if also the variable `org-cycle-global-at-bob' is t."
5080 (interactive "P")
5081 (org-load-modules-maybe)
5082 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5083 (and org-cycle-level-after-item/entry-creation
5084 (or (org-cycle-level)
5085 (org-cycle-item-indentation))))
5086 (let* ((limit-level
5087 (or org-cycle-max-level
5088 (and (boundp 'org-inlinetask-min-level)
5089 org-inlinetask-min-level
5090 (1- org-inlinetask-min-level))))
5091 (nstars (and limit-level
5092 (if org-odd-levels-only
5093 (and limit-level (1- (* limit-level 2)))
5094 limit-level)))
5095 (outline-regexp
5096 (cond
5097 ((not (org-mode-p)) outline-regexp)
5098 ((or (eq org-cycle-include-plain-lists 'integrate)
5099 (and org-cycle-include-plain-lists (org-at-item-p)))
5100 (concat "\\(?:\\*"
5101 (if nstars (format "\\{1,%d\\}" nstars) "+")
5102 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5103 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5104 (bob-special (and org-cycle-global-at-bob (bobp)
5105 (not (looking-at outline-regexp))))
5106 (org-cycle-hook
5107 (if bob-special
5108 (delq 'org-optimize-window-after-visibility-change
5109 (copy-sequence org-cycle-hook))
5110 org-cycle-hook))
5111 (pos (point)))
5113 (if (or bob-special (equal arg '(4)))
5114 ;; special case: use global cycling
5115 (setq arg t))
5117 (cond
5119 ((equal arg '(16))
5120 (org-set-startup-visibility)
5121 (message "Startup visibility, plus VISIBILITY properties"))
5123 ((equal arg '(64))
5124 (show-all)
5125 (message "Entire buffer visible, including drawers"))
5127 ((org-at-table-p 'any)
5128 ;; Enter the table or move to the next field in the table
5129 (or (org-table-recognize-table.el)
5130 (progn
5131 (if arg (org-table-edit-field t)
5132 (org-table-justify-field-maybe)
5133 (call-interactively 'org-table-next-field)))))
5135 ((run-hook-with-args-until-success
5136 'org-tab-after-check-for-table-hook))
5138 ((eq arg t) ;; Global cycling
5139 (org-cycle-internal-global))
5141 ((and org-drawers org-drawer-regexp
5142 (save-excursion
5143 (beginning-of-line 1)
5144 (looking-at org-drawer-regexp)))
5145 ;; Toggle block visibility
5146 (org-flag-drawer
5147 (not (get-char-property (match-end 0) 'invisible))))
5149 ((integerp arg)
5150 ;; Show-subtree, ARG levels up from here.
5151 (save-excursion
5152 (org-back-to-heading)
5153 (outline-up-heading (if (< arg 0) (- arg)
5154 (- (funcall outline-level) arg)))
5155 (org-show-subtree)))
5157 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5158 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5160 (org-cycle-internal-local))
5162 ;; TAB emulation and template completion
5163 (buffer-read-only (org-back-to-heading))
5165 ((run-hook-with-args-until-success
5166 'org-tab-after-check-for-cycling-hook))
5168 ((org-try-structure-completion))
5170 ((org-try-cdlatex-tab))
5172 ((run-hook-with-args-until-success
5173 'org-tab-before-tab-emulation-hook))
5175 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5176 (or (not (bolp))
5177 (not (looking-at outline-regexp))))
5178 (call-interactively (global-key-binding "\t")))
5180 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5181 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5182 (or (and (eq org-cycle-emulate-tab 'white)
5183 (= (match-end 0) (point-at-eol)))
5184 (and (eq org-cycle-emulate-tab 'whitestart)
5185 (>= (match-end 0) pos))))
5187 (eq org-cycle-emulate-tab t))
5188 (call-interactively (global-key-binding "\t")))
5190 (t (save-excursion
5191 (org-back-to-heading)
5192 (org-cycle)))))))
5194 (defun org-cycle-internal-global ()
5195 "Do the global cycling action."
5196 (cond
5197 ((and (eq last-command this-command)
5198 (eq org-cycle-global-status 'overview))
5199 ;; We just created the overview - now do table of contents
5200 ;; This can be slow in very large buffers, so indicate action
5201 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5202 (message "CONTENTS...")
5203 (org-content)
5204 (message "CONTENTS...done")
5205 (setq org-cycle-global-status 'contents)
5206 (run-hook-with-args 'org-cycle-hook 'contents))
5208 ((and (eq last-command this-command)
5209 (eq org-cycle-global-status 'contents))
5210 ;; We just showed the table of contents - now show everything
5211 (run-hook-with-args 'org-pre-cycle-hook 'all)
5212 (show-all)
5213 (message "SHOW ALL")
5214 (setq org-cycle-global-status 'all)
5215 (run-hook-with-args 'org-cycle-hook 'all))
5218 ;; Default action: go to overview
5219 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5220 (org-overview)
5221 (message "OVERVIEW")
5222 (setq org-cycle-global-status 'overview)
5223 (run-hook-with-args 'org-cycle-hook 'overview))))
5225 (defun org-cycle-internal-local ()
5226 "Do the local cycling action."
5227 (org-back-to-heading)
5228 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5229 ;; First, some boundaries
5230 (save-excursion
5231 (org-back-to-heading)
5232 (setq level (funcall outline-level))
5233 (save-excursion
5234 (beginning-of-line 2)
5235 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5236 ; XEmacs does not have `next-single-char-property-change'
5237 ; I'm not sure about Emacs 21.
5238 (while (and (not (eobp)) ;; this is like `next-line'
5239 (get-char-property (1- (point)) 'invisible))
5240 (beginning-of-line 2))
5241 (while (and (not (eobp)) ;; this is like `next-line'
5242 (get-char-property (1- (point)) 'invisible))
5243 (goto-char (next-single-char-property-change (point) 'invisible))
5244 ;;;??? (or (bolp) (beginning-of-line 2))))
5245 (and (eolp) (beginning-of-line 2))))
5246 (setq eol (point)))
5247 (outline-end-of-heading) (setq eoh (point))
5248 (save-excursion
5249 (outline-next-heading)
5250 (setq has-children (and (org-at-heading-p t)
5251 (> (funcall outline-level) level))))
5252 (org-end-of-subtree t)
5253 (unless (eobp)
5254 (skip-chars-forward " \t\n")
5255 (beginning-of-line 1) ; in case this is an item
5257 (setq eos (if (eobp) (point) (1- (point)))))
5258 ;; Find out what to do next and set `this-command'
5259 (cond
5260 ((= eos eoh)
5261 ;; Nothing is hidden behind this heading
5262 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5263 (message "EMPTY ENTRY")
5264 (setq org-cycle-subtree-status nil)
5265 (save-excursion
5266 (goto-char eos)
5267 (outline-next-heading)
5268 (if (org-invisible-p) (org-flag-heading nil))))
5269 ((and (or (>= eol eos)
5270 (not (string-match "\\S-" (buffer-substring eol eos))))
5271 (or has-children
5272 (not (setq children-skipped
5273 org-cycle-skip-children-state-if-no-children))))
5274 ;; Entire subtree is hidden in one line: children view
5275 (run-hook-with-args 'org-pre-cycle-hook 'children)
5276 (org-show-entry)
5277 (show-children)
5278 (message "CHILDREN")
5279 (save-excursion
5280 (goto-char eos)
5281 (outline-next-heading)
5282 (if (org-invisible-p) (org-flag-heading nil)))
5283 (setq org-cycle-subtree-status 'children)
5284 (run-hook-with-args 'org-cycle-hook 'children))
5285 ((or children-skipped
5286 (and (eq last-command this-command)
5287 (eq org-cycle-subtree-status 'children)))
5288 ;; We just showed the children, or no children are there,
5289 ;; now show everything.
5290 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5291 (org-show-subtree)
5292 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5293 (setq org-cycle-subtree-status 'subtree)
5294 (run-hook-with-args 'org-cycle-hook 'subtree))
5296 ;; Default action: hide the subtree.
5297 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5298 (hide-subtree)
5299 (message "FOLDED")
5300 (setq org-cycle-subtree-status 'folded)
5301 (run-hook-with-args 'org-cycle-hook 'folded)))))
5303 ;;;###autoload
5304 (defun org-global-cycle (&optional arg)
5305 "Cycle the global visibility. For details see `org-cycle'.
5306 With C-u prefix arg, switch to startup visibility.
5307 With a numeric prefix, show all headlines up to that level."
5308 (interactive "P")
5309 (let ((org-cycle-include-plain-lists
5310 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5311 (cond
5312 ((integerp arg)
5313 (show-all)
5314 (hide-sublevels arg)
5315 (setq org-cycle-global-status 'contents))
5316 ((equal arg '(4))
5317 (org-set-startup-visibility)
5318 (message "Startup visibility, plus VISIBILITY properties."))
5320 (org-cycle '(4))))))
5322 (defun org-set-startup-visibility ()
5323 "Set the visibility required by startup options and properties."
5324 (cond
5325 ((eq org-startup-folded t)
5326 (org-cycle '(4)))
5327 ((eq org-startup-folded 'content)
5328 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5329 (org-cycle '(4)) (org-cycle '(4)))))
5330 (unless (eq org-startup-folded 'showeverything)
5331 (if org-hide-block-startup (org-hide-block-all))
5332 (org-set-visibility-according-to-property 'no-cleanup)
5333 (org-cycle-hide-archived-subtrees 'all)
5334 (org-cycle-hide-drawers 'all)
5335 (org-cycle-show-empty-lines 'all)))
5337 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5338 "Switch subtree visibilities according to :VISIBILITY: property."
5339 (interactive)
5340 (let (org-show-entry-below state)
5341 (save-excursion
5342 (goto-char (point-min))
5343 (while (re-search-forward
5344 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5345 nil t)
5346 (setq state (match-string 1))
5347 (save-excursion
5348 (org-back-to-heading t)
5349 (hide-subtree)
5350 (org-reveal)
5351 (cond
5352 ((equal state '("fold" "folded"))
5353 (hide-subtree))
5354 ((equal state "children")
5355 (org-show-hidden-entry)
5356 (show-children))
5357 ((equal state "content")
5358 (save-excursion
5359 (save-restriction
5360 (org-narrow-to-subtree)
5361 (org-content))))
5362 ((member state '("all" "showall"))
5363 (show-subtree)))))
5364 (unless no-cleanup
5365 (org-cycle-hide-archived-subtrees 'all)
5366 (org-cycle-hide-drawers 'all)
5367 (org-cycle-show-empty-lines 'all)))))
5369 (defun org-overview ()
5370 "Switch to overview mode, showing only top-level headlines.
5371 Really, this shows all headlines with level equal or greater than the level
5372 of the first headline in the buffer. This is important, because if the
5373 first headline is not level one, then (hide-sublevels 1) gives confusing
5374 results."
5375 (interactive)
5376 (let ((level (save-excursion
5377 (goto-char (point-min))
5378 (if (re-search-forward (concat "^" outline-regexp) nil t)
5379 (progn
5380 (goto-char (match-beginning 0))
5381 (funcall outline-level))))))
5382 (and level (hide-sublevels level))))
5384 (defun org-content (&optional arg)
5385 "Show all headlines in the buffer, like a table of contents.
5386 With numerical argument N, show content up to level N."
5387 (interactive "P")
5388 (save-excursion
5389 ;; Visit all headings and show their offspring
5390 (and (integerp arg) (org-overview))
5391 (goto-char (point-max))
5392 (catch 'exit
5393 (while (and (progn (condition-case nil
5394 (outline-previous-visible-heading 1)
5395 (error (goto-char (point-min))))
5397 (looking-at outline-regexp))
5398 (if (integerp arg)
5399 (show-children (1- arg))
5400 (show-branches))
5401 (if (bobp) (throw 'exit nil))))))
5404 (defun org-optimize-window-after-visibility-change (state)
5405 "Adjust the window after a change in outline visibility.
5406 This function is the default value of the hook `org-cycle-hook'."
5407 (when (get-buffer-window (current-buffer))
5408 (cond
5409 ((eq state 'content) nil)
5410 ((eq state 'all) nil)
5411 ((eq state 'folded) nil)
5412 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5413 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5415 ;; FIXME: no longer in use
5416 (defun org-compact-display-after-subtree-move ()
5417 "Show a compacter version of the tree of the entry's parent."
5418 (save-excursion
5419 (if (org-up-heading-safe)
5420 (progn
5421 (hide-subtree)
5422 (show-entry)
5423 (show-children)
5424 (org-cycle-show-empty-lines 'children)
5425 (org-cycle-hide-drawers 'children))
5426 (org-overview))))
5428 (defun org-remove-empty-overlays-at (pos)
5429 "Remove outline overlays that do not contain non-white stuff."
5430 (mapc
5431 (lambda (o)
5432 (and (eq 'outline (org-overlay-get o 'invisible))
5433 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5434 (org-overlay-end o))))
5435 (org-delete-overlay o)))
5436 (org-overlays-at pos)))
5438 (defun org-clean-visibility-after-subtree-move ()
5439 "Fix visibility issues after moving a subtree."
5440 ;; First, find a reasonable region to look at:
5441 ;; Start two siblings above, end three below
5442 (let* ((beg (save-excursion
5443 (and (org-get-last-sibling)
5444 (org-get-last-sibling))
5445 (point)))
5446 (end (save-excursion
5447 (and (org-get-next-sibling)
5448 (org-get-next-sibling)
5449 (org-get-next-sibling))
5450 (if (org-at-heading-p)
5451 (point-at-eol)
5452 (point))))
5453 (level (looking-at "\\*+"))
5454 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5455 (save-excursion
5456 (save-restriction
5457 (narrow-to-region beg end)
5458 (when re
5459 ;; Properly fold already folded siblings
5460 (goto-char (point-min))
5461 (while (re-search-forward re nil t)
5462 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5463 (hide-entry))))
5464 (org-cycle-show-empty-lines 'overview)
5465 (org-cycle-hide-drawers 'overview)))))
5467 (defun org-cycle-show-empty-lines (state)
5468 "Show empty lines above all visible headlines.
5469 The region to be covered depends on STATE when called through
5470 `org-cycle-hook'. Lisp program can use t for STATE to get the
5471 entire buffer covered. Note that an empty line is only shown if there
5472 are at least `org-cycle-separator-lines' empty lines before the headline."
5473 (when (not (= org-cycle-separator-lines 0))
5474 (save-excursion
5475 (let* ((n (abs org-cycle-separator-lines))
5476 (re (cond
5477 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5478 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5479 (t (let ((ns (number-to-string (- n 2))))
5480 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5481 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5482 beg end b e)
5483 (cond
5484 ((memq state '(overview contents t))
5485 (setq beg (point-min) end (point-max)))
5486 ((memq state '(children folded))
5487 (setq beg (point) end (progn (org-end-of-subtree t t)
5488 (beginning-of-line 2)
5489 (point)))))
5490 (when beg
5491 (goto-char beg)
5492 (while (re-search-forward re end t)
5493 (unless (get-char-property (match-end 1) 'invisible)
5494 (setq e (match-end 1))
5495 (if (< org-cycle-separator-lines 0)
5496 (setq b (save-excursion
5497 (goto-char (match-beginning 0))
5498 (org-back-over-empty-lines)
5499 (if (save-excursion
5500 (goto-char (max (point-min) (1- (point))))
5501 (org-on-heading-p))
5502 (1- (point))
5503 (point))))
5504 (setq b (match-beginning 1)))
5505 (outline-flag-region b e nil)))))))
5506 ;; Never hide empty lines at the end of the file.
5507 (save-excursion
5508 (goto-char (point-max))
5509 (outline-previous-heading)
5510 (outline-end-of-heading)
5511 (if (and (looking-at "[ \t\n]+")
5512 (= (match-end 0) (point-max)))
5513 (outline-flag-region (point) (match-end 0) nil))))
5515 (defun org-show-empty-lines-in-parent ()
5516 "Move to the parent and re-show empty lines before visible headlines."
5517 (save-excursion
5518 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5519 (org-cycle-show-empty-lines context))))
5521 (defun org-files-list ()
5522 "Return `org-agenda-files' list, plus all open org-mode files.
5523 This is useful for operations that need to scan all of a user's
5524 open and agenda-wise Org files."
5525 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5526 (dolist (buf (buffer-list))
5527 (with-current-buffer buf
5528 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5529 (let ((file (expand-file-name (buffer-file-name))))
5530 (unless (member file files)
5531 (push file files))))))
5532 files))
5534 (defsubst org-entry-beginning-position ()
5535 "Return the beginning position of the current entry."
5536 (save-excursion (outline-back-to-heading t) (point)))
5538 (defsubst org-entry-end-position ()
5539 "Return the end position of the current entry."
5540 (save-excursion (outline-next-heading) (point)))
5542 (defun org-cycle-hide-drawers (state)
5543 "Re-hide all drawers after a visibility state change."
5544 (when (and (org-mode-p)
5545 (not (memq state '(overview folded contents))))
5546 (save-excursion
5547 (let* ((globalp (memq state '(contents all)))
5548 (beg (if globalp (point-min) (point)))
5549 (end (if globalp (point-max)
5550 (if (eq state 'children)
5551 (save-excursion (outline-next-heading) (point))
5552 (org-end-of-subtree t)))))
5553 (goto-char beg)
5554 (while (re-search-forward org-drawer-regexp end t)
5555 (org-flag-drawer t))))))
5557 (defun org-flag-drawer (flag)
5558 (save-excursion
5559 (beginning-of-line 1)
5560 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5561 (let ((b (match-end 0))
5562 (outline-regexp org-outline-regexp))
5563 (if (re-search-forward
5564 "^[ \t]*:END:"
5565 (save-excursion (outline-next-heading) (point)) t)
5566 (outline-flag-region b (point-at-eol) flag)
5567 (error ":END: line missing at position %s" b))))))
5569 (defun org-subtree-end-visible-p ()
5570 "Is the end of the current subtree visible?"
5571 (pos-visible-in-window-p
5572 (save-excursion (org-end-of-subtree t) (point))))
5574 (defun org-first-headline-recenter (&optional N)
5575 "Move cursor to the first headline and recenter the headline.
5576 Optional argument N means, put the headline into the Nth line of the window."
5577 (goto-char (point-min))
5578 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5579 (beginning-of-line)
5580 (recenter (prefix-numeric-value N))))
5582 ;;; Folding of blocks
5584 (defconst org-block-regexp
5586 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5587 "Regular expression for hiding blocks.")
5589 (defvar org-hide-block-overlays nil
5590 "Overlays hiding blocks.")
5591 (make-variable-buffer-local 'org-hide-block-overlays)
5593 (defun org-block-map (function &optional start end)
5594 "Call func at the head of all source blocks in the current
5595 buffer. Optional arguments START and END can be used to limit
5596 the range."
5597 (let ((start (or start (point-min)))
5598 (end (or end (point-max))))
5599 (save-excursion
5600 (goto-char start)
5601 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5602 (save-excursion
5603 (save-match-data
5604 (goto-char (match-beginning 0))
5605 (funcall function)))))))
5607 (defun org-hide-block-toggle-all ()
5608 "Toggle the visibility of all blocks in the current buffer."
5609 (org-block-map #'org-hide-block-toggle))
5611 (defun org-hide-block-all ()
5612 "Fold all blocks in the current buffer."
5613 (interactive)
5614 (org-show-block-all)
5615 (org-block-map #'org-hide-block-toggle-maybe))
5617 (defun org-show-block-all ()
5618 "Unfold all blocks in the current buffer."
5619 (mapc 'org-delete-overlay org-hide-block-overlays)
5620 (setq org-hide-block-overlays nil))
5622 (defun org-hide-block-toggle-maybe ()
5623 "Toggle visibility of block at point."
5624 (interactive)
5625 (let ((case-fold-search t))
5626 (if (save-excursion
5627 (beginning-of-line 1)
5628 (looking-at org-block-regexp))
5629 (progn (org-hide-block-toggle)
5630 t) ;; to signal that we took action
5631 nil))) ;; to signal that we did not
5633 (defun org-hide-block-toggle (&optional force)
5634 "Toggle the visibility of the current block."
5635 (interactive)
5636 (save-excursion
5637 (beginning-of-line)
5638 (if (re-search-forward org-block-regexp nil t)
5639 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5640 (end (match-end 0)) ;; end of entire body
5642 (if (memq t (mapcar (lambda (overlay)
5643 (eq (org-overlay-get overlay 'invisible)
5644 'org-hide-block))
5645 (org-overlays-at start)))
5646 (if (or (not force) (eq force 'off))
5647 (mapc (lambda (ov)
5648 (when (member ov org-hide-block-overlays)
5649 (setq org-hide-block-overlays
5650 (delq ov org-hide-block-overlays)))
5651 (when (eq (org-overlay-get ov 'invisible)
5652 'org-hide-block)
5653 (org-delete-overlay ov)))
5654 (org-overlays-at start)))
5655 (setq ov (org-make-overlay start end))
5656 (org-overlay-put ov 'invisible 'org-hide-block)
5657 ;; make the block accessible to isearch
5658 (org-overlay-put
5659 ov 'isearch-open-invisible
5660 (lambda (ov)
5661 (when (member ov org-hide-block-overlays)
5662 (setq org-hide-block-overlays
5663 (delq ov org-hide-block-overlays)))
5664 (when (eq (org-overlay-get ov 'invisible)
5665 'org-hide-block)
5666 (org-delete-overlay ov))))
5667 (push ov org-hide-block-overlays)))
5668 (error "Not looking at a source block"))))
5670 ;; org-tab-after-check-for-cycling-hook
5671 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5672 ;; Remove overlays when changing major mode
5673 (add-hook 'org-mode-hook
5674 (lambda () (org-add-hook 'change-major-mode-hook
5675 'org-show-block-all 'append 'local)))
5677 ;;; Org-goto
5679 (defvar org-goto-window-configuration nil)
5680 (defvar org-goto-marker nil)
5681 (defvar org-goto-map
5682 (let ((map (make-sparse-keymap)))
5683 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5684 (while (setq cmd (pop cmds))
5685 (substitute-key-definition cmd cmd map global-map)))
5686 (suppress-keymap map)
5687 (org-defkey map "\C-m" 'org-goto-ret)
5688 (org-defkey map [(return)] 'org-goto-ret)
5689 (org-defkey map [(left)] 'org-goto-left)
5690 (org-defkey map [(right)] 'org-goto-right)
5691 (org-defkey map [(control ?g)] 'org-goto-quit)
5692 (org-defkey map "\C-i" 'org-cycle)
5693 (org-defkey map [(tab)] 'org-cycle)
5694 (org-defkey map [(down)] 'outline-next-visible-heading)
5695 (org-defkey map [(up)] 'outline-previous-visible-heading)
5696 (if org-goto-auto-isearch
5697 (if (fboundp 'define-key-after)
5698 (define-key-after map [t] 'org-goto-local-auto-isearch)
5699 nil)
5700 (org-defkey map "q" 'org-goto-quit)
5701 (org-defkey map "n" 'outline-next-visible-heading)
5702 (org-defkey map "p" 'outline-previous-visible-heading)
5703 (org-defkey map "f" 'outline-forward-same-level)
5704 (org-defkey map "b" 'outline-backward-same-level)
5705 (org-defkey map "u" 'outline-up-heading))
5706 (org-defkey map "/" 'org-occur)
5707 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5708 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5709 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5710 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5711 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5712 map))
5714 (defconst org-goto-help
5715 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5716 RET=jump to location [Q]uit and return to previous location
5717 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5719 (defvar org-goto-start-pos) ; dynamically scoped parameter
5721 ;; FIXME: Docstring does not mention both interfaces
5722 (defun org-goto (&optional alternative-interface)
5723 "Look up a different location in the current file, keeping current visibility.
5725 When you want look-up or go to a different location in a document, the
5726 fastest way is often to fold the entire buffer and then dive into the tree.
5727 This method has the disadvantage, that the previous location will be folded,
5728 which may not be what you want.
5730 This command works around this by showing a copy of the current buffer
5731 in an indirect buffer, in overview mode. You can dive into the tree in
5732 that copy, use org-occur and incremental search to find a location.
5733 When pressing RET or `Q', the command returns to the original buffer in
5734 which the visibility is still unchanged. After RET is will also jump to
5735 the location selected in the indirect buffer and expose the
5736 the headline hierarchy above."
5737 (interactive "P")
5738 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5739 (org-refile-use-outline-path t)
5740 (org-refile-target-verify-function nil)
5741 (interface
5742 (if (not alternative-interface)
5743 org-goto-interface
5744 (if (eq org-goto-interface 'outline)
5745 'outline-path-completion
5746 'outline)))
5747 (org-goto-start-pos (point))
5748 (selected-point
5749 (if (eq interface 'outline)
5750 (car (org-get-location (current-buffer) org-goto-help))
5751 (nth 3 (org-refile-get-location "Goto: ")))))
5752 (if selected-point
5753 (progn
5754 (org-mark-ring-push org-goto-start-pos)
5755 (goto-char selected-point)
5756 (if (or (org-invisible-p) (org-invisible-p2))
5757 (org-show-context 'org-goto)))
5758 (message "Quit"))))
5760 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5761 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5762 (defvar org-goto-local-auto-isearch-map) ; defined below
5764 (defun org-get-location (buf help)
5765 "Let the user select a location in the Org-mode buffer BUF.
5766 This function uses a recursive edit. It returns the selected position
5767 or nil."
5768 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5769 (isearch-hide-immediately nil)
5770 (isearch-search-fun-function
5771 (lambda () 'org-goto-local-search-headings))
5772 (org-goto-selected-point org-goto-exit-command))
5773 (save-excursion
5774 (save-window-excursion
5775 (delete-other-windows)
5776 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5777 (switch-to-buffer
5778 (condition-case nil
5779 (make-indirect-buffer (current-buffer) "*org-goto*")
5780 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5781 (with-output-to-temp-buffer "*Help*"
5782 (princ help))
5783 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5784 (setq buffer-read-only nil)
5785 (let ((org-startup-truncated t)
5786 (org-startup-folded nil)
5787 (org-startup-align-all-tables nil))
5788 (org-mode)
5789 (org-overview))
5790 (setq buffer-read-only t)
5791 (if (and (boundp 'org-goto-start-pos)
5792 (integer-or-marker-p org-goto-start-pos))
5793 (let ((org-show-hierarchy-above t)
5794 (org-show-siblings t)
5795 (org-show-following-heading t))
5796 (goto-char org-goto-start-pos)
5797 (and (org-invisible-p) (org-show-context)))
5798 (goto-char (point-min)))
5799 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5800 (message "Select location and press RET")
5801 (use-local-map org-goto-map)
5802 (recursive-edit)
5804 (kill-buffer "*org-goto*")
5805 (cons org-goto-selected-point org-goto-exit-command)))
5807 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5808 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5809 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5810 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5812 (defun org-goto-local-search-headings (string bound noerror)
5813 "Search and make sure that any matches are in headlines."
5814 (catch 'return
5815 (while (if isearch-forward
5816 (search-forward string bound noerror)
5817 (search-backward string bound noerror))
5818 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5819 (and (member :headline context)
5820 (not (member :tags context))))
5821 (throw 'return (point))))))
5823 (defun org-goto-local-auto-isearch ()
5824 "Start isearch."
5825 (interactive)
5826 (goto-char (point-min))
5827 (let ((keys (this-command-keys)))
5828 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5829 (isearch-mode t)
5830 (isearch-process-search-char (string-to-char keys)))))
5832 (defun org-goto-ret (&optional arg)
5833 "Finish `org-goto' by going to the new location."
5834 (interactive "P")
5835 (setq org-goto-selected-point (point)
5836 org-goto-exit-command 'return)
5837 (throw 'exit nil))
5839 (defun org-goto-left ()
5840 "Finish `org-goto' by going to the new location."
5841 (interactive)
5842 (if (org-on-heading-p)
5843 (progn
5844 (beginning-of-line 1)
5845 (setq org-goto-selected-point (point)
5846 org-goto-exit-command 'left)
5847 (throw 'exit nil))
5848 (error "Not on a heading")))
5850 (defun org-goto-right ()
5851 "Finish `org-goto' by going to the new location."
5852 (interactive)
5853 (if (org-on-heading-p)
5854 (progn
5855 (setq org-goto-selected-point (point)
5856 org-goto-exit-command 'right)
5857 (throw 'exit nil))
5858 (error "Not on a heading")))
5860 (defun org-goto-quit ()
5861 "Finish `org-goto' without cursor motion."
5862 (interactive)
5863 (setq org-goto-selected-point nil)
5864 (setq org-goto-exit-command 'quit)
5865 (throw 'exit nil))
5867 ;;; Indirect buffer display of subtrees
5869 (defvar org-indirect-dedicated-frame nil
5870 "This is the frame being used for indirect tree display.")
5871 (defvar org-last-indirect-buffer nil)
5873 (defun org-tree-to-indirect-buffer (&optional arg)
5874 "Create indirect buffer and narrow it to current subtree.
5875 With numerical prefix ARG, go up to this level and then take that tree.
5876 If ARG is negative, go up that many levels.
5877 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5878 indirect buffer previously made with this command, to avoid proliferation of
5879 indirect buffers. However, when you call the command with a `C-u' prefix, or
5880 when `org-indirect-buffer-display' is `new-frame', the last buffer
5881 is kept so that you can work with several indirect buffers at the same time.
5882 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5883 requests that a new frame be made for the new buffer, so that the dedicated
5884 frame is not changed."
5885 (interactive "P")
5886 (let ((cbuf (current-buffer))
5887 (cwin (selected-window))
5888 (pos (point))
5889 beg end level heading ibuf)
5890 (save-excursion
5891 (org-back-to-heading t)
5892 (when (numberp arg)
5893 (setq level (org-outline-level))
5894 (if (< arg 0) (setq arg (+ level arg)))
5895 (while (> (setq level (org-outline-level)) arg)
5896 (outline-up-heading 1 t)))
5897 (setq beg (point)
5898 heading (org-get-heading))
5899 (org-end-of-subtree t t) (setq end (point)))
5900 (if (and (buffer-live-p org-last-indirect-buffer)
5901 (not (eq org-indirect-buffer-display 'new-frame))
5902 (not arg))
5903 (kill-buffer org-last-indirect-buffer))
5904 (setq ibuf (org-get-indirect-buffer cbuf)
5905 org-last-indirect-buffer ibuf)
5906 (cond
5907 ((or (eq org-indirect-buffer-display 'new-frame)
5908 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5909 (select-frame (make-frame))
5910 (delete-other-windows)
5911 (switch-to-buffer ibuf)
5912 (org-set-frame-title heading))
5913 ((eq org-indirect-buffer-display 'dedicated-frame)
5914 (raise-frame
5915 (select-frame (or (and org-indirect-dedicated-frame
5916 (frame-live-p org-indirect-dedicated-frame)
5917 org-indirect-dedicated-frame)
5918 (setq org-indirect-dedicated-frame (make-frame)))))
5919 (delete-other-windows)
5920 (switch-to-buffer ibuf)
5921 (org-set-frame-title (concat "Indirect: " heading)))
5922 ((eq org-indirect-buffer-display 'current-window)
5923 (switch-to-buffer ibuf))
5924 ((eq org-indirect-buffer-display 'other-window)
5925 (pop-to-buffer ibuf))
5926 (t (error "Invalid value")))
5927 (if (featurep 'xemacs)
5928 (save-excursion (org-mode) (turn-on-font-lock)))
5929 (narrow-to-region beg end)
5930 (show-all)
5931 (goto-char pos)
5932 (and (window-live-p cwin) (select-window cwin))))
5934 (defun org-get-indirect-buffer (&optional buffer)
5935 (setq buffer (or buffer (current-buffer)))
5936 (let ((n 1) (base (buffer-name buffer)) bname)
5937 (while (buffer-live-p
5938 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5939 (setq n (1+ n)))
5940 (condition-case nil
5941 (make-indirect-buffer buffer bname 'clone)
5942 (error (make-indirect-buffer buffer bname)))))
5944 (defun org-set-frame-title (title)
5945 "Set the title of the current frame to the string TITLE."
5946 ;; FIXME: how to name a single frame in XEmacs???
5947 (unless (featurep 'xemacs)
5948 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5950 ;;;; Structure editing
5952 ;;; Inserting headlines
5954 (defun org-previous-line-empty-p ()
5955 (save-excursion
5956 (and (not (bobp))
5957 (or (beginning-of-line 0) t)
5958 (save-match-data
5959 (looking-at "[ \t]*$")))))
5961 (defun org-insert-heading (&optional force-heading)
5962 "Insert a new heading or item with same depth at point.
5963 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5964 If point is at the beginning of a headline, insert a sibling before the
5965 current headline. If point is not at the beginning, do not split the line,
5966 but create the new headline after the current line."
5967 (interactive "P")
5968 (if (= (buffer-size) 0)
5969 (insert "\n* ")
5970 (when (or force-heading (not (org-insert-item)))
5971 (let* ((empty-line-p nil)
5972 (head (save-excursion
5973 (condition-case nil
5974 (progn
5975 (org-back-to-heading)
5976 (setq empty-line-p (org-previous-line-empty-p))
5977 (match-string 0))
5978 (error "*"))))
5979 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5980 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5981 pos hide-previous previous-pos)
5982 (cond
5983 ((and (org-on-heading-p) (bolp)
5984 (or (bobp)
5985 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5986 ;; insert before the current line
5987 (open-line (if blank 2 1)))
5988 ((and (bolp)
5989 (not org-insert-heading-respect-content)
5990 (or (bobp)
5991 (save-excursion
5992 (backward-char 1) (not (org-invisible-p)))))
5993 ;; insert right here
5994 nil)
5996 ;; somewhere in the line
5997 (save-excursion
5998 (setq previous-pos (point-at-bol))
5999 (end-of-line)
6000 (setq hide-previous (org-invisible-p)))
6001 (and org-insert-heading-respect-content (org-show-subtree))
6002 (let ((split
6003 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6004 (save-excursion
6005 (let ((p (point)))
6006 (goto-char (point-at-bol))
6007 (and (looking-at org-complex-heading-regexp)
6008 (> p (match-beginning 4)))))))
6009 tags pos)
6010 (cond
6011 (org-insert-heading-respect-content
6012 (org-end-of-subtree nil t)
6013 (or (bolp) (newline))
6014 (or (org-previous-line-empty-p)
6015 (and blank (newline)))
6016 (open-line 1))
6017 ((org-on-heading-p)
6018 (when hide-previous
6019 (show-children)
6020 (org-show-entry))
6021 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6022 (setq tags (and (match-end 2) (match-string 2)))
6023 (and (match-end 1)
6024 (delete-region (match-beginning 1) (match-end 1)))
6025 (setq pos (point-at-bol))
6026 (or split (end-of-line 1))
6027 (delete-horizontal-space)
6028 (newline (if blank 2 1))
6029 (when tags
6030 (save-excursion
6031 (goto-char pos)
6032 (end-of-line 1)
6033 (insert " " tags)
6034 (org-set-tags nil 'align))))
6036 (or split (end-of-line 1))
6037 (newline (if blank 2 1)))))))
6038 (insert head) (just-one-space)
6039 (setq pos (point))
6040 (end-of-line 1)
6041 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6042 (when (and org-insert-heading-respect-content hide-previous)
6043 (save-excursion
6044 (goto-char previous-pos)
6045 (hide-subtree)))
6046 (run-hooks 'org-insert-heading-hook)))))
6048 (defun org-get-heading (&optional no-tags)
6049 "Return the heading of the current entry, without the stars."
6050 (save-excursion
6051 (org-back-to-heading t)
6052 (if (looking-at
6053 (if no-tags
6054 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6055 "\\*+[ \t]+\\([^\r\n]*\\)"))
6056 (match-string 1) "")))
6058 (defun org-heading-components ()
6059 "Return the components of the current heading.
6060 This is a list with the following elements:
6061 - the level as an integer
6062 - the reduced level, different if `org-odd-levels-only' is set.
6063 - the TODO keyword, or nil
6064 - the priority character, like ?A, or nil if no priority is given
6065 - the headline text itself, or the tags string if no headline text
6066 - the tags string, or nil."
6067 (save-excursion
6068 (org-back-to-heading t)
6069 (if (looking-at org-complex-heading-regexp)
6070 (list (length (match-string 1))
6071 (org-reduced-level (length (match-string 1)))
6072 (org-match-string-no-properties 2)
6073 (and (match-end 3) (aref (match-string 3) 2))
6074 (org-match-string-no-properties 4)
6075 (org-match-string-no-properties 5)))))
6077 (defun org-get-entry ()
6078 "Get the entry text, after heading, entire subtree."
6079 (save-excursion
6080 (org-back-to-heading t)
6081 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6083 (defun org-insert-heading-after-current ()
6084 "Insert a new heading with same level as current, after current subtree."
6085 (interactive)
6086 (org-back-to-heading)
6087 (org-insert-heading)
6088 (org-move-subtree-down)
6089 (end-of-line 1))
6091 (defun org-insert-heading-respect-content ()
6092 (interactive)
6093 (let ((org-insert-heading-respect-content t))
6094 (org-insert-heading t)))
6096 (defun org-insert-todo-heading-respect-content (&optional force-state)
6097 (interactive "P")
6098 (let ((org-insert-heading-respect-content t))
6099 (org-insert-todo-heading force-state t)))
6101 (defun org-insert-todo-heading (arg &optional force-heading)
6102 "Insert a new heading with the same level and TODO state as current heading.
6103 If the heading has no TODO state, or if the state is DONE, use the first
6104 state (TODO by default). Also with prefix arg, force first state."
6105 (interactive "P")
6106 (when (or force-heading (not (org-insert-item 'checkbox)))
6107 (org-insert-heading force-heading)
6108 (save-excursion
6109 (org-back-to-heading)
6110 (outline-previous-heading)
6111 (looking-at org-todo-line-regexp))
6112 (let*
6113 ((new-mark-x
6114 (if (or arg
6115 (not (match-beginning 2))
6116 (member (match-string 2) org-done-keywords))
6117 (car org-todo-keywords-1)
6118 (match-string 2)))
6119 (new-mark
6121 (run-hook-with-args-until-success
6122 'org-todo-get-default-hook new-mark-x nil)
6123 new-mark-x)))
6124 (beginning-of-line 1)
6125 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6126 (if org-treat-insert-todo-heading-as-state-change
6127 (org-todo new-mark)
6128 (insert new-mark " "))))
6129 (when org-provide-todo-statistics
6130 (org-update-parent-todo-statistics))))
6132 (defun org-insert-subheading (arg)
6133 "Insert a new subheading and demote it.
6134 Works for outline headings and for plain lists alike."
6135 (interactive "P")
6136 (org-insert-heading arg)
6137 (cond
6138 ((org-on-heading-p) (org-do-demote))
6139 ((org-at-item-p) (org-indent-item 1))))
6141 (defun org-insert-todo-subheading (arg)
6142 "Insert a new subheading with TODO keyword or checkbox and demote it.
6143 Works for outline headings and for plain lists alike."
6144 (interactive "P")
6145 (org-insert-todo-heading arg)
6146 (cond
6147 ((org-on-heading-p) (org-do-demote))
6148 ((org-at-item-p) (org-indent-item 1))))
6150 ;;; Promotion and Demotion
6152 (defvar org-after-demote-entry-hook nil
6153 "Hook run after an entry has been demoted.
6154 The cursor will be at the beginning of the entry.
6155 When a subtree is being demoted, the hook will be called for each node.")
6157 (defvar org-after-promote-entry-hook nil
6158 "Hook run after an entry has been promoted.
6159 The cursor will be at the beginning of the entry.
6160 When a subtree is being promoted, the hook will be called for each node.")
6162 (defun org-promote-subtree ()
6163 "Promote the entire subtree.
6164 See also `org-promote'."
6165 (interactive)
6166 (save-excursion
6167 (org-map-tree 'org-promote))
6168 (org-fix-position-after-promote))
6170 (defun org-demote-subtree ()
6171 "Demote the entire subtree. See `org-demote'.
6172 See also `org-promote'."
6173 (interactive)
6174 (save-excursion
6175 (org-map-tree 'org-demote))
6176 (org-fix-position-after-promote))
6179 (defun org-do-promote ()
6180 "Promote the current heading higher up the tree.
6181 If the region is active in `transient-mark-mode', promote all headings
6182 in the region."
6183 (interactive)
6184 (save-excursion
6185 (if (org-region-active-p)
6186 (org-map-region 'org-promote (region-beginning) (region-end))
6187 (org-promote)))
6188 (org-fix-position-after-promote))
6190 (defun org-do-demote ()
6191 "Demote the current heading lower down the tree.
6192 If the region is active in `transient-mark-mode', demote all headings
6193 in the region."
6194 (interactive)
6195 (save-excursion
6196 (if (org-region-active-p)
6197 (org-map-region 'org-demote (region-beginning) (region-end))
6198 (org-demote)))
6199 (org-fix-position-after-promote))
6201 (defun org-fix-position-after-promote ()
6202 "Make sure that after pro/demotion cursor position is right."
6203 (let ((pos (point)))
6204 (when (save-excursion
6205 (beginning-of-line 1)
6206 (looking-at org-todo-line-regexp)
6207 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6208 (cond ((eobp) (insert " "))
6209 ((eolp) (insert " "))
6210 ((equal (char-after) ?\ ) (forward-char 1))))))
6212 (defun org-current-level ()
6213 "Return the level of the current entry, or nil if before the first headline.
6214 The level is the number of stars at the beginning of the headline."
6215 (save-excursion
6216 (condition-case nil
6217 (progn
6218 (org-back-to-heading t)
6219 (funcall outline-level))
6220 (error nil))))
6222 (defun org-reduced-level (l)
6223 "Compute the effective level of a heading.
6224 This takes into account the setting of `org-odd-levels-only'."
6225 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6227 (defun org-get-valid-level (level &optional change)
6228 "Rectify a level change under the influence of `org-odd-levels-only'
6229 LEVEL is a current level, CHANGE is by how much the level should be
6230 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6231 even level numbers will become the next higher odd number."
6232 (if org-odd-levels-only
6233 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6234 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6235 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6236 (max 1 (+ level (or change 0)))))
6238 (if (boundp 'define-obsolete-function-alias)
6239 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6240 (define-obsolete-function-alias 'org-get-legal-level
6241 'org-get-valid-level)
6242 (define-obsolete-function-alias 'org-get-legal-level
6243 'org-get-valid-level "23.1")))
6245 (defun org-promote ()
6246 "Promote the current heading higher up the tree.
6247 If the region is active in `transient-mark-mode', promote all headings
6248 in the region."
6249 (org-back-to-heading t)
6250 (let* ((level (save-match-data (funcall outline-level)))
6251 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6252 (diff (abs (- level (length up-head) -1))))
6253 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6254 (replace-match up-head nil t)
6255 ;; Fixup tag positioning
6256 (and org-auto-align-tags (org-set-tags nil t))
6257 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6258 (run-hooks 'org-after-promote-entry-hook)))
6260 (defun org-demote ()
6261 "Demote the current heading lower down the tree.
6262 If the region is active in `transient-mark-mode', demote all headings
6263 in the region."
6264 (org-back-to-heading t)
6265 (let* ((level (save-match-data (funcall outline-level)))
6266 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6267 (diff (abs (- level (length down-head) -1))))
6268 (replace-match down-head nil t)
6269 ;; Fixup tag positioning
6270 (and org-auto-align-tags (org-set-tags nil t))
6271 (if org-adapt-indentation (org-fixup-indentation diff))
6272 (run-hooks 'org-after-demote-entry-hook)))
6274 (defvar org-tab-ind-state nil)
6276 (defun org-cycle-level ()
6277 (let ((org-adapt-indentation nil))
6278 (when (and (looking-at "[ \t]*$")
6279 (looking-back
6280 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6281 (setq this-command 'org-cycle-level)
6282 (if (eq last-command 'org-cycle-level)
6283 (condition-case nil
6284 (progn (org-do-promote)
6285 (if (equal org-tab-ind-state (org-current-level))
6286 (org-do-promote)))
6287 (error
6288 (progn
6289 (save-excursion
6290 (beginning-of-line 1)
6291 (and (looking-at "\\*+")
6292 (replace-match
6293 (make-string org-tab-ind-state ?*))))
6294 (setq this-command 'org-cycle))))
6295 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6296 (org-do-demote))
6297 t)))
6299 (defun org-map-tree (fun)
6300 "Call FUN for every heading underneath the current one."
6301 (org-back-to-heading)
6302 (let ((level (funcall outline-level)))
6303 (save-excursion
6304 (funcall fun)
6305 (while (and (progn
6306 (outline-next-heading)
6307 (> (funcall outline-level) level))
6308 (not (eobp)))
6309 (funcall fun)))))
6311 (defun org-map-region (fun beg end)
6312 "Call FUN for every heading between BEG and END."
6313 (let ((org-ignore-region t))
6314 (save-excursion
6315 (setq end (copy-marker end))
6316 (goto-char beg)
6317 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6318 (< (point) end))
6319 (funcall fun))
6320 (while (and (progn
6321 (outline-next-heading)
6322 (< (point) end))
6323 (not (eobp)))
6324 (funcall fun)))))
6326 (defun org-fixup-indentation (diff)
6327 "Change the indentation in the current entry by DIFF
6328 However, if any line in the current entry has no indentation, or if it
6329 would end up with no indentation after the change, nothing at all is done."
6330 (save-excursion
6331 (let ((end (save-excursion (outline-next-heading)
6332 (point-marker)))
6333 (prohibit (if (> diff 0)
6334 "^\\S-"
6335 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6336 col)
6337 (unless (save-excursion (end-of-line 1)
6338 (re-search-forward prohibit end t))
6339 (while (and (< (point) end)
6340 (re-search-forward "^[ \t]+" end t))
6341 (goto-char (match-end 0))
6342 (setq col (current-column))
6343 (if (< diff 0) (replace-match ""))
6344 (org-indent-to-column (+ diff col))))
6345 (move-marker end nil))))
6347 (defun org-convert-to-odd-levels ()
6348 "Convert an org-mode file with all levels allowed to one with odd levels.
6349 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6350 level 5 etc."
6351 (interactive)
6352 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6353 (let ((outline-regexp org-outline-regexp)
6354 (outline-level 'org-outline-level)
6355 (org-odd-levels-only nil) n)
6356 (save-excursion
6357 (goto-char (point-min))
6358 (while (re-search-forward "^\\*\\*+ " nil t)
6359 (setq n (- (length (match-string 0)) 2))
6360 (while (>= (setq n (1- n)) 0)
6361 (org-demote))
6362 (end-of-line 1))))))
6364 (defun org-convert-to-oddeven-levels ()
6365 "Convert an org-mode file with only odd levels to one with odd and even levels.
6366 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6367 section with an even level, conversion would destroy the structure of the file. An error
6368 is signaled in this case."
6369 (interactive)
6370 (goto-char (point-min))
6371 ;; First check if there are no even levels
6372 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6373 (org-show-context t)
6374 (error "Not all levels are odd in this file. Conversion not possible"))
6375 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6376 (let ((outline-regexp org-outline-regexp)
6377 (outline-level 'org-outline-level)
6378 (org-odd-levels-only nil) n)
6379 (save-excursion
6380 (goto-char (point-min))
6381 (while (re-search-forward "^\\*\\*+ " nil t)
6382 (setq n (/ (1- (length (match-string 0))) 2))
6383 (while (>= (setq n (1- n)) 0)
6384 (org-promote))
6385 (end-of-line 1))))))
6387 (defun org-tr-level (n)
6388 "Make N odd if required."
6389 (if org-odd-levels-only (1+ (/ n 2)) n))
6391 ;;; Vertical tree motion, cutting and pasting of subtrees
6393 (defun org-move-subtree-up (&optional arg)
6394 "Move the current subtree up past ARG headlines of the same level."
6395 (interactive "p")
6396 (org-move-subtree-down (- (prefix-numeric-value arg))))
6398 (defun org-move-subtree-down (&optional arg)
6399 "Move the current subtree down past ARG headlines of the same level."
6400 (interactive "p")
6401 (setq arg (prefix-numeric-value arg))
6402 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6403 'org-get-last-sibling))
6404 (ins-point (make-marker))
6405 (cnt (abs arg))
6406 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6407 ;; Select the tree
6408 (org-back-to-heading)
6409 (setq beg0 (point))
6410 (save-excursion
6411 (setq ne-beg (org-back-over-empty-lines))
6412 (setq beg (point)))
6413 (save-match-data
6414 (save-excursion (outline-end-of-heading)
6415 (setq folded (org-invisible-p)))
6416 (outline-end-of-subtree))
6417 (outline-next-heading)
6418 (setq ne-end (org-back-over-empty-lines))
6419 (setq end (point))
6420 (goto-char beg0)
6421 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6422 ;; include less whitespace
6423 (save-excursion
6424 (goto-char beg)
6425 (forward-line (- ne-beg ne-end))
6426 (setq beg (point))))
6427 ;; Find insertion point, with error handling
6428 (while (> cnt 0)
6429 (or (and (funcall movfunc) (looking-at outline-regexp))
6430 (progn (goto-char beg0)
6431 (error "Cannot move past superior level or buffer limit")))
6432 (setq cnt (1- cnt)))
6433 (if (> arg 0)
6434 ;; Moving forward - still need to move over subtree
6435 (progn (org-end-of-subtree t t)
6436 (save-excursion
6437 (org-back-over-empty-lines)
6438 (or (bolp) (newline)))))
6439 (setq ne-ins (org-back-over-empty-lines))
6440 (move-marker ins-point (point))
6441 (setq txt (buffer-substring beg end))
6442 (org-save-markers-in-region beg end)
6443 (delete-region beg end)
6444 (org-remove-empty-overlays-at beg)
6445 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6446 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6447 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6448 (let ((bbb (point)))
6449 (insert-before-markers txt)
6450 (org-reinstall-markers-in-region bbb)
6451 (move-marker ins-point bbb))
6452 (or (bolp) (insert "\n"))
6453 (setq ins-end (point))
6454 (goto-char ins-point)
6455 (org-skip-whitespace)
6456 (when (and (< arg 0)
6457 (org-first-sibling-p)
6458 (> ne-ins ne-beg))
6459 ;; Move whitespace back to beginning
6460 (save-excursion
6461 (goto-char ins-end)
6462 (let ((kill-whole-line t))
6463 (kill-line (- ne-ins ne-beg)) (point)))
6464 (insert (make-string (- ne-ins ne-beg) ?\n)))
6465 (move-marker ins-point nil)
6466 (if folded
6467 (hide-subtree)
6468 (org-show-entry)
6469 (show-children)
6470 (org-cycle-hide-drawers 'children))
6471 (org-clean-visibility-after-subtree-move)))
6473 (defvar org-subtree-clip ""
6474 "Clipboard for cut and paste of subtrees.
6475 This is actually only a copy of the kill, because we use the normal kill
6476 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6478 (defvar org-subtree-clip-folded nil
6479 "Was the last copied subtree folded?
6480 This is used to fold the tree back after pasting.")
6482 (defun org-cut-subtree (&optional n)
6483 "Cut the current subtree into the clipboard.
6484 With prefix arg N, cut this many sequential subtrees.
6485 This is a short-hand for marking the subtree and then cutting it."
6486 (interactive "p")
6487 (org-copy-subtree n 'cut))
6489 (defun org-copy-subtree (&optional n cut force-store-markers)
6490 "Cut the current subtree into the clipboard.
6491 With prefix arg N, cut this many sequential subtrees.
6492 This is a short-hand for marking the subtree and then copying it.
6493 If CUT is non-nil, actually cut the subtree.
6494 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6495 of some markers in the region, even if CUT is non-nil. This is
6496 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6497 (interactive "p")
6498 (let (beg end folded (beg0 (point)))
6499 (if (interactive-p)
6500 (org-back-to-heading nil) ; take what looks like a subtree
6501 (org-back-to-heading t)) ; take what is really there
6502 (org-back-over-empty-lines)
6503 (setq beg (point))
6504 (skip-chars-forward " \t\r\n")
6505 (save-match-data
6506 (save-excursion (outline-end-of-heading)
6507 (setq folded (org-invisible-p)))
6508 (condition-case nil
6509 (org-forward-same-level (1- n) t)
6510 (error nil))
6511 (org-end-of-subtree t t))
6512 (org-back-over-empty-lines)
6513 (setq end (point))
6514 (goto-char beg0)
6515 (when (> end beg)
6516 (setq org-subtree-clip-folded folded)
6517 (when (or cut force-store-markers)
6518 (org-save-markers-in-region beg end))
6519 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6520 (setq org-subtree-clip (current-kill 0))
6521 (message "%s: Subtree(s) with %d characters"
6522 (if cut "Cut" "Copied")
6523 (length org-subtree-clip)))))
6525 (defun org-paste-subtree (&optional level tree for-yank)
6526 "Paste the clipboard as a subtree, with modification of headline level.
6527 The entire subtree is promoted or demoted in order to match a new headline
6528 level.
6530 If the cursor is at the beginning of a headline, the same level as
6531 that headline is used to paste the tree
6533 If not, the new level is derived from the *visible* headings
6534 before and after the insertion point, and taken to be the inferior headline
6535 level of the two. So if the previous visible heading is level 3 and the
6536 next is level 4 (or vice versa), level 4 will be used for insertion.
6537 This makes sure that the subtree remains an independent subtree and does
6538 not swallow low level entries.
6540 You can also force a different level, either by using a numeric prefix
6541 argument, or by inserting the heading marker by hand. For example, if the
6542 cursor is after \"*****\", then the tree will be shifted to level 5.
6544 If optional TREE is given, use this text instead of the kill ring.
6546 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6547 move back over whitespace before inserting, and move point to the end of
6548 the inserted text when done."
6549 (interactive "P")
6550 (setq tree (or tree (and kill-ring (current-kill 0))))
6551 (unless (org-kill-is-subtree-p tree)
6552 (error "%s"
6553 (substitute-command-keys
6554 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6555 (let* ((visp (not (org-invisible-p)))
6556 (txt tree)
6557 (^re (concat "^\\(" outline-regexp "\\)"))
6558 (re (concat "\\(" outline-regexp "\\)"))
6559 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6561 (old-level (if (string-match ^re txt)
6562 (- (match-end 0) (match-beginning 0) 1)
6563 -1))
6564 (force-level (cond (level (prefix-numeric-value level))
6565 ((and (looking-at "[ \t]*$")
6566 (string-match
6567 ^re_ (buffer-substring
6568 (point-at-bol) (point))))
6569 (- (match-end 1) (match-beginning 1)))
6570 ((and (bolp)
6571 (looking-at org-outline-regexp))
6572 (- (match-end 0) (point) 1))
6573 (t nil)))
6574 (previous-level (save-excursion
6575 (condition-case nil
6576 (progn
6577 (outline-previous-visible-heading 1)
6578 (if (looking-at re)
6579 (- (match-end 0) (match-beginning 0) 1)
6581 (error 1))))
6582 (next-level (save-excursion
6583 (condition-case nil
6584 (progn
6585 (or (looking-at outline-regexp)
6586 (outline-next-visible-heading 1))
6587 (if (looking-at re)
6588 (- (match-end 0) (match-beginning 0) 1)
6590 (error 1))))
6591 (new-level (or force-level (max previous-level next-level)))
6592 (shift (if (or (= old-level -1)
6593 (= new-level -1)
6594 (= old-level new-level))
6596 (- new-level old-level)))
6597 (delta (if (> shift 0) -1 1))
6598 (func (if (> shift 0) 'org-demote 'org-promote))
6599 (org-odd-levels-only nil)
6600 beg end newend)
6601 ;; Remove the forced level indicator
6602 (if force-level
6603 (delete-region (point-at-bol) (point)))
6604 ;; Paste
6605 (beginning-of-line 1)
6606 (unless for-yank (org-back-over-empty-lines))
6607 (setq beg (point))
6608 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6609 (insert-before-markers txt)
6610 (unless (string-match "\n\\'" txt) (insert "\n"))
6611 (setq newend (point))
6612 (org-reinstall-markers-in-region beg)
6613 (setq end (point))
6614 (goto-char beg)
6615 (skip-chars-forward " \t\n\r")
6616 (setq beg (point))
6617 (if (and (org-invisible-p) visp)
6618 (save-excursion (outline-show-heading)))
6619 ;; Shift if necessary
6620 (unless (= shift 0)
6621 (save-restriction
6622 (narrow-to-region beg end)
6623 (while (not (= shift 0))
6624 (org-map-region func (point-min) (point-max))
6625 (setq shift (+ delta shift)))
6626 (goto-char (point-min))
6627 (setq newend (point-max))))
6628 (when (or (interactive-p) for-yank)
6629 (message "Clipboard pasted as level %d subtree" new-level))
6630 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6631 kill-ring
6632 (eq org-subtree-clip (current-kill 0))
6633 org-subtree-clip-folded)
6634 ;; The tree was folded before it was killed/copied
6635 (hide-subtree))
6636 (and for-yank (goto-char newend))))
6638 (defun org-kill-is-subtree-p (&optional txt)
6639 "Check if the current kill is an outline subtree, or a set of trees.
6640 Returns nil if kill does not start with a headline, or if the first
6641 headline level is not the largest headline level in the tree.
6642 So this will actually accept several entries of equal levels as well,
6643 which is OK for `org-paste-subtree'.
6644 If optional TXT is given, check this string instead of the current kill."
6645 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6646 (start-level (and kill
6647 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6648 org-outline-regexp "\\)")
6649 kill)
6650 (- (match-end 2) (match-beginning 2) 1)))
6651 (re (concat "^" org-outline-regexp))
6652 (start (1+ (or (match-beginning 2) -1))))
6653 (if (not start-level)
6654 (progn
6655 nil) ;; does not even start with a heading
6656 (catch 'exit
6657 (while (setq start (string-match re kill (1+ start)))
6658 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6659 (throw 'exit nil)))
6660 t))))
6662 (defvar org-markers-to-move nil
6663 "Markers that should be moved with a cut-and-paste operation.
6664 Those markers are stored together with their positions relative to
6665 the start of the region.")
6667 (defun org-save-markers-in-region (beg end)
6668 "Check markers in region.
6669 If these markers are between BEG and END, record their position relative
6670 to BEG, so that after moving the block of text, we can put the markers back
6671 into place.
6672 This function gets called just before an entry or tree gets cut from the
6673 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6674 called immediately, to move the markers with the entries."
6675 (setq org-markers-to-move nil)
6676 (when (featurep 'org-clock)
6677 (org-clock-save-markers-for-cut-and-paste beg end))
6678 (when (featurep 'org-agenda)
6679 (org-agenda-save-markers-for-cut-and-paste beg end)))
6681 (defun org-check-and-save-marker (marker beg end)
6682 "Check if MARKER is between BEG and END.
6683 If yes, remember the marker and the distance to BEG."
6684 (when (and (marker-buffer marker)
6685 (equal (marker-buffer marker) (current-buffer)))
6686 (if (and (>= marker beg) (< marker end))
6687 (push (cons marker (- marker beg)) org-markers-to-move))))
6689 (defun org-reinstall-markers-in-region (beg)
6690 "Move all remembered markers to their position relative to BEG."
6691 (mapc (lambda (x)
6692 (move-marker (car x) (+ beg (cdr x))))
6693 org-markers-to-move)
6694 (setq org-markers-to-move nil))
6696 (defun org-narrow-to-subtree ()
6697 "Narrow buffer to the current subtree."
6698 (interactive)
6699 (save-excursion
6700 (save-match-data
6701 (narrow-to-region
6702 (progn (org-back-to-heading t) (point))
6703 (progn (org-end-of-subtree t t) (point))))))
6705 (defun org-clone-subtree-with-time-shift (n &optional shift)
6706 "Clone the task (subtree) at point N times.
6707 The clones will be inserted as siblings.
6709 In interactive use, the user will be prompted for the number of clones
6710 to be produced, and for a time SHIFT, which may be a repeater as used
6711 in time stamps, for example `+3d'.
6713 When a valid repeater is given and the entry contains any time stamps,
6714 the clones will become a sequence in time, with time stamps in the
6715 subtree shifted for each clone produced. If SHIFT is nil or the
6716 empty string, time stamps will be left alone.
6718 If the original subtree did contain time stamps with a repeater,
6719 the following will happen:
6720 - the repeater will be removed in each clone
6721 - an additional clone will be produced, with the current, unshifted
6722 date(s) in the entry.
6723 - the original entry will be placed *after* all the clones, with
6724 repeater intact.
6725 - the start days in the repeater in the original entry will be shifted
6726 to past the last clone.
6727 I this way you can spell out a number of instances of a repeating task,
6728 and still retain the repeater to cover future instances of the task."
6729 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6730 (let (beg end template task
6731 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6732 (if (not (and (integerp n) (> n 0)))
6733 (error "Invalid number of replications %s" n))
6734 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6735 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6736 shift)))
6737 (error "Invalid shift specification %s" shift))
6738 (when doshift
6739 (setq shift-n (string-to-number (match-string 1 shift))
6740 shift-what (cdr (assoc (match-string 2 shift)
6741 '(("d" . day) ("w" . week)
6742 ("m" . month) ("y" . year))))))
6743 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6744 (setq nmin 1 nmax n)
6745 (org-back-to-heading t)
6746 (setq beg (point))
6747 (org-end-of-subtree t t)
6748 (or (bolp) (insert "\n"))
6749 (setq end (point))
6750 (setq template (buffer-substring beg end))
6751 (when (and doshift
6752 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6753 (delete-region beg end)
6754 (setq end beg)
6755 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6756 (goto-char end)
6757 (loop for n from nmin to nmax do
6758 (if (not doshift)
6759 (setq task template)
6760 (with-temp-buffer
6761 (insert template)
6762 (org-mode)
6763 (goto-char (point-min))
6764 (while (re-search-forward org-ts-regexp-both nil t)
6765 (org-timestamp-change (* n shift-n) shift-what))
6766 (unless (= n n-no-remove)
6767 (goto-char (point-min))
6768 (while (re-search-forward org-ts-regexp nil t)
6769 (save-excursion
6770 (goto-char (match-beginning 0))
6771 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6772 (delete-region (match-beginning 1) (match-end 1))))))
6773 (setq task (buffer-string))))
6774 (insert task))
6775 (goto-char beg)))
6777 ;;; Outline Sorting
6779 (defun org-sort (with-case)
6780 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6781 Optional argument WITH-CASE means sort case-sensitively.
6782 With a double prefix argument, also remove duplicate entries."
6783 (interactive "P")
6784 (if (org-at-table-p)
6785 (org-call-with-arg 'org-table-sort-lines with-case)
6786 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6788 (defun org-sort-remove-invisible (s)
6789 (remove-text-properties 0 (length s) org-rm-props s)
6790 (while (string-match org-bracket-link-regexp s)
6791 (setq s (replace-match (if (match-end 2)
6792 (match-string 3 s)
6793 (match-string 1 s)) t t s)))
6796 (defvar org-priority-regexp) ; defined later in the file
6798 (defvar org-after-sorting-entries-or-items-hook nil
6799 "Hook that is run after a bunch of entries or items have been sorted.
6800 When children are sorted, the cursor is in the parent line when this
6801 hook gets called. When a region or a plain list is sorted, the cursor
6802 will be in the first entry of the sorted region/list.")
6804 (defun org-sort-entries-or-items
6805 (&optional with-case sorting-type getkey-func compare-func property)
6806 "Sort entries on a certain level of an outline tree, or plain list items.
6807 If there is an active region, the entries in the region are sorted.
6808 Else, if the cursor is before the first entry, sort the top-level items.
6809 Else, the children of the entry at point are sorted.
6810 If the cursor is at the first item in a plain list, the list items will be
6811 sorted.
6813 Sorting can be alphabetically, numerically, by date/time as given by
6814 a time stamp, by a property or by priority.
6816 The command prompts for the sorting type unless it has been given to the
6817 function through the SORTING-TYPE argument, which needs to a character,
6818 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6819 precise meaning of each character:
6821 n Numerically, by converting the beginning of the entry/item to a number.
6822 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6823 t By date/time, either the first active time stamp in the entry, or, if
6824 none exist, by the first inactive one.
6825 In items, only the first line will be checked.
6826 s By the scheduled date/time.
6827 d By deadline date/time.
6828 c By creation time, which is assumed to be the first inactive time stamp
6829 at the beginning of a line.
6830 p By priority according to the cookie.
6831 r By the value of a property.
6833 Capital letters will reverse the sort order.
6835 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6836 called with point at the beginning of the record. It must return either
6837 a string or a number that should serve as the sorting key for that record.
6839 Comparing entries ignores case by default. However, with an optional argument
6840 WITH-CASE, the sorting considers case as well."
6841 (interactive "P")
6842 (let ((case-func (if with-case 'identity 'downcase))
6843 start beg end stars re re2
6844 txt what tmp plain-list-p)
6845 ;; Find beginning and end of region to sort
6846 (cond
6847 ((org-region-active-p)
6848 ;; we will sort the region
6849 (setq end (region-end)
6850 what "region")
6851 (goto-char (region-beginning))
6852 (if (not (org-on-heading-p)) (outline-next-heading))
6853 (setq start (point)))
6854 ((org-at-item-p)
6855 ;; we will sort this plain list
6856 (org-beginning-of-item-list) (setq start (point))
6857 (org-end-of-item-list) (setq end (point))
6858 (goto-char start)
6859 (setq plain-list-p t
6860 what "plain list"))
6861 ((or (org-on-heading-p)
6862 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6863 ;; we will sort the children of the current headline
6864 (org-back-to-heading)
6865 (setq start (point)
6866 end (progn (org-end-of-subtree t t)
6867 (org-back-over-empty-lines)
6868 (point))
6869 what "children")
6870 (goto-char start)
6871 (show-subtree)
6872 (outline-next-heading))
6874 ;; we will sort the top-level entries in this file
6875 (goto-char (point-min))
6876 (or (org-on-heading-p) (outline-next-heading))
6877 (setq start (point) end (point-max) what "top-level")
6878 (goto-char start)
6879 (show-all)))
6881 (setq beg (point))
6882 (if (>= beg end) (error "Nothing to sort"))
6884 (unless plain-list-p
6885 (looking-at "\\(\\*+\\)")
6886 (setq stars (match-string 1)
6887 re (concat "^" (regexp-quote stars) " +")
6888 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6889 txt (buffer-substring beg end))
6890 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6891 (if (and (not (equal stars "*")) (string-match re2 txt))
6892 (error "Region to sort contains a level above the first entry")))
6894 (unless sorting-type
6895 (message
6896 (if plain-list-p
6897 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6898 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6899 [t]ime [s]cheduled [d]eadline [c]reated
6900 A/N/T/S/D/C/P/O/F means reversed:")
6901 what)
6902 (setq sorting-type (read-char-exclusive))
6904 (and (= (downcase sorting-type) ?f)
6905 (setq getkey-func
6906 (org-icompleting-read "Sort using function: "
6907 obarray 'fboundp t nil nil))
6908 (setq getkey-func (intern getkey-func)))
6910 (and (= (downcase sorting-type) ?r)
6911 (setq property
6912 (org-icompleting-read "Property: "
6913 (mapcar 'list (org-buffer-property-keys t))
6914 nil t))))
6916 (message "Sorting entries...")
6918 (save-restriction
6919 (narrow-to-region start end)
6921 (let ((dcst (downcase sorting-type))
6922 (case-fold-search nil)
6923 (now (current-time)))
6924 (sort-subr
6925 (/= dcst sorting-type)
6926 ;; This function moves to the beginning character of the "record" to
6927 ;; be sorted.
6928 (if plain-list-p
6929 (lambda nil
6930 (if (org-at-item-p) t (goto-char (point-max))))
6931 (lambda nil
6932 (if (re-search-forward re nil t)
6933 (goto-char (match-beginning 0))
6934 (goto-char (point-max)))))
6935 ;; This function moves to the last character of the "record" being
6936 ;; sorted.
6937 (if plain-list-p
6938 'org-end-of-item
6939 (lambda nil
6940 (save-match-data
6941 (condition-case nil
6942 (outline-forward-same-level 1)
6943 (error
6944 (goto-char (point-max)))))))
6946 ;; This function returns the value that gets sorted against.
6947 (if plain-list-p
6948 (lambda nil
6949 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6950 (cond
6951 ((= dcst ?n)
6952 (string-to-number (buffer-substring (match-end 0)
6953 (point-at-eol))))
6954 ((= dcst ?a)
6955 (buffer-substring (match-end 0) (point-at-eol)))
6956 ((= dcst ?t)
6957 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6958 (re-search-forward org-ts-regexp-both
6959 (point-at-eol) t))
6960 (org-time-string-to-seconds (match-string 0))
6961 (org-float-time now)))
6962 ((= dcst ?f)
6963 (if getkey-func
6964 (progn
6965 (setq tmp (funcall getkey-func))
6966 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6967 tmp)
6968 (error "Invalid key function `%s'" getkey-func)))
6969 (t (error "Invalid sorting type `%c'" sorting-type)))))
6970 (lambda nil
6971 (cond
6972 ((= dcst ?n)
6973 (if (looking-at org-complex-heading-regexp)
6974 (string-to-number (match-string 4))
6975 nil))
6976 ((= dcst ?a)
6977 (if (looking-at org-complex-heading-regexp)
6978 (funcall case-func (match-string 4))
6979 nil))
6980 ((= dcst ?t)
6981 (let ((end (save-excursion (outline-next-heading) (point))))
6982 (if (or (re-search-forward org-ts-regexp end t)
6983 (re-search-forward org-ts-regexp-both end t))
6984 (org-time-string-to-seconds (match-string 0))
6985 (org-float-time now))))
6986 ((= dcst ?c)
6987 (let ((end (save-excursion (outline-next-heading) (point))))
6988 (if (re-search-forward
6989 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6990 end t)
6991 (org-time-string-to-seconds (match-string 0))
6992 (org-float-time now))))
6993 ((= dcst ?s)
6994 (let ((end (save-excursion (outline-next-heading) (point))))
6995 (if (re-search-forward org-scheduled-time-regexp end t)
6996 (org-time-string-to-seconds (match-string 1))
6997 (org-float-time now))))
6998 ((= dcst ?d)
6999 (let ((end (save-excursion (outline-next-heading) (point))))
7000 (if (re-search-forward org-deadline-time-regexp end t)
7001 (org-time-string-to-seconds (match-string 1))
7002 (org-float-time now))))
7003 ((= dcst ?p)
7004 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7005 (string-to-char (match-string 2))
7006 org-default-priority))
7007 ((= dcst ?r)
7008 (or (org-entry-get nil property) ""))
7009 ((= dcst ?o)
7010 (if (looking-at org-complex-heading-regexp)
7011 (- 9999 (length (member (match-string 2)
7012 org-todo-keywords-1)))))
7013 ((= dcst ?f)
7014 (if getkey-func
7015 (progn
7016 (setq tmp (funcall getkey-func))
7017 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7018 tmp)
7019 (error "Invalid key function `%s'" getkey-func)))
7020 (t (error "Invalid sorting type `%c'" sorting-type)))))
7022 (cond
7023 ((= dcst ?a) 'string<)
7024 ((= dcst ?f) compare-func)
7025 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7026 (t nil)))))
7027 (run-hooks 'org-after-sorting-entries-or-items-hook)
7028 (message "Sorting entries...done")))
7030 (defun org-do-sort (table what &optional with-case sorting-type)
7031 "Sort TABLE of WHAT according to SORTING-TYPE.
7032 The user will be prompted for the SORTING-TYPE if the call to this
7033 function does not specify it. WHAT is only for the prompt, to indicate
7034 what is being sorted. The sorting key will be extracted from
7035 the car of the elements of the table.
7036 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7037 (unless sorting-type
7038 (message
7039 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7040 what)
7041 (setq sorting-type (read-char-exclusive)))
7042 (let ((dcst (downcase sorting-type))
7043 extractfun comparefun)
7044 ;; Define the appropriate functions
7045 (cond
7046 ((= dcst ?n)
7047 (setq extractfun 'string-to-number
7048 comparefun (if (= dcst sorting-type) '< '>)))
7049 ((= dcst ?a)
7050 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7051 (lambda(x) (downcase (org-sort-remove-invisible x))))
7052 comparefun (if (= dcst sorting-type)
7053 'string<
7054 (lambda (a b) (and (not (string< a b))
7055 (not (string= a b)))))))
7056 ((= dcst ?t)
7057 (setq extractfun
7058 (lambda (x)
7059 (if (or (string-match org-ts-regexp x)
7060 (string-match org-ts-regexp-both x))
7061 (org-float-time
7062 (org-time-string-to-time (match-string 0 x)))
7064 comparefun (if (= dcst sorting-type) '< '>)))
7065 (t (error "Invalid sorting type `%c'" sorting-type)))
7067 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7068 table)
7069 (lambda (a b) (funcall comparefun (car a) (car b))))))
7072 ;;; The orgstruct minor mode
7074 ;; Define a minor mode which can be used in other modes in order to
7075 ;; integrate the org-mode structure editing commands.
7077 ;; This is really a hack, because the org-mode structure commands use
7078 ;; keys which normally belong to the major mode. Here is how it
7079 ;; works: The minor mode defines all the keys necessary to operate the
7080 ;; structure commands, but wraps the commands into a function which
7081 ;; tests if the cursor is currently at a headline or a plain list
7082 ;; item. If that is the case, the structure command is used,
7083 ;; temporarily setting many Org-mode variables like regular
7084 ;; expressions for filling etc. However, when any of those keys is
7085 ;; used at a different location, function uses `key-binding' to look
7086 ;; up if the key has an associated command in another currently active
7087 ;; keymap (minor modes, major mode, global), and executes that
7088 ;; command. There might be problems if any of the keys is otherwise
7089 ;; used as a prefix key.
7091 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7092 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7093 ;; addresses this by checking explicitly for both bindings.
7095 (defvar orgstruct-mode-map (make-sparse-keymap)
7096 "Keymap for the minor `orgstruct-mode'.")
7098 (defvar org-local-vars nil
7099 "List of local variables, for use by `orgstruct-mode'")
7101 ;;;###autoload
7102 (define-minor-mode orgstruct-mode
7103 "Toggle the minor more `orgstruct-mode'.
7104 This mode is for using Org-mode structure commands in other modes.
7105 The following key behave as if Org-mode was active, if the cursor
7106 is on a headline, or on a plain list item (both in the definition
7107 of Org-mode).
7109 M-up Move entry/item up
7110 M-down Move entry/item down
7111 M-left Promote
7112 M-right Demote
7113 M-S-up Move entry/item up
7114 M-S-down Move entry/item down
7115 M-S-left Promote subtree
7116 M-S-right Demote subtree
7117 M-q Fill paragraph and items like in Org-mode
7118 C-c ^ Sort entries
7119 C-c - Cycle list bullet
7120 TAB Cycle item visibility
7121 M-RET Insert new heading/item
7122 S-M-RET Insert new TODO heading / Checkbox item
7123 C-c C-c Set tags / toggle checkbox"
7124 nil " OrgStruct" nil
7125 (org-load-modules-maybe)
7126 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7128 ;;;###autoload
7129 (defun turn-on-orgstruct ()
7130 "Unconditionally turn on `orgstruct-mode'."
7131 (orgstruct-mode 1))
7133 (defun orgstruct++-mode (&optional arg)
7134 "Toggle `orgstruct-mode', the enhanced version of it.
7135 In addition to setting orgstruct-mode, this also exports all indentation
7136 and autofilling variables from org-mode into the buffer. It will also
7137 recognize item context in multiline items.
7138 Note that turning off orgstruct-mode will *not* remove the
7139 indentation/paragraph settings. This can only be done by refreshing the
7140 major mode, for example with \\[normal-mode]."
7141 (interactive "P")
7142 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7143 (if (< arg 1)
7144 (orgstruct-mode -1)
7145 (orgstruct-mode 1)
7146 (let (var val)
7147 (mapc
7148 (lambda (x)
7149 (when (string-match
7150 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7151 (symbol-name (car x)))
7152 (setq var (car x) val (nth 1 x))
7153 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7154 org-local-vars)
7155 (org-set-local 'orgstruct-is-++ t))))
7157 (defvar orgstruct-is-++ nil
7158 "Is orgstruct-mode in ++ version in the current-buffer?")
7159 (make-variable-buffer-local 'orgstruct-is-++)
7161 ;;;###autoload
7162 (defun turn-on-orgstruct++ ()
7163 "Unconditionally turn on `orgstruct++-mode'."
7164 (orgstruct++-mode 1))
7166 (defun orgstruct-error ()
7167 "Error when there is no default binding for a structure key."
7168 (interactive)
7169 (error "This key has no function outside structure elements"))
7171 (defun orgstruct-setup ()
7172 "Setup orgstruct keymaps."
7173 (let ((nfunc 0)
7174 (bindings
7175 (list
7176 '([(meta up)] org-metaup)
7177 '([(meta down)] org-metadown)
7178 '([(meta left)] org-metaleft)
7179 '([(meta right)] org-metaright)
7180 '([(meta shift up)] org-shiftmetaup)
7181 '([(meta shift down)] org-shiftmetadown)
7182 '([(meta shift left)] org-shiftmetaleft)
7183 '([(meta shift right)] org-shiftmetaright)
7184 '([?\e (up)] org-metaup)
7185 '([?\e (down)] org-metadown)
7186 '([?\e (left)] org-metaleft)
7187 '([?\e (right)] org-metaright)
7188 '([?\e (shift up)] org-shiftmetaup)
7189 '([?\e (shift down)] org-shiftmetadown)
7190 '([?\e (shift left)] org-shiftmetaleft)
7191 '([?\e (shift right)] org-shiftmetaright)
7192 '([(shift up)] org-shiftup)
7193 '([(shift down)] org-shiftdown)
7194 '([(shift left)] org-shiftleft)
7195 '([(shift right)] org-shiftright)
7196 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7197 '("\M-q" fill-paragraph)
7198 '("\C-c^" org-sort)
7199 '("\C-c-" org-cycle-list-bullet)))
7200 elt key fun cmd)
7201 (while (setq elt (pop bindings))
7202 (setq nfunc (1+ nfunc))
7203 (setq key (org-key (car elt))
7204 fun (nth 1 elt)
7205 cmd (orgstruct-make-binding fun nfunc key))
7206 (org-defkey orgstruct-mode-map key cmd))
7208 ;; Special treatment needed for TAB and RET
7209 (org-defkey orgstruct-mode-map [(tab)]
7210 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7211 (org-defkey orgstruct-mode-map "\C-i"
7212 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7214 (org-defkey orgstruct-mode-map "\M-\C-m"
7215 (orgstruct-make-binding 'org-insert-heading 105
7216 "\M-\C-m" [(meta return)]))
7217 (org-defkey orgstruct-mode-map [(meta return)]
7218 (orgstruct-make-binding 'org-insert-heading 106
7219 [(meta return)] "\M-\C-m"))
7221 (org-defkey orgstruct-mode-map [(shift meta return)]
7222 (orgstruct-make-binding 'org-insert-todo-heading 107
7223 [(meta return)] "\M-\C-m"))
7225 (org-defkey orgstruct-mode-map "\e\C-m"
7226 (orgstruct-make-binding 'org-insert-heading 108
7227 "\e\C-m" [?\e (return)]))
7228 (org-defkey orgstruct-mode-map [?\e (return)]
7229 (orgstruct-make-binding 'org-insert-heading 109
7230 [?\e (return)] "\e\C-m"))
7231 (org-defkey orgstruct-mode-map [?\e (shift return)]
7232 (orgstruct-make-binding 'org-insert-todo-heading 110
7233 [?\e (return)] "\e\C-m"))
7235 (unless org-local-vars
7236 (setq org-local-vars (org-get-local-variables)))
7240 (defun orgstruct-make-binding (fun n &rest keys)
7241 "Create a function for binding in the structure minor mode.
7242 FUN is the command to call inside a table. N is used to create a unique
7243 command name. KEYS are keys that should be checked in for a command
7244 to execute outside of tables."
7245 (eval
7246 (list 'defun
7247 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7248 '(arg)
7249 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7250 "Outside of structure, run the binding of `"
7251 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7252 "'.")
7253 '(interactive "p")
7254 (list 'if
7255 `(org-context-p 'headline 'item
7256 (and orgstruct-is-++
7257 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7258 'item-body))
7259 (list 'org-run-like-in-org-mode (list 'quote fun))
7260 (list 'let '(orgstruct-mode)
7261 (list 'call-interactively
7262 (append '(or)
7263 (mapcar (lambda (k)
7264 (list 'key-binding k))
7265 keys)
7266 '('orgstruct-error))))))))
7268 (defun org-context-p (&rest contexts)
7269 "Check if local context is any of CONTEXTS.
7270 Possible values in the list of contexts are `table', `headline', and `item'."
7271 (let ((pos (point)))
7272 (goto-char (point-at-bol))
7273 (prog1 (or (and (memq 'table contexts)
7274 (looking-at "[ \t]*|"))
7275 (and (memq 'headline contexts)
7276 ;;????????? (looking-at "\\*+"))
7277 (looking-at outline-regexp))
7278 (and (memq 'item contexts)
7279 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7280 (and (memq 'item-body contexts)
7281 (org-in-item-p)))
7282 (goto-char pos))))
7284 (defun org-get-local-variables ()
7285 "Return a list of all local variables in an org-mode buffer."
7286 (let (varlist)
7287 (with-current-buffer (get-buffer-create "*Org tmp*")
7288 (erase-buffer)
7289 (org-mode)
7290 (setq varlist (buffer-local-variables)))
7291 (kill-buffer "*Org tmp*")
7292 (delq nil
7293 (mapcar
7294 (lambda (x)
7295 (setq x
7296 (if (symbolp x)
7297 (list x)
7298 (list (car x) (list 'quote (cdr x)))))
7299 (if (string-match
7300 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7301 (symbol-name (car x)))
7302 x nil))
7303 varlist))))
7305 ;;;###autoload
7306 (defun org-run-like-in-org-mode (cmd)
7307 "Run a command, pretending that the current buffer is in Org-mode.
7308 This will temporarily bind local variables that are typically bound in
7309 Org-mode to the values they have in Org-mode, and then interactively
7310 call CMD."
7311 (org-load-modules-maybe)
7312 (unless org-local-vars
7313 (setq org-local-vars (org-get-local-variables)))
7314 (eval (list 'let org-local-vars
7315 (list 'call-interactively (list 'quote cmd)))))
7317 ;;;; Archiving
7319 (defun org-get-category (&optional pos)
7320 "Get the category applying to position POS."
7321 (get-text-property (or pos (point)) 'org-category))
7323 (defun org-refresh-category-properties ()
7324 "Refresh category text properties in the buffer."
7325 (let ((def-cat (cond
7326 ((null org-category)
7327 (if buffer-file-name
7328 (file-name-sans-extension
7329 (file-name-nondirectory buffer-file-name))
7330 "???"))
7331 ((symbolp org-category) (symbol-name org-category))
7332 (t org-category)))
7333 beg end cat pos optionp)
7334 (org-unmodified
7335 (save-excursion
7336 (save-restriction
7337 (widen)
7338 (goto-char (point-min))
7339 (put-text-property (point) (point-max) 'org-category def-cat)
7340 (while (re-search-forward
7341 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7342 (setq pos (match-end 0)
7343 optionp (equal (char-after (match-beginning 0)) ?#)
7344 cat (org-trim (match-string 2)))
7345 (if optionp
7346 (setq beg (point-at-bol) end (point-max))
7347 (org-back-to-heading t)
7348 (setq beg (point) end (org-end-of-subtree t t)))
7349 (put-text-property beg end 'org-category cat)
7350 (goto-char pos)))))))
7353 ;;;; Link Stuff
7355 ;;; Link abbreviations
7357 (defun org-link-expand-abbrev (link)
7358 "Apply replacements as defined in `org-link-abbrev-alist."
7359 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7360 (let* ((key (match-string 1 link))
7361 (as (or (assoc key org-link-abbrev-alist-local)
7362 (assoc key org-link-abbrev-alist)))
7363 (tag (and (match-end 2) (match-string 3 link)))
7364 rpl)
7365 (if (not as)
7366 link
7367 (setq rpl (cdr as))
7368 (cond
7369 ((symbolp rpl) (funcall rpl tag))
7370 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7371 ((string-match "%h" rpl)
7372 (replace-match (url-hexify-string (or tag "")) t t rpl))
7373 (t (concat rpl tag)))))
7374 link))
7376 ;;; Storing and inserting links
7378 (defvar org-insert-link-history nil
7379 "Minibuffer history for links inserted with `org-insert-link'.")
7381 (defvar org-stored-links nil
7382 "Contains the links stored with `org-store-link'.")
7384 (defvar org-store-link-plist nil
7385 "Plist with info about the most recently link created with `org-store-link'.")
7387 (defvar org-link-protocols nil
7388 "Link protocols added to Org-mode using `org-add-link-type'.")
7390 (defvar org-store-link-functions nil
7391 "List of functions that are called to create and store a link.
7392 Each function will be called in turn until one returns a non-nil
7393 value. Each function should check if it is responsible for creating
7394 this link (for example by looking at the major mode).
7395 If not, it must exit and return nil.
7396 If yes, it should return a non-nil value after a calling
7397 `org-store-link-props' with a list of properties and values.
7398 Special properties are:
7400 :type The link prefix. like \"http\". This must be given.
7401 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7402 This is obligatory as well.
7403 :description Optional default description for the second pair
7404 of brackets in an Org-mode link. The user can still change
7405 this when inserting this link into an Org-mode buffer.
7407 In addition to these, any additional properties can be specified
7408 and then used in remember templates.")
7410 (defun org-add-link-type (type &optional follow export)
7411 "Add TYPE to the list of `org-link-types'.
7412 Re-compute all regular expressions depending on `org-link-types'
7414 FOLLOW and EXPORT are two functions.
7416 FOLLOW should take the link path as the single argument and do whatever
7417 is necessary to follow the link, for example find a file or display
7418 a mail message.
7420 EXPORT should format the link path for export to one of the export formats.
7421 It should be a function accepting three arguments:
7423 path the path of the link, the text after the prefix (like \"http:\")
7424 desc the description of the link, if any, nil if there was no description
7425 format the export format, a symbol like `html' or `latex'.
7427 The function may use the FORMAT information to return different values
7428 depending on the format. The return value will be put literally into
7429 the exported file.
7430 Org-mode has a built-in default for exporting links. If you are happy with
7431 this default, there is no need to define an export function for the link
7432 type. For a simple example of an export function, see `org-bbdb.el'."
7433 (add-to-list 'org-link-types type t)
7434 (org-make-link-regexps)
7435 (if (assoc type org-link-protocols)
7436 (setcdr (assoc type org-link-protocols) (list follow export))
7437 (push (list type follow export) org-link-protocols)))
7439 (defvar org-agenda-buffer-name)
7441 ;;;###autoload
7442 (defun org-store-link (arg)
7443 "\\<org-mode-map>Store an org-link to the current location.
7444 This link is added to `org-stored-links' and can later be inserted
7445 into an org-buffer with \\[org-insert-link].
7447 For some link types, a prefix arg is interpreted:
7448 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7449 For file links, arg negates `org-context-in-file-links'."
7450 (interactive "P")
7451 (org-load-modules-maybe)
7452 (setq org-store-link-plist nil) ; reset
7453 (let ((outline-regexp (org-get-limited-outline-regexp))
7454 link cpltxt desc description search txt custom-id)
7455 (cond
7457 ((run-hook-with-args-until-success 'org-store-link-functions)
7458 (setq link (plist-get org-store-link-plist :link)
7459 desc (or (plist-get org-store-link-plist :description) link)))
7461 ((equal (buffer-name) "*Org Edit Src Example*")
7462 (let (label gc)
7463 (while (or (not label)
7464 (save-excursion
7465 (save-restriction
7466 (widen)
7467 (goto-char (point-min))
7468 (re-search-forward
7469 (regexp-quote (format org-coderef-label-format label))
7470 nil t))))
7471 (when label (message "Label exists already") (sit-for 2))
7472 (setq label (read-string "Code line label: " label)))
7473 (end-of-line 1)
7474 (setq link (format org-coderef-label-format label))
7475 (setq gc (- 79 (length link)))
7476 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7477 (insert link)
7478 (setq link (concat "(" label ")") desc nil)))
7480 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7481 ;; We are in the agenda, link to referenced location
7482 (let ((m (or (get-text-property (point) 'org-hd-marker)
7483 (get-text-property (point) 'org-marker))))
7484 (when m
7485 (org-with-point-at m
7486 (call-interactively 'org-store-link)))))
7488 ((eq major-mode 'calendar-mode)
7489 (let ((cd (calendar-cursor-to-date)))
7490 (setq link
7491 (format-time-string
7492 (car org-time-stamp-formats)
7493 (apply 'encode-time
7494 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7495 nil nil nil))))
7496 (org-store-link-props :type "calendar" :date cd)))
7498 ((eq major-mode 'w3-mode)
7499 (setq cpltxt (if (and (buffer-name)
7500 (not (string-match "Untitled" (buffer-name))))
7501 (buffer-name)
7502 (url-view-url t))
7503 link (org-make-link (url-view-url t)))
7504 (org-store-link-props :type "w3" :url (url-view-url t)))
7506 ((eq major-mode 'w3m-mode)
7507 (setq cpltxt (or w3m-current-title w3m-current-url)
7508 link (org-make-link w3m-current-url))
7509 (org-store-link-props :type "w3m" :url (url-view-url t)))
7511 ((setq search (run-hook-with-args-until-success
7512 'org-create-file-search-functions))
7513 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7514 "::" search))
7515 (setq cpltxt (or description link)))
7517 ((eq major-mode 'image-mode)
7518 (setq cpltxt (concat "file:"
7519 (abbreviate-file-name buffer-file-name))
7520 link (org-make-link cpltxt))
7521 (org-store-link-props :type "image" :file buffer-file-name))
7523 ((eq major-mode 'dired-mode)
7524 ;; link to the file in the current line
7525 (setq cpltxt (concat "file:"
7526 (abbreviate-file-name
7527 (expand-file-name
7528 (dired-get-filename nil t))))
7529 link (org-make-link cpltxt)))
7531 ((and buffer-file-name (org-mode-p))
7532 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7533 (cond
7534 ((org-in-regexp "<<\\(.*?\\)>>")
7535 (setq cpltxt
7536 (concat "file:"
7537 (abbreviate-file-name buffer-file-name)
7538 "::" (match-string 1))
7539 link (org-make-link cpltxt)))
7540 ((and (featurep 'org-id)
7541 (or (eq org-link-to-org-use-id t)
7542 (and (eq org-link-to-org-use-id 'create-if-interactive)
7543 (interactive-p))
7544 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7545 (interactive-p)
7546 (not custom-id))
7547 (and org-link-to-org-use-id
7548 (condition-case nil
7549 (org-entry-get nil "ID")
7550 (error nil)))))
7551 ;; We can make a link using the ID.
7552 (setq link (condition-case nil
7553 (prog1 (org-id-store-link)
7554 (setq desc (plist-get org-store-link-plist
7555 :description)))
7556 (error
7557 ;; probably before first headline, link to file only
7558 (concat "file:"
7559 (abbreviate-file-name buffer-file-name))))))
7561 ;; Just link to current headline
7562 (setq cpltxt (concat "file:"
7563 (abbreviate-file-name buffer-file-name)))
7564 ;; Add a context search string
7565 (when (org-xor org-context-in-file-links arg)
7566 (setq txt (cond
7567 ((org-on-heading-p) nil)
7568 ((org-region-active-p)
7569 (buffer-substring (region-beginning) (region-end)))
7570 (t nil)))
7571 (when (or (null txt) (string-match "\\S-" txt))
7572 (setq cpltxt
7573 (concat cpltxt "::"
7574 (condition-case nil
7575 (org-make-org-heading-search-string txt)
7576 (error "")))
7577 desc (or (nth 4 (ignore-errors
7578 (org-heading-components))) "NONE"))))
7579 (if (string-match "::\\'" cpltxt)
7580 (setq cpltxt (substring cpltxt 0 -2)))
7581 (setq link (org-make-link cpltxt)))))
7583 ((buffer-file-name (buffer-base-buffer))
7584 ;; Just link to this file here.
7585 (setq cpltxt (concat "file:"
7586 (abbreviate-file-name
7587 (buffer-file-name (buffer-base-buffer)))))
7588 ;; Add a context string
7589 (when (org-xor org-context-in-file-links arg)
7590 (setq txt (if (org-region-active-p)
7591 (buffer-substring (region-beginning) (region-end))
7592 (buffer-substring (point-at-bol) (point-at-eol))))
7593 ;; Only use search option if there is some text.
7594 (when (string-match "\\S-" txt)
7595 (setq cpltxt
7596 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7597 desc "NONE")))
7598 (setq link (org-make-link cpltxt)))
7600 ((interactive-p)
7601 (error "Cannot link to a buffer which is not visiting a file"))
7603 (t (setq link nil)))
7605 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7606 (setq link (or link cpltxt)
7607 desc (or desc cpltxt))
7608 (if (equal desc "NONE") (setq desc nil))
7610 (if (and (or (interactive-p) executing-kbd-macro) link)
7611 (progn
7612 (setq org-stored-links
7613 (cons (list link desc) org-stored-links))
7614 (message "Stored: %s" (or desc link))
7615 (when custom-id
7616 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7617 "::#" custom-id))
7618 (setq org-stored-links
7619 (cons (list link desc) org-stored-links))))
7620 (and link (org-make-link-string link desc)))))
7622 (defun org-store-link-props (&rest plist)
7623 "Store link properties, extract names and addresses."
7624 (let (x adr)
7625 (when (setq x (plist-get plist :from))
7626 (setq adr (mail-extract-address-components x))
7627 (setq plist (plist-put plist :fromname (car adr)))
7628 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7629 (when (setq x (plist-get plist :to))
7630 (setq adr (mail-extract-address-components x))
7631 (setq plist (plist-put plist :toname (car adr)))
7632 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7633 (let ((from (plist-get plist :from))
7634 (to (plist-get plist :to)))
7635 (when (and from to org-from-is-user-regexp)
7636 (setq plist
7637 (plist-put plist :fromto
7638 (if (string-match org-from-is-user-regexp from)
7639 (concat "to %t")
7640 (concat "from %f"))))))
7641 (setq org-store-link-plist plist))
7643 (defun org-add-link-props (&rest plist)
7644 "Add these properties to the link property list."
7645 (let (key value)
7646 (while plist
7647 (setq key (pop plist) value (pop plist))
7648 (setq org-store-link-plist
7649 (plist-put org-store-link-plist key value)))))
7651 (defun org-email-link-description (&optional fmt)
7652 "Return the description part of an email link.
7653 This takes information from `org-store-link-plist' and formats it
7654 according to FMT (default from `org-email-link-description-format')."
7655 (setq fmt (or fmt org-email-link-description-format))
7656 (let* ((p org-store-link-plist)
7657 (to (plist-get p :toaddress))
7658 (from (plist-get p :fromaddress))
7659 (table
7660 (list
7661 (cons "%c" (plist-get p :fromto))
7662 (cons "%F" (plist-get p :from))
7663 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7664 (cons "%T" (plist-get p :to))
7665 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7666 (cons "%s" (plist-get p :subject))
7667 (cons "%m" (plist-get p :message-id)))))
7668 (when (string-match "%c" fmt)
7669 ;; Check if the user wrote this message
7670 (if (and org-from-is-user-regexp from to
7671 (save-match-data (string-match org-from-is-user-regexp from)))
7672 (setq fmt (replace-match "to %t" t t fmt))
7673 (setq fmt (replace-match "from %f" t t fmt))))
7674 (org-replace-escapes fmt table)))
7676 (defun org-make-org-heading-search-string (&optional string heading)
7677 "Make search string for STRING or current headline."
7678 (interactive)
7679 (let ((s (or string (org-get-heading))))
7680 (unless (and string (not heading))
7681 ;; We are using a headline, clean up garbage in there.
7682 (if (string-match org-todo-regexp s)
7683 (setq s (replace-match "" t t s)))
7684 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7685 (setq s (replace-match "" t t s)))
7686 (setq s (org-trim s))
7687 (if (string-match (concat "^\\(" org-quote-string "\\|"
7688 org-comment-string "\\)") s)
7689 (setq s (replace-match "" t t s)))
7690 (while (string-match org-ts-regexp s)
7691 (setq s (replace-match "" t t s))))
7692 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7693 (setq s (replace-match " " t t s)))
7694 (or string (setq s (concat "*" s))) ; Add * for headlines
7695 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7697 (defun org-make-link (&rest strings)
7698 "Concatenate STRINGS."
7699 (apply 'concat strings))
7701 (defun org-make-link-string (link &optional description)
7702 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7703 (unless (string-match "\\S-" link)
7704 (error "Empty link"))
7705 (when (stringp description)
7706 ;; Remove brackets from the description, they are fatal.
7707 (while (string-match "\\[" description)
7708 (setq description (replace-match "{" t t description)))
7709 (while (string-match "\\]" description)
7710 (setq description (replace-match "}" t t description))))
7711 (when (equal (org-link-escape link) description)
7712 ;; No description needed, it is identical
7713 (setq description nil))
7714 (when (and (not description)
7715 (not (equal link (org-link-escape link))))
7716 (setq description (org-extract-attributes link)))
7717 (concat "[[" (org-link-escape link) "]"
7718 (if description (concat "[" description "]") "")
7719 "]"))
7721 (defconst org-link-escape-chars
7722 '((?\ . "%20")
7723 (?\[ . "%5B")
7724 (?\] . "%5D")
7725 (?\340 . "%E0") ; `a
7726 (?\342 . "%E2") ; ^a
7727 (?\347 . "%E7") ; ,c
7728 (?\350 . "%E8") ; `e
7729 (?\351 . "%E9") ; 'e
7730 (?\352 . "%EA") ; ^e
7731 (?\356 . "%EE") ; ^i
7732 (?\364 . "%F4") ; ^o
7733 (?\371 . "%F9") ; `u
7734 (?\373 . "%FB") ; ^u
7735 (?\; . "%3B")
7736 (?? . "%3F")
7737 (?= . "%3D")
7738 (?+ . "%2B")
7740 "Association list of escapes for some characters problematic in links.
7741 This is the list that is used for internal purposes.")
7743 (defvar org-url-encoding-use-url-hexify nil)
7745 (defconst org-link-escape-chars-browser
7746 '((?\ . "%20")) ; 32 for the SPC char
7747 "Association list of escapes for some characters problematic in links.
7748 This is the list that is used before handing over to the browser.")
7750 (defun org-link-escape (text &optional table)
7751 "Escape characters in TEXT that are problematic for links."
7752 (if org-url-encoding-use-url-hexify
7753 (url-hexify-string text)
7754 (setq table (or table org-link-escape-chars))
7755 (when text
7756 (let ((re (mapconcat (lambda (x) (regexp-quote
7757 (char-to-string (car x))))
7758 table "\\|")))
7759 (while (string-match re text)
7760 (setq text
7761 (replace-match
7762 (cdr (assoc (string-to-char (match-string 0 text))
7763 table))
7764 t t text)))
7765 text))))
7767 (defun org-link-unescape (text &optional table)
7768 "Reverse the action of `org-link-escape'."
7769 (if org-url-encoding-use-url-hexify
7770 (url-unhex-string text)
7771 (setq table (or table org-link-escape-chars))
7772 (when text
7773 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7774 table "\\|")))
7775 (while (string-match re text)
7776 (setq text
7777 (replace-match
7778 (char-to-string (car (rassoc (match-string 0 text) table)))
7779 t t text)))
7780 text))))
7782 (defun org-xor (a b)
7783 "Exclusive or."
7784 (if a (not b) b))
7786 (defun org-fixup-message-id-for-http (s)
7787 "Replace special characters in a message id, so it can be used in an http query."
7788 (while (string-match "<" s)
7789 (setq s (replace-match "%3C" t t s)))
7790 (while (string-match ">" s)
7791 (setq s (replace-match "%3E" t t s)))
7792 (while (string-match "@" s)
7793 (setq s (replace-match "%40" t t s)))
7796 ;;;###autoload
7797 (defun org-insert-link-global ()
7798 "Insert a link like Org-mode does.
7799 This command can be called in any mode to insert a link in Org-mode syntax."
7800 (interactive)
7801 (org-load-modules-maybe)
7802 (org-run-like-in-org-mode 'org-insert-link))
7804 (defun org-insert-link (&optional complete-file link-location)
7805 "Insert a link. At the prompt, enter the link.
7807 Completion can be used to insert any of the link protocol prefixes like
7808 http or ftp in use.
7810 The history can be used to select a link previously stored with
7811 `org-store-link'. When the empty string is entered (i.e. if you just
7812 press RET at the prompt), the link defaults to the most recently
7813 stored link. As SPC triggers completion in the minibuffer, you need to
7814 use M-SPC or C-q SPC to force the insertion of a space character.
7816 You will also be prompted for a description, and if one is given, it will
7817 be displayed in the buffer instead of the link.
7819 If there is already a link at point, this command will allow you to edit link
7820 and description parts.
7822 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7823 be selected using completion. The path to the file will be relative to the
7824 current directory if the file is in the current directory or a subdirectory.
7825 Otherwise, the link will be the absolute path as completed in the minibuffer
7826 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7827 option `org-link-file-path-type'.
7829 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7830 the current directory or below.
7832 With three \\[universal-argument] prefixes, negate the meaning of
7833 `org-keep-stored-link-after-insertion'.
7835 If `org-make-link-description-function' is non-nil, this function will be
7836 called with the link target, and the result will be the default
7837 link description.
7839 If the LINK-LOCATION parameter is non-nil, this value will be
7840 used as the link location instead of reading one interactively."
7841 (interactive "P")
7842 (let* ((wcf (current-window-configuration))
7843 (region (if (org-region-active-p)
7844 (buffer-substring (region-beginning) (region-end))))
7845 (remove (and region (list (region-beginning) (region-end))))
7846 (desc region)
7847 tmphist ; byte-compile incorrectly complains about this
7848 (link link-location)
7849 entry file all-prefixes)
7850 (cond
7851 (link-location) ; specified by arg, just use it.
7852 ((org-in-regexp org-bracket-link-regexp 1)
7853 ;; We do have a link at point, and we are going to edit it.
7854 (setq remove (list (match-beginning 0) (match-end 0)))
7855 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7856 (setq link (read-string "Link: "
7857 (org-link-unescape
7858 (org-match-string-no-properties 1)))))
7859 ((or (org-in-regexp org-angle-link-re)
7860 (org-in-regexp org-plain-link-re))
7861 ;; Convert to bracket link
7862 (setq remove (list (match-beginning 0) (match-end 0))
7863 link (read-string "Link: "
7864 (org-remove-angle-brackets (match-string 0)))))
7865 ((member complete-file '((4) (16)))
7866 ;; Completing read for file names.
7867 (setq link (org-file-complete-link complete-file)))
7869 ;; Read link, with completion for stored links.
7870 (with-output-to-temp-buffer "*Org Links*"
7871 (princ "Insert a link.
7872 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7873 (when org-stored-links
7874 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7875 (princ (mapconcat
7876 (lambda (x)
7877 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7878 (reverse org-stored-links) "\n"))))
7879 (let ((cw (selected-window)))
7880 (select-window (get-buffer-window "*Org Links*"))
7881 (setq truncate-lines t)
7882 (unless (pos-visible-in-window-p (point-max))
7883 (org-fit-window-to-buffer))
7884 (and (window-live-p cw) (select-window cw)))
7885 ;; Fake a link history, containing the stored links.
7886 (setq tmphist (append (mapcar 'car org-stored-links)
7887 org-insert-link-history))
7888 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7889 (mapcar 'car org-link-abbrev-alist)
7890 org-link-types))
7891 (unwind-protect
7892 (progn
7893 (setq link
7894 (let ((org-completion-use-ido nil)
7895 (org-completion-use-iswitchb nil))
7896 (org-completing-read
7897 "Link: "
7898 (append
7899 (mapcar (lambda (x) (list (concat x ":")))
7900 all-prefixes)
7901 (mapcar 'car org-stored-links))
7902 nil nil nil
7903 'tmphist
7904 (car (car org-stored-links)))))
7905 (if (or (member link all-prefixes)
7906 (and (equal ":" (substring link -1))
7907 (member (substring link 0 -1) all-prefixes)
7908 (setq link (substring link 0 -1))))
7909 (setq link (org-link-try-special-completion link))))
7910 (set-window-configuration wcf)
7911 (kill-buffer "*Org Links*"))
7912 (setq entry (assoc link org-stored-links))
7913 (or entry (push link org-insert-link-history))
7914 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7915 (not org-keep-stored-link-after-insertion))
7916 (setq org-stored-links (delq (assoc link org-stored-links)
7917 org-stored-links)))
7918 (setq desc (or desc (nth 1 entry)))))
7920 (if (string-match org-plain-link-re link)
7921 ;; URL-like link, normalize the use of angular brackets.
7922 (setq link (org-make-link (org-remove-angle-brackets link))))
7924 ;; Check if we are linking to the current file with a search option
7925 ;; If yes, simplify the link by using only the search option.
7926 (when (and buffer-file-name
7927 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7928 (let* ((path (match-string 1 link))
7929 (case-fold-search nil)
7930 (search (match-string 2 link)))
7931 (save-match-data
7932 (if (equal (file-truename buffer-file-name) (file-truename path))
7933 ;; We are linking to this same file, with a search option
7934 (setq link search)))))
7936 ;; Check if we can/should use a relative path. If yes, simplify the link
7937 (when (string-match "^file:\\(.*\\)" link)
7938 (let* ((path (match-string 1 link))
7939 (origpath path)
7940 (case-fold-search nil))
7941 (cond
7942 ((or (eq org-link-file-path-type 'absolute)
7943 (equal complete-file '(16)))
7944 (setq path (abbreviate-file-name (expand-file-name path))))
7945 ((eq org-link-file-path-type 'noabbrev)
7946 (setq path (expand-file-name path)))
7947 ((eq org-link-file-path-type 'relative)
7948 (setq path (file-relative-name path)))
7950 (save-match-data
7951 (if (string-match (concat "^" (regexp-quote
7952 (file-name-as-directory
7953 (expand-file-name "."))))
7954 (expand-file-name path))
7955 ;; We are linking a file with relative path name.
7956 (setq path (substring (expand-file-name path)
7957 (match-end 0)))
7958 (setq path (abbreviate-file-name (expand-file-name path)))))))
7959 (setq link (concat "file:" path))
7960 (if (equal desc origpath)
7961 (setq desc path))))
7963 (if org-make-link-description-function
7964 (setq desc (funcall org-make-link-description-function link desc)))
7966 (setq desc (read-string "Description: " desc))
7967 (unless (string-match "\\S-" desc) (setq desc nil))
7968 (if remove (apply 'delete-region remove))
7969 (insert (org-make-link-string link desc))))
7971 (defun org-link-try-special-completion (type)
7972 "If there is completion support for link type TYPE, offer it."
7973 (let ((fun (intern (concat "org-" type "-complete-link"))))
7974 (if (functionp fun)
7975 (funcall fun)
7976 (read-string "Link (no completion support): " (concat type ":")))))
7978 (defun org-file-complete-link (&optional arg)
7979 "Create a file link using completion."
7980 (let (file link)
7981 (setq file (read-file-name "File: "))
7982 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7983 (pwd1 (file-name-as-directory (abbreviate-file-name
7984 (expand-file-name ".")))))
7985 (cond
7986 ((equal arg '(16))
7987 (setq link (org-make-link
7988 "file:"
7989 (abbreviate-file-name (expand-file-name file)))))
7990 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7991 (setq link (org-make-link "file:" (match-string 1 file))))
7992 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7993 (expand-file-name file))
7994 (setq link (org-make-link
7995 "file:" (match-string 1 (expand-file-name file)))))
7996 (t (setq link (org-make-link "file:" file)))))
7997 link))
7999 (defun org-completing-read (&rest args)
8000 "Completing-read with SPACE being a normal character."
8001 (let ((minibuffer-local-completion-map
8002 (copy-keymap minibuffer-local-completion-map)))
8003 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8004 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8005 (apply 'org-icompleting-read args)))
8007 (defun org-completing-read-no-i (&rest args)
8008 (let (org-completion-use-ido org-completion-use-iswitchb)
8009 (apply 'org-completing-read args)))
8011 (defun org-iswitchb-completing-read (prompt choices &rest args)
8012 "Use iswitch as a completing-read replacement to choose from choices.
8013 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8014 from."
8015 (let* ((iswitchb-use-virtual-buffers nil)
8016 (iswitchb-make-buflist-hook
8017 (lambda ()
8018 (setq iswitchb-temp-buflist choices))))
8019 (iswitchb-read-buffer prompt)))
8021 (defun org-icompleting-read (&rest args)
8022 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8023 (org-without-partial-completion
8024 (if (and org-completion-use-ido
8025 (fboundp 'ido-completing-read)
8026 (boundp 'ido-mode) ido-mode
8027 (listp (second args)))
8028 (let ((ido-enter-matching-directory nil))
8029 (apply 'ido-completing-read (concat (car args))
8030 (if (consp (car (nth 1 args)))
8031 (mapcar (lambda (x) (car x)) (nth 1 args))
8032 (nth 1 args))
8033 (cddr args)))
8034 (if (and org-completion-use-iswitchb
8035 (boundp 'iswitchb-mode) iswitchb-mode
8036 (listp (second args)))
8037 (apply 'org-iswitchb-completing-read (concat (car args))
8038 (if (consp (car (nth 1 args)))
8039 (mapcar (lambda (x) (car x)) (nth 1 args))
8040 (nth 1 args))
8041 (cddr args))
8042 (apply 'completing-read args)))))
8044 (defun org-extract-attributes (s)
8045 "Extract the attributes cookie from a string and set as text property."
8046 (let (a attr (start 0) key value)
8047 (save-match-data
8048 (when (string-match "{{\\([^}]+\\)}}$" s)
8049 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8050 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8051 (setq key (match-string 1 a) value (match-string 2 a)
8052 start (match-end 0)
8053 attr (plist-put attr (intern key) value))))
8054 (org-add-props s nil 'org-attr attr))
8057 (defun org-extract-attributes-from-string (tag)
8058 (let (key value attr)
8059 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8060 (setq key (match-string 1 tag) value (match-string 2 tag)
8061 tag (replace-match "" t t tag)
8062 attr (plist-put attr (intern key) value)))
8063 (cons tag attr)))
8065 (defun org-attributes-to-string (plist)
8066 "Format a property list into an HTML attribute list."
8067 (let ((s "") key value)
8068 (while plist
8069 (setq key (pop plist) value (pop plist))
8070 (and value
8071 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8074 ;;; Opening/following a link
8076 (defvar org-link-search-failed nil)
8078 (defun org-next-link ()
8079 "Move forward to the next link.
8080 If the link is in hidden text, expose it."
8081 (interactive)
8082 (when (and org-link-search-failed (eq this-command last-command))
8083 (goto-char (point-min))
8084 (message "Link search wrapped back to beginning of buffer"))
8085 (setq org-link-search-failed nil)
8086 (let* ((pos (point))
8087 (ct (org-context))
8088 (a (assoc :link ct)))
8089 (if a (goto-char (nth 2 a)))
8090 (if (re-search-forward org-any-link-re nil t)
8091 (progn
8092 (goto-char (match-beginning 0))
8093 (if (org-invisible-p) (org-show-context)))
8094 (goto-char pos)
8095 (setq org-link-search-failed t)
8096 (error "No further link found"))))
8098 (defun org-previous-link ()
8099 "Move backward to the previous link.
8100 If the link is in hidden text, expose it."
8101 (interactive)
8102 (when (and org-link-search-failed (eq this-command last-command))
8103 (goto-char (point-max))
8104 (message "Link search wrapped back to end of buffer"))
8105 (setq org-link-search-failed nil)
8106 (let* ((pos (point))
8107 (ct (org-context))
8108 (a (assoc :link ct)))
8109 (if a (goto-char (nth 1 a)))
8110 (if (re-search-backward org-any-link-re nil t)
8111 (progn
8112 (goto-char (match-beginning 0))
8113 (if (org-invisible-p) (org-show-context)))
8114 (goto-char pos)
8115 (setq org-link-search-failed t)
8116 (error "No further link found"))))
8118 (defun org-translate-link (s)
8119 "Translate a link string if a translation function has been defined."
8120 (if (and org-link-translation-function
8121 (fboundp org-link-translation-function)
8122 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8123 (progn
8124 (setq s (funcall org-link-translation-function
8125 (match-string 1) (match-string 2)))
8126 (concat (car s) ":" (cdr s)))
8129 (defun org-translate-link-from-planner (type path)
8130 "Translate a link from Emacs Planner syntax so that Org can follow it.
8131 This is still an experimental function, your mileage may vary."
8132 (cond
8133 ((member type '("http" "https" "news" "ftp"))
8134 ;; standard Internet links are the same.
8135 nil)
8136 ((and (equal type "irc") (string-match "^//" path))
8137 ;; Planner has two / at the beginning of an irc link, we have 1.
8138 ;; We should have zero, actually....
8139 (setq path (substring path 1)))
8140 ((and (equal type "lisp") (string-match "^/" path))
8141 ;; Planner has a slash, we do not.
8142 (setq type "elisp" path (substring path 1)))
8143 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8144 ;; A typical message link. Planner has the id after the final slash,
8145 ;; we separate it with a hash mark
8146 (setq path (concat (match-string 1 path) "#"
8147 (org-remove-angle-brackets (match-string 2 path)))))
8149 (cons type path))
8151 (defun org-find-file-at-mouse (ev)
8152 "Open file link or URL at mouse."
8153 (interactive "e")
8154 (mouse-set-point ev)
8155 (org-open-at-point 'in-emacs))
8157 (defun org-open-at-mouse (ev)
8158 "Open file link or URL at mouse."
8159 (interactive "e")
8160 (mouse-set-point ev)
8161 (if (eq major-mode 'org-agenda-mode)
8162 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8163 (org-open-at-point))
8165 (defvar org-window-config-before-follow-link nil
8166 "The window configuration before following a link.
8167 This is saved in case the need arises to restore it.")
8169 (defvar org-open-link-marker (make-marker)
8170 "Marker pointing to the location where `org-open-at-point; was called.")
8172 ;;;###autoload
8173 (defun org-open-at-point-global ()
8174 "Follow a link like Org-mode does.
8175 This command can be called in any mode to follow a link that has
8176 Org-mode syntax."
8177 (interactive)
8178 (org-run-like-in-org-mode 'org-open-at-point))
8180 ;;;###autoload
8181 (defun org-open-link-from-string (s &optional arg reference-buffer)
8182 "Open a link in the string S, as if it was in Org-mode."
8183 (interactive "sLink: \nP")
8184 (let ((reference-buffer (or reference-buffer (current-buffer))))
8185 (with-temp-buffer
8186 (let ((org-inhibit-startup t))
8187 (org-mode)
8188 (insert s)
8189 (goto-char (point-min))
8190 (org-open-at-point arg reference-buffer)))))
8192 (defun org-open-at-point (&optional in-emacs reference-buffer)
8193 "Open link at or after point.
8194 If there is no link at point, this function will search forward up to
8195 the end of the current line.
8196 Normally, files will be opened by an appropriate application. If the
8197 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8198 With a double prefix argument, try to open outside of Emacs, in the
8199 application the system uses for this file type."
8200 (interactive "P")
8201 (org-load-modules-maybe)
8202 (move-marker org-open-link-marker (point))
8203 (setq org-window-config-before-follow-link (current-window-configuration))
8204 (org-remove-occur-highlights nil nil t)
8205 (cond
8206 ((and (org-on-heading-p)
8207 (not (org-in-regexp
8208 (concat org-plain-link-re "\\|"
8209 org-bracket-link-regexp "\\|"
8210 org-angle-link-re "\\|"
8211 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8212 (or (org-offer-links-in-entry in-emacs)
8213 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8214 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8215 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8216 (org-footnote-action))
8218 (let (type path link line search (pos (point)))
8219 (catch 'match
8220 (save-excursion
8221 (skip-chars-forward "^]\n\r")
8222 (when (org-in-regexp org-bracket-link-regexp)
8223 (setq link (org-extract-attributes
8224 (org-link-unescape (org-match-string-no-properties 1))))
8225 (while (string-match " *\n *" link)
8226 (setq link (replace-match " " t t link)))
8227 (setq link (org-link-expand-abbrev link))
8228 (cond
8229 ((or (file-name-absolute-p link)
8230 (string-match "^\\.\\.?/" link))
8231 (setq type "file" path link))
8232 ((string-match org-link-re-with-space3 link)
8233 (setq type (match-string 1 link) path (match-string 2 link)))
8234 (t (setq type "thisfile" path link)))
8235 (throw 'match t)))
8237 (when (get-text-property (point) 'org-linked-text)
8238 (setq type "thisfile"
8239 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8240 (1+ (point)) (point))
8241 path (buffer-substring
8242 (previous-single-property-change pos 'org-linked-text)
8243 (next-single-property-change pos 'org-linked-text)))
8244 (throw 'match t))
8246 (save-excursion
8247 (when (or (org-in-regexp org-angle-link-re)
8248 (org-in-regexp org-plain-link-re))
8249 (setq type (match-string 1) path (match-string 2))
8250 (throw 'match t)))
8251 (save-excursion
8252 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8253 (setq type "tags"
8254 path (match-string 1))
8255 (while (string-match ":" path)
8256 (setq path (replace-match "+" t t path)))
8257 (throw 'match t)))
8258 (when (org-in-regexp "<\\([^><\n]+\\)>")
8259 (setq type "tree-match"
8260 path (match-string 1))
8261 (throw 'match t)))
8262 (unless path
8263 (error "No link found"))
8265 ;; switch back to reference buffer
8266 ;; needed when if called in a temporary buffer through
8267 ;; org-open-link-from-string
8268 (with-current-buffer (or reference-buffer (current-buffer))
8270 ;; Remove any trailing spaces in path
8271 (if (string-match " +\\'" path)
8272 (setq path (replace-match "" t t path)))
8273 (if (and org-link-translation-function
8274 (fboundp org-link-translation-function))
8275 ;; Check if we need to translate the link
8276 (let ((tmp (funcall org-link-translation-function type path)))
8277 (setq type (car tmp) path (cdr tmp))))
8279 (cond
8281 ((assoc type org-link-protocols)
8282 (funcall (nth 1 (assoc type org-link-protocols)) path))
8284 ((equal type "mailto")
8285 (let ((cmd (car org-link-mailto-program))
8286 (args (cdr org-link-mailto-program)) args1
8287 (address path) (subject "") a)
8288 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8289 (setq address (match-string 1 path)
8290 subject (org-link-escape (match-string 2 path))))
8291 (while args
8292 (cond
8293 ((not (stringp (car args))) (push (pop args) args1))
8294 (t (setq a (pop args))
8295 (if (string-match "%a" a)
8296 (setq a (replace-match address t t a)))
8297 (if (string-match "%s" a)
8298 (setq a (replace-match subject t t a)))
8299 (push a args1))))
8300 (apply cmd (nreverse args1))))
8302 ((member type '("http" "https" "ftp" "news"))
8303 (browse-url (concat type ":" (org-link-escape
8304 path org-link-escape-chars-browser))))
8306 ((member type '("message"))
8307 (browse-url (concat type ":" path)))
8309 ((string= type "tags")
8310 (org-tags-view in-emacs path))
8311 ((string= type "thisfile")
8312 (if in-emacs
8313 (switch-to-buffer-other-window
8314 (org-get-buffer-for-internal-link (current-buffer)))
8315 (org-mark-ring-push))
8316 (let ((cmd `(org-link-search
8317 ,path
8318 ,(cond ((equal in-emacs '(4)) 'occur)
8319 ((equal in-emacs '(16)) 'org-occur)
8320 (t nil))
8321 ,pos)))
8322 (condition-case nil (eval cmd)
8323 (error (progn (widen) (eval cmd))))))
8325 ((string= type "tree-match")
8326 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8328 ((string= type "file")
8329 (if (string-match "::\\([0-9]+\\)\\'" path)
8330 (setq line (string-to-number (match-string 1 path))
8331 path (substring path 0 (match-beginning 0)))
8332 (if (string-match "::\\(.+\\)\\'" path)
8333 (setq search (match-string 1 path)
8334 path (substring path 0 (match-beginning 0)))))
8335 (if (string-match "[*?{]" (file-name-nondirectory path))
8336 (dired path)
8337 (org-open-file path in-emacs line search)))
8339 ((string= type "news")
8340 (require 'org-gnus)
8341 (org-gnus-follow-link path))
8343 ((string= type "shell")
8344 (let ((cmd path))
8345 (if (or (not org-confirm-shell-link-function)
8346 (funcall org-confirm-shell-link-function
8347 (format "Execute \"%s\" in shell? "
8348 (org-add-props cmd nil
8349 'face 'org-warning))))
8350 (progn
8351 (message "Executing %s" cmd)
8352 (shell-command cmd))
8353 (error "Abort"))))
8355 ((string= type "elisp")
8356 (let ((cmd path))
8357 (if (or (not org-confirm-elisp-link-function)
8358 (funcall org-confirm-elisp-link-function
8359 (format "Execute \"%s\" as elisp? "
8360 (org-add-props cmd nil
8361 'face 'org-warning))))
8362 (message "%s => %s" cmd
8363 (if (equal (string-to-char cmd) ?\()
8364 (eval (read cmd))
8365 (call-interactively (read cmd))))
8366 (error "Abort"))))
8369 (browse-url-at-point)))))))
8370 (move-marker org-open-link-marker nil)
8371 (run-hook-with-args 'org-follow-link-hook))
8373 (defun org-offer-links-in-entry (&optional nth zero)
8374 "Offer links in the current entry and follow the selected link.
8375 If there is only one link, follow it immediately as well.
8376 If NTH is an integer, immediately pick the NTH link found.
8377 If ZERO is a string, check also this string for a link, and if
8378 there is one, offer it as link number zero."
8379 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8380 "\\(" org-angle-link-re "\\)\\|"
8381 "\\(" org-plain-link-re "\\)"))
8382 (cnt ?0)
8383 (in-emacs (if (integerp nth) nil nth))
8384 have-zero end links link c)
8385 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8386 (push (match-string 0 zero) links)
8387 (setq cnt (1- cnt) have-zero t))
8388 (save-excursion
8389 (org-back-to-heading t)
8390 (setq end (save-excursion (outline-next-heading) (point)))
8391 (while (re-search-forward re end t)
8392 (push (match-string 0) links))
8393 (setq links (org-uniquify (reverse links))))
8395 (cond
8396 ((null links)
8397 (message "No links"))
8398 ((equal (length links) 1)
8399 (setq link (car links)))
8400 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8401 (setq link (nth (if have-zero nth (1- nth)) links)))
8402 (t ; we have to select a link
8403 (save-excursion
8404 (save-window-excursion
8405 (delete-other-windows)
8406 (with-output-to-temp-buffer "*Select Link*"
8407 (mapc (lambda (l)
8408 (if (not (string-match org-bracket-link-regexp l))
8409 (princ (format "[%c] %s\n" (incf cnt)
8410 (org-remove-angle-brackets l)))
8411 (if (match-end 3)
8412 (princ (format "[%c] %s (%s)\n" (incf cnt)
8413 (match-string 3 l) (match-string 1 l)))
8414 (princ (format "[%c] %s\n" (incf cnt)
8415 (match-string 1 l))))))
8416 links))
8417 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8418 (message "Select link to open:")
8419 (setq c (read-char-exclusive))
8420 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8421 (when (equal c ?q) (error "Abort"))
8422 (setq nth (- c ?0))
8423 (if have-zero (setq nth (1+ nth)))
8424 (unless (and (integerp nth) (>= (length links) nth))
8425 (error "Invalid link selection"))
8426 (setq link (nth (1- nth) links))))
8427 (if link
8428 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8429 nil)))
8431 ;;;; Time estimates
8433 (defun org-get-effort (&optional pom)
8434 "Get the effort estimate for the current entry."
8435 (org-entry-get pom org-effort-property))
8437 ;;; File search
8439 (defvar org-create-file-search-functions nil
8440 "List of functions to construct the right search string for a file link.
8441 These functions are called in turn with point at the location to
8442 which the link should point.
8444 A function in the hook should first test if it would like to
8445 handle this file type, for example by checking the major-mode or
8446 the file extension. If it decides not to handle this file, it
8447 should just return nil to give other functions a chance. If it
8448 does handle the file, it must return the search string to be used
8449 when following the link. The search string will be part of the
8450 file link, given after a double colon, and `org-open-at-point'
8451 will automatically search for it. If special measures must be
8452 taken to make the search successful, another function should be
8453 added to the companion hook `org-execute-file-search-functions',
8454 which see.
8456 A function in this hook may also use `setq' to set the variable
8457 `description' to provide a suggestion for the descriptive text to
8458 be used for this link when it gets inserted into an Org-mode
8459 buffer with \\[org-insert-link].")
8461 (defvar org-execute-file-search-functions nil
8462 "List of functions to execute a file search triggered by a link.
8464 Functions added to this hook must accept a single argument, the
8465 search string that was part of the file link, the part after the
8466 double colon. The function must first check if it would like to
8467 handle this search, for example by checking the major-mode or the
8468 file extension. If it decides not to handle this search, it
8469 should just return nil to give other functions a chance. If it
8470 does handle the search, it must return a non-nil value to keep
8471 other functions from trying.
8473 Each function can access the current prefix argument through the
8474 variable `current-prefix-argument'. Note that a single prefix is
8475 used to force opening a link in Emacs, so it may be good to only
8476 use a numeric or double prefix to guide the search function.
8478 In case this is needed, a function in this hook can also restore
8479 the window configuration before `org-open-at-point' was called using:
8481 (set-window-configuration org-window-config-before-follow-link)")
8483 (defun org-link-search (s &optional type avoid-pos)
8484 "Search for a link search option.
8485 If S is surrounded by forward slashes, it is interpreted as a
8486 regular expression. In org-mode files, this will create an `org-occur'
8487 sparse tree. In ordinary files, `occur' will be used to list matches.
8488 If the current buffer is in `dired-mode', grep will be used to search
8489 in all files. If AVOID-POS is given, ignore matches near that position."
8490 (let ((case-fold-search t)
8491 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8492 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8493 (append '(("") (" ") ("\t") ("\n"))
8494 org-emphasis-alist)
8495 "\\|") "\\)"))
8496 (pos (point))
8497 (pre nil) (post nil)
8498 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8499 (cond
8500 ;; First check if there are any special
8501 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8502 ;; Now try the builtin stuff
8503 ((and (equal (string-to-char s0) ?#)
8504 (> (length s0) 1)
8505 (save-excursion
8506 (goto-char (point-min))
8507 (and
8508 (re-search-forward
8509 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8510 (setq type 'dedicated
8511 pos (match-beginning 0))))
8512 ;; There is an exact target for this
8513 (goto-char pos)
8514 (org-back-to-heading t)))
8515 ((save-excursion
8516 (goto-char (point-min))
8517 (and
8518 (re-search-forward
8519 (concat "<<" (regexp-quote s0) ">>") nil t)
8520 (setq type 'dedicated
8521 pos (match-beginning 0))))
8522 ;; There is an exact target for this
8523 (goto-char pos))
8524 ((and (string-match "^(\\(.*\\))$" s0)
8525 (save-excursion
8526 (goto-char (point-min))
8527 (and
8528 (re-search-forward
8529 (concat "[^[]" (regexp-quote
8530 (format org-coderef-label-format
8531 (match-string 1 s0))))
8532 nil t)
8533 (setq type 'dedicated
8534 pos (1+ (match-beginning 0))))))
8535 ;; There is a coderef target for this
8536 (goto-char pos))
8537 ((string-match "^/\\(.*\\)/$" s)
8538 ;; A regular expression
8539 (cond
8540 ((org-mode-p)
8541 (org-occur (match-string 1 s)))
8542 ;;((eq major-mode 'dired-mode)
8543 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8544 (t (org-do-occur (match-string 1 s)))))
8546 ;; A normal search strings
8547 (when (equal (string-to-char s) ?*)
8548 ;; Anchor on headlines, post may include tags.
8549 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8550 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8551 s (substring s 1)))
8552 (remove-text-properties
8553 0 (length s)
8554 '(face nil mouse-face nil keymap nil fontified nil) s)
8555 ;; Make a series of regular expressions to find a match
8556 (setq words (org-split-string s "[ \n\r\t]+")
8558 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8559 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8560 "\\)" markers)
8561 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8562 re2a (concat "[ \t\r\n]" re2a_)
8563 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8564 re4 (concat "[^a-zA-Z_]" re4_)
8566 re1 (concat pre re2 post)
8567 re3 (concat pre (if pre re4_ re4) post)
8568 re5 (concat pre ".*" re4)
8569 re2 (concat pre re2)
8570 re2a (concat pre (if pre re2a_ re2a))
8571 re4 (concat pre (if pre re4_ re4))
8572 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8573 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8574 re5 "\\)"
8576 (cond
8577 ((eq type 'org-occur) (org-occur reall))
8578 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8579 (t (goto-char (point-min))
8580 (setq type 'fuzzy)
8581 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8582 (org-search-not-self 1 re1 nil t)
8583 (org-search-not-self 1 re2 nil t)
8584 (org-search-not-self 1 re2a nil t)
8585 (org-search-not-self 1 re3 nil t)
8586 (org-search-not-self 1 re4 nil t)
8587 (org-search-not-self 1 re5 nil t)
8589 (goto-char (match-beginning 1))
8590 (goto-char pos)
8591 (error "No match")))))
8593 ;; Normal string-search
8594 (goto-char (point-min))
8595 (if (search-forward s nil t)
8596 (goto-char (match-beginning 0))
8597 (error "No match"))))
8598 (and (org-mode-p) (org-show-context 'link-search))
8599 type))
8601 (defun org-search-not-self (group &rest args)
8602 "Execute `re-search-forward', but only accept matches that do not
8603 enclose the position of `org-open-link-marker'."
8604 (let ((m org-open-link-marker))
8605 (catch 'exit
8606 (while (apply 're-search-forward args)
8607 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8608 (goto-char (match-end group))
8609 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8610 (> (match-beginning 0) (marker-position m))
8611 (< (match-end 0) (marker-position m)))
8612 (save-match-data
8613 (or (not (org-in-regexp
8614 org-bracket-link-analytic-regexp 1))
8615 (not (match-end 4)) ; no description
8616 (and (<= (match-beginning 4) (point))
8617 (>= (match-end 4) (point))))))
8618 (throw 'exit (point))))))))
8620 (defun org-get-buffer-for-internal-link (buffer)
8621 "Return a buffer to be used for displaying the link target of internal links."
8622 (cond
8623 ((not org-display-internal-link-with-indirect-buffer)
8624 buffer)
8625 ((string-match "(Clone)$" (buffer-name buffer))
8626 (message "Buffer is already a clone, not making another one")
8627 ;; we also do not modify visibility in this case
8628 buffer)
8629 (t ; make a new indirect buffer for displaying the link
8630 (let* ((bn (buffer-name buffer))
8631 (ibn (concat bn "(Clone)"))
8632 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8633 (with-current-buffer ib (org-overview))
8634 ib))))
8636 (defun org-do-occur (regexp &optional cleanup)
8637 "Call the Emacs command `occur'.
8638 If CLEANUP is non-nil, remove the printout of the regular expression
8639 in the *Occur* buffer. This is useful if the regex is long and not useful
8640 to read."
8641 (occur regexp)
8642 (when cleanup
8643 (let ((cwin (selected-window)) win beg end)
8644 (when (setq win (get-buffer-window "*Occur*"))
8645 (select-window win))
8646 (goto-char (point-min))
8647 (when (re-search-forward "match[a-z]+" nil t)
8648 (setq beg (match-end 0))
8649 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8650 (setq end (1- (match-beginning 0)))))
8651 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8652 (goto-char (point-min))
8653 (select-window cwin))))
8655 ;;; The mark ring for links jumps
8657 (defvar org-mark-ring nil
8658 "Mark ring for positions before jumps in Org-mode.")
8659 (defvar org-mark-ring-last-goto nil
8660 "Last position in the mark ring used to go back.")
8661 ;; Fill and close the ring
8662 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8663 (loop for i from 1 to org-mark-ring-length do
8664 (push (make-marker) org-mark-ring))
8665 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8666 org-mark-ring)
8668 (defun org-mark-ring-push (&optional pos buffer)
8669 "Put the current position or POS into the mark ring and rotate it."
8670 (interactive)
8671 (setq pos (or pos (point)))
8672 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8673 (move-marker (car org-mark-ring)
8674 (or pos (point))
8675 (or buffer (current-buffer)))
8676 (message "%s"
8677 (substitute-command-keys
8678 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8680 (defun org-mark-ring-goto (&optional n)
8681 "Jump to the previous position in the mark ring.
8682 With prefix arg N, jump back that many stored positions. When
8683 called several times in succession, walk through the entire ring.
8684 Org-mode commands jumping to a different position in the current file,
8685 or to another Org-mode file, automatically push the old position
8686 onto the ring."
8687 (interactive "p")
8688 (let (p m)
8689 (if (eq last-command this-command)
8690 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8691 (setq p org-mark-ring))
8692 (setq org-mark-ring-last-goto p)
8693 (setq m (car p))
8694 (switch-to-buffer (marker-buffer m))
8695 (goto-char m)
8696 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8698 (defun org-remove-angle-brackets (s)
8699 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8700 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8702 (defun org-add-angle-brackets (s)
8703 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8704 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8706 (defun org-remove-double-quotes (s)
8707 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8708 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8711 ;;; Following specific links
8713 (defun org-follow-timestamp-link ()
8714 (cond
8715 ((org-at-date-range-p t)
8716 (let ((org-agenda-start-on-weekday)
8717 (t1 (match-string 1))
8718 (t2 (match-string 2)))
8719 (setq t1 (time-to-days (org-time-string-to-time t1))
8720 t2 (time-to-days (org-time-string-to-time t2)))
8721 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8722 ((org-at-timestamp-p t)
8723 (org-agenda-list nil (time-to-days (org-time-string-to-time
8724 (substring (match-string 1) 0 10)))
8726 (t (error "This should not happen"))))
8729 ;;; Following file links
8730 (defvar org-wait nil)
8731 (defun org-open-file (path &optional in-emacs line search)
8732 "Open the file at PATH.
8733 First, this expands any special file name abbreviations. Then the
8734 configuration variable `org-file-apps' is checked if it contains an
8735 entry for this file type, and if yes, the corresponding command is launched.
8737 If no application is found, Emacs simply visits the file.
8739 With optional prefix argument IN-EMACS, Emacs will visit the file.
8740 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8741 and o use an external application to visit the file.
8743 Optional LINE specifies a line to go to, optional SEARCH a string to
8744 search for. If LINE or SEARCH is given, the file will always be
8745 opened in Emacs.
8746 If the file does not exist, an error is thrown."
8747 (setq in-emacs (or in-emacs line search))
8748 (let* ((file (if (equal path "")
8749 buffer-file-name
8750 (substitute-in-file-name (expand-file-name path))))
8751 (apps (append org-file-apps (org-default-apps)))
8752 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8753 (dirp (if remp nil (file-directory-p file)))
8754 (file (if (and dirp org-open-directory-means-index-dot-org)
8755 (concat (file-name-as-directory file) "index.org")
8756 file))
8757 (a-m-a-p (assq 'auto-mode apps))
8758 (dfile (downcase file))
8759 (old-buffer (current-buffer))
8760 (old-pos (point))
8761 (old-mode major-mode)
8762 ext cmd)
8763 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8764 (setq ext (match-string 1 dfile))
8765 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8766 (setq ext (match-string 1 dfile))))
8767 (cond
8768 ((equal in-emacs '(16))
8769 (setq cmd (cdr (assoc 'system apps))))
8770 (in-emacs (setq cmd 'emacs))
8772 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8773 (and dirp (cdr (assoc 'directory apps)))
8774 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8775 'string-match)
8776 (cdr (assoc ext apps))
8777 (cdr (assoc t apps))))))
8778 (when (eq cmd 'system)
8779 (setq cmd (cdr (assoc 'system apps))))
8780 (when (eq cmd 'default)
8781 (setq cmd (cdr (assoc t apps))))
8782 (when (eq cmd 'mailcap)
8783 (require 'mailcap)
8784 (mailcap-parse-mailcaps)
8785 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8786 (command (mailcap-mime-info mime-type)))
8787 (if (stringp command)
8788 (setq cmd command)
8789 (setq cmd 'emacs))))
8790 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8791 (not (file-exists-p file))
8792 (not org-open-non-existing-files))
8793 (error "No such file: %s" file))
8794 (cond
8795 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8796 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8797 (while (string-match "['\"]%s['\"]" cmd)
8798 (setq cmd (replace-match "%s" t t cmd)))
8799 (while (string-match "%s" cmd)
8800 (setq cmd (replace-match
8801 (save-match-data
8802 (shell-quote-argument
8803 (convert-standard-filename file)))
8804 t t cmd)))
8805 (save-window-excursion
8806 (start-process-shell-command cmd nil cmd)
8807 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8809 ((or (stringp cmd)
8810 (eq cmd 'emacs))
8811 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8812 (widen)
8813 (if line (org-goto-line line)
8814 (if search (org-link-search search))))
8815 ((consp cmd)
8816 (let ((file (convert-standard-filename file)))
8817 (eval cmd)))
8818 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8819 (and (org-mode-p) (eq old-mode 'org-mode)
8820 (or (not (equal old-buffer (current-buffer)))
8821 (not (equal old-pos (point))))
8822 (org-mark-ring-push old-pos old-buffer))))
8824 (defun org-default-apps ()
8825 "Return the default applications for this operating system."
8826 (cond
8827 ((eq system-type 'darwin)
8828 org-file-apps-defaults-macosx)
8829 ((eq system-type 'windows-nt)
8830 org-file-apps-defaults-windowsnt)
8831 (t org-file-apps-defaults-gnu)))
8833 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8834 "Convert extensions to regular expressions in the cars of LIST.
8835 Also, weed out any non-string entries, because the return value is used
8836 only for regexp matching.
8837 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8838 point to the symbol `emacs', indicating that the file should
8839 be opened in Emacs."
8840 (append
8841 (delq nil
8842 (mapcar (lambda (x)
8843 (if (not (stringp (car x)))
8845 (if (string-match "\\W" (car x))
8847 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8848 list))
8849 (if add-auto-mode
8850 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8852 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8853 (defun org-file-remote-p (file)
8854 "Test whether FILE specifies a location on a remote system.
8855 Return non-nil if the location is indeed remote.
8857 For example, the filename \"/user@host:/foo\" specifies a location
8858 on the system \"/user@host:\"."
8859 (cond ((fboundp 'file-remote-p)
8860 (file-remote-p file))
8861 ((fboundp 'tramp-handle-file-remote-p)
8862 (tramp-handle-file-remote-p file))
8863 ((and (boundp 'ange-ftp-name-format)
8864 (string-match (car ange-ftp-name-format) file))
8866 (t nil)))
8869 ;;;; Refiling
8871 (defun org-get-org-file ()
8872 "Read a filename, with default directory `org-directory'."
8873 (let ((default (or org-default-notes-file remember-data-file)))
8874 (read-file-name (format "File name [%s]: " default)
8875 (file-name-as-directory org-directory)
8876 default)))
8878 (defun org-notes-order-reversed-p ()
8879 "Check if the current file should receive notes in reversed order."
8880 (cond
8881 ((not org-reverse-note-order) nil)
8882 ((eq t org-reverse-note-order) t)
8883 ((not (listp org-reverse-note-order)) nil)
8884 (t (catch 'exit
8885 (let ((all org-reverse-note-order)
8886 entry)
8887 (while (setq entry (pop all))
8888 (if (string-match (car entry) buffer-file-name)
8889 (throw 'exit (cdr entry))))
8890 nil)))))
8892 (defvar org-refile-target-table nil
8893 "The list of refile targets, created by `org-refile'.")
8895 (defvar org-agenda-new-buffers nil
8896 "Buffers created to visit agenda files.")
8898 (defun org-get-refile-targets (&optional default-buffer)
8899 "Produce a table with refile targets."
8900 (let ((case-fold-search nil)
8901 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8902 (entries (or org-refile-targets '((nil . (:level . 1)))))
8903 targets txt re files f desc descre fast-path-p level pos0)
8904 (message "Getting targets...")
8905 (with-current-buffer (or default-buffer (current-buffer))
8906 (while (setq entry (pop entries))
8907 (setq files (car entry) desc (cdr entry))
8908 (setq fast-path-p nil)
8909 (cond
8910 ((null files) (setq files (list (current-buffer))))
8911 ((eq files 'org-agenda-files)
8912 (setq files (org-agenda-files 'unrestricted)))
8913 ((and (symbolp files) (fboundp files))
8914 (setq files (funcall files)))
8915 ((and (symbolp files) (boundp files))
8916 (setq files (symbol-value files))))
8917 (if (stringp files) (setq files (list files)))
8918 (cond
8919 ((eq (car desc) :tag)
8920 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8921 ((eq (car desc) :todo)
8922 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8923 ((eq (car desc) :regexp)
8924 (setq descre (cdr desc)))
8925 ((eq (car desc) :level)
8926 (setq descre (concat "^\\*\\{" (number-to-string
8927 (if org-odd-levels-only
8928 (1- (* 2 (cdr desc)))
8929 (cdr desc)))
8930 "\\}[ \t]")))
8931 ((eq (car desc) :maxlevel)
8932 (setq fast-path-p t)
8933 (setq descre (concat "^\\*\\{1," (number-to-string
8934 (if org-odd-levels-only
8935 (1- (* 2 (cdr desc)))
8936 (cdr desc)))
8937 "\\}[ \t]")))
8938 (t (error "Bad refiling target description %s" desc)))
8939 (while (setq f (pop files))
8940 (with-current-buffer
8941 (if (bufferp f) f (org-get-agenda-file-buffer f))
8942 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8943 (setq f (expand-file-name f))
8944 (if (eq org-refile-use-outline-path 'file)
8945 (push (list (file-name-nondirectory f) f nil nil) targets))
8946 (save-excursion
8947 (save-restriction
8948 (widen)
8949 (goto-char (point-min))
8950 (while (re-search-forward descre nil t)
8951 (goto-char (setq pos0 (point-at-bol)))
8952 (catch 'next
8953 (when org-refile-target-verify-function
8954 (save-match-data
8955 (or (funcall org-refile-target-verify-function)
8956 (throw 'next t))))
8957 (when (looking-at org-complex-heading-regexp)
8958 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8959 txt (org-link-display-format (match-string 4))
8960 re (concat "^" (regexp-quote
8961 (buffer-substring (match-beginning 1)
8962 (match-end 4)))))
8963 (if (match-end 5) (setq re (concat re "[ \t]+"
8964 (regexp-quote
8965 (match-string 5)))))
8966 (setq re (concat re "[ \t]*$"))
8967 (when org-refile-use-outline-path
8968 (setq txt (mapconcat 'org-protect-slash
8969 (append
8970 (if (eq org-refile-use-outline-path 'file)
8971 (list (file-name-nondirectory
8972 (buffer-file-name (buffer-base-buffer))))
8973 (if (eq org-refile-use-outline-path 'full-file-path)
8974 (list (buffer-file-name (buffer-base-buffer)))))
8975 (org-get-outline-path fast-path-p level txt)
8976 (list txt))
8977 "/")))
8978 (push (list txt f re (point)) targets)))
8979 (when (= (point) pos0)
8980 ;; verification function has not moved point
8981 (goto-char (point-at-eol))))))))))
8982 (message "Getting targets...done")
8983 (nreverse targets)))
8985 (defun org-protect-slash (s)
8986 (while (string-match "/" s)
8987 (setq s (replace-match "\\" t t s)))
8990 (defvar org-olpa (make-vector 20 nil))
8992 (defun org-get-outline-path (&optional fastp level heading)
8993 "Return the outline path to the current entry, as a list.
8994 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
8995 routine which makes outline path derivations for an entire file,
8996 avoiding backtracing."
8997 (if fastp
8998 (progn
8999 (if (> level 19)
9000 (error "Outline path failure, more than 19 levels."))
9001 (loop for i from level upto 19 do
9002 (aset org-olpa i nil))
9003 (prog1
9004 (delq nil (append org-olpa nil))
9005 (aset org-olpa level heading)))
9006 (let (rtn)
9007 (save-excursion
9008 (while (org-up-heading-safe)
9009 (when (looking-at org-complex-heading-regexp)
9010 (push (org-match-string-no-properties 4) rtn)))
9011 rtn))))
9013 (defun org-format-outline-path (path &optional width prefix)
9014 "Format the outlie path PATH for display.
9015 Width is the maximum number of characters that is available.
9016 Prefix is a prefix to be included in the returned string,
9017 such as the file name."
9018 (setq width (or width 79))
9019 (if prefix (setq width (- width (length prefix))))
9020 (if (not path)
9021 (or prefix "")
9022 (let* ((nsteps (length path))
9023 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9024 (maxwidth (if (<= total-width width)
9025 10000 ;; everything fits
9026 ;; we need to shorten the level headings
9027 (/ (- width nsteps) nsteps)))
9028 (org-odd-levels-only nil)
9029 (n 0)
9030 (total (1+ (length prefix))))
9031 (setq maxwidth (max maxwidth 10))
9032 (concat prefix
9033 (mapconcat
9034 (lambda (h)
9035 (setq n (1+ n))
9036 (if (and (= n nsteps) (< maxwidth 10000))
9037 (setq maxwidth (- total-width total)))
9038 (if (< (length h) maxwidth)
9039 (progn (setq total (+ total (length h) 1)) h)
9040 (setq h (substring h 0 (- maxwidth 2))
9041 total (+ total maxwidth 1))
9042 (if (string-match "[ \t]+\\'" h)
9043 (setq h (substring h 0 (match-beginning 0))))
9044 (setq h (concat h "..")))
9045 (org-add-props h nil 'face
9046 (nth (% (1- n) org-n-level-faces)
9047 org-level-faces))
9049 path "/")))))
9051 (defun org-display-outline-path (&optional file current)
9052 "Display the current outline path in the echo area."
9053 (interactive "P")
9054 (let ((bfn (buffer-file-name (buffer-base-buffer)))
9055 (path (and (org-mode-p) (org-get-outline-path))))
9056 (if current (setq path (append path
9057 (save-excursion
9058 (org-back-to-heading t)
9059 (if (looking-at org-complex-heading-regexp)
9060 (list (match-string 4)))))))
9061 (message (org-format-outline-path
9062 path
9063 (1- (frame-width))
9064 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9066 (defvar org-refile-history nil
9067 "History for refiling operations.")
9069 (defvar org-after-refile-insert-hook nil
9070 "Hook run after `org-refile' has inserted its stuff at the new location.
9071 Note that this is still *before* the stuff will be removed from
9072 the *old* location.")
9074 (defun org-refile (&optional goto default-buffer rfloc)
9075 "Move the entry at point to another heading.
9076 The list of target headings is compiled using the information in
9077 `org-refile-targets', which see. This list is created before each use
9078 and will therefore always be up-to-date.
9080 At the target location, the entry is filed as a subitem of the target heading.
9081 Depending on `org-reverse-note-order', the new subitem will either be the
9082 first or the last subitem.
9084 If there is an active region, all entries in that region will be moved.
9085 However, the region must fulfil the requirement that the first heading
9086 is the first one sets the top-level of the moved text - at most siblings
9087 below it are allowed.
9089 With prefix arg GOTO, the command will only visit the target location,
9090 not actually move anything.
9091 With a double prefix `C-u C-u', go to the location where the last refiling
9092 operation has put the subtree.
9093 With a prefix argument of `2', refile to the running clock.
9095 RFLOC can be a refile location obtained in a different way.
9097 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9098 (interactive "P")
9099 (let* ((cbuf (current-buffer))
9100 (regionp (org-region-active-p))
9101 (region-start (and regionp (region-beginning)))
9102 (region-end (and regionp (region-end)))
9103 (region-length (and regionp (- region-end region-start)))
9104 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9105 pos it nbuf file re level reversed)
9106 (setq last-command nil)
9107 (when regionp
9108 (goto-char region-start)
9109 (or (bolp) (goto-char (point-at-bol)))
9110 (setq region-start (point))
9111 (unless (org-kill-is-subtree-p
9112 (buffer-substring region-start region-end))
9113 (error "The region is not a (sequence of) subtree(s)")))
9114 (if (equal goto '(16))
9115 (org-refile-goto-last-stored)
9116 (when (or
9117 (and (equal goto 2)
9118 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9119 (prog1
9120 (setq it (list (or org-clock-heading "running clock")
9121 (buffer-file-name
9122 (marker-buffer org-clock-hd-marker))
9124 (marker-position org-clock-hd-marker)))
9125 (setq goto nil)))
9126 (setq it (or rfloc
9127 (save-excursion
9128 (org-refile-get-location
9129 (if goto "Goto: " "Refile to: ") default-buffer
9130 org-refile-allow-creating-parent-nodes)))))
9131 (setq file (nth 1 it)
9132 re (nth 2 it)
9133 pos (nth 3 it))
9134 (if (and (not goto)
9136 (equal (buffer-file-name) file)
9137 (if regionp
9138 (and (>= pos region-start)
9139 (<= pos region-end))
9140 (and (>= pos (point))
9141 (< pos (save-excursion
9142 (org-end-of-subtree t t))))))
9143 (error "Cannot refile to position inside the tree or region"))
9145 (setq nbuf (or (find-buffer-visiting file)
9146 (find-file-noselect file)))
9147 (if goto
9148 (progn
9149 (switch-to-buffer nbuf)
9150 (goto-char pos)
9151 (org-show-context 'org-goto))
9152 (if regionp
9153 (progn
9154 (org-kill-new (buffer-substring region-start region-end))
9155 (org-save-markers-in-region region-start region-end))
9156 (org-copy-subtree 1 nil t))
9157 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9158 (find-file-noselect file)))
9159 (setq reversed (org-notes-order-reversed-p))
9160 (save-excursion
9161 (save-restriction
9162 (widen)
9163 (if pos
9164 (progn
9165 (goto-char pos)
9166 (looking-at outline-regexp)
9167 (setq level (org-get-valid-level (funcall outline-level) 1))
9168 (goto-char
9169 (if reversed
9170 (or (outline-next-heading) (point-max))
9171 (or (save-excursion (org-get-next-sibling))
9172 (org-end-of-subtree t t)
9173 (point-max)))))
9174 (setq level 1)
9175 (if (not reversed)
9176 (goto-char (point-max))
9177 (goto-char (point-min))
9178 (or (outline-next-heading) (goto-char (point-max)))))
9179 (if (not (bolp)) (newline))
9180 (bookmark-set "org-refile-last-stored")
9181 (org-paste-subtree level)
9182 (if (fboundp 'deactivate-mark) (deactivate-mark))
9183 (run-hooks 'org-after-refile-insert-hook))))
9184 (if regionp
9185 (delete-region (point) (+ (point) region-length))
9186 (org-cut-subtree))
9187 (when (featurep 'org-inlinetask)
9188 (org-inlinetask-remove-END-maybe))
9189 (setq org-markers-to-move nil)
9190 (message "Refiled to \"%s\"" (car it))))))
9191 (org-reveal))
9193 (defun org-refile-goto-last-stored ()
9194 "Go to the location where the last refile was stored."
9195 (interactive)
9196 (bookmark-jump "org-refile-last-stored")
9197 (message "This is the location of the last refile"))
9199 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9200 "Prompt the user for a refile location, using PROMPT."
9201 (let ((org-refile-targets org-refile-targets)
9202 (org-refile-use-outline-path org-refile-use-outline-path))
9203 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9204 (unless org-refile-target-table
9205 (error "No refile targets"))
9206 (let* ((cbuf (current-buffer))
9207 (partial-completion-mode nil)
9208 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9209 (cfunc (if (and org-refile-use-outline-path
9210 org-outline-path-complete-in-steps)
9211 'org-olpath-completing-read
9212 'org-icompleting-read))
9213 (extra (if org-refile-use-outline-path "/" ""))
9214 (filename (and cfn (expand-file-name cfn)))
9215 (tbl (mapcar
9216 (lambda (x)
9217 (if (and (not (member org-refile-use-outline-path
9218 '(file full-file-path)))
9219 (not (equal filename (nth 1 x))))
9220 (cons (concat (car x) extra " ("
9221 (file-name-nondirectory (nth 1 x)) ")")
9222 (cdr x))
9223 (cons (concat (car x) extra) (cdr x))))
9224 org-refile-target-table))
9225 (completion-ignore-case t)
9226 pa answ parent-target child parent old-hist)
9227 (setq old-hist org-refile-history)
9228 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9229 nil 'org-refile-history))
9230 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9231 (if pa
9232 (progn
9233 (when (or (not org-refile-history)
9234 (not (eq old-hist org-refile-history))
9235 (not (equal (car pa) (car org-refile-history))))
9236 (setq org-refile-history
9237 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9238 org-refile-history
9239 (cdr org-refile-history))))
9240 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9241 (pop org-refile-history)))
9243 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9244 (setq parent (match-string 1 answ)
9245 child (match-string 2 answ))
9246 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9247 (when (and parent-target
9248 (or (eq new-nodes t)
9249 (and (eq new-nodes 'confirm)
9250 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9251 (org-refile-new-child parent-target child))))))
9253 (defun org-refile-new-child (parent-target child)
9254 "Use refile target PARENT-TARGET to add new CHILD below it."
9255 (unless parent-target
9256 (error "Cannot find parent for new node"))
9257 (let ((file (nth 1 parent-target))
9258 (pos (nth 3 parent-target))
9259 level)
9260 (with-current-buffer (or (find-buffer-visiting file)
9261 (find-file-noselect file))
9262 (save-excursion
9263 (save-restriction
9264 (widen)
9265 (if pos
9266 (goto-char pos)
9267 (goto-char (point-max))
9268 (if (not (bolp)) (newline)))
9269 (when (looking-at outline-regexp)
9270 (setq level (funcall outline-level))
9271 (org-end-of-subtree t t))
9272 (org-back-over-empty-lines)
9273 (insert "\n" (make-string
9274 (if pos (org-get-valid-level level 1) 1) ?*)
9275 " " child "\n")
9276 (beginning-of-line 0)
9277 (list (concat (car parent-target) "/" child) file "" (point)))))))
9279 (defun org-olpath-completing-read (prompt collection &rest args)
9280 "Read an outline path like a file name."
9281 (let ((thetable collection)
9282 (org-completion-use-ido nil) ; does not work with ido.
9283 (org-completion-use-iswitchb nil)) ; or iswitchb
9284 (apply
9285 'org-icompleting-read prompt
9286 (lambda (string predicate &optional flag)
9287 (let (rtn r f (l (length string)))
9288 (cond
9289 ((eq flag nil)
9290 ;; try completion
9291 (try-completion string thetable))
9292 ((eq flag t)
9293 ;; all-completions
9294 (setq rtn (all-completions string thetable predicate))
9295 (mapcar
9296 (lambda (x)
9297 (setq r (substring x l))
9298 (if (string-match " ([^)]*)$" x)
9299 (setq f (match-string 0 x))
9300 (setq f ""))
9301 (if (string-match "/" r)
9302 (concat string (substring r 0 (match-end 0)) f)
9304 rtn))
9305 ((eq flag 'lambda)
9306 ;; exact match?
9307 (assoc string thetable)))
9309 args)))
9311 ;;;; Dynamic blocks
9313 (defun org-find-dblock (name)
9314 "Find the first dynamic block with name NAME in the buffer.
9315 If not found, stay at current position and return nil."
9316 (let (pos)
9317 (save-excursion
9318 (goto-char (point-min))
9319 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9320 nil t)
9321 (match-beginning 0))))
9322 (if pos (goto-char pos))
9323 pos))
9325 (defconst org-dblock-start-re
9326 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9327 "Matches the start line of a dynamic block, with parameters.")
9329 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9330 "Matches the end of a dynamic block.")
9332 (defun org-create-dblock (plist)
9333 "Create a dynamic block section, with parameters taken from PLIST.
9334 PLIST must contain a :name entry which is used as name of the block."
9335 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9336 (end-of-line 1)
9337 (newline))
9338 (let ((col (current-column))
9339 (name (plist-get plist :name)))
9340 (insert "#+BEGIN: " name)
9341 (while plist
9342 (if (eq (car plist) :name)
9343 (setq plist (cddr plist))
9344 (insert " " (prin1-to-string (pop plist)))))
9345 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9346 (beginning-of-line -2)))
9348 (defun org-prepare-dblock ()
9349 "Prepare dynamic block for refresh.
9350 This empties the block, puts the cursor at the insert position and returns
9351 the property list including an extra property :name with the block name."
9352 (unless (looking-at org-dblock-start-re)
9353 (error "Not at a dynamic block"))
9354 (let* ((begdel (1+ (match-end 0)))
9355 (name (org-no-properties (match-string 1)))
9356 (params (append (list :name name)
9357 (read (concat "(" (match-string 3) ")")))))
9358 (save-excursion
9359 (beginning-of-line 1)
9360 (skip-chars-forward " \t")
9361 (setq params (plist-put params :indentation-column (current-column))))
9362 (unless (re-search-forward org-dblock-end-re nil t)
9363 (error "Dynamic block not terminated"))
9364 (setq params
9365 (append params
9366 (list :content (buffer-substring
9367 begdel (match-beginning 0)))))
9368 (delete-region begdel (match-beginning 0))
9369 (goto-char begdel)
9370 (open-line 1)
9371 params))
9373 (defun org-map-dblocks (&optional command)
9374 "Apply COMMAND to all dynamic blocks in the current buffer.
9375 If COMMAND is not given, use `org-update-dblock'."
9376 (let ((cmd (or command 'org-update-dblock))
9377 pos)
9378 (save-excursion
9379 (goto-char (point-min))
9380 (while (re-search-forward org-dblock-start-re nil t)
9381 (goto-char (setq pos (match-beginning 0)))
9382 (condition-case nil
9383 (funcall cmd)
9384 (error (message "Error during update of dynamic block")))
9385 (goto-char pos)
9386 (unless (re-search-forward org-dblock-end-re nil t)
9387 (error "Dynamic block not terminated"))))))
9389 (defun org-dblock-update (&optional arg)
9390 "User command for updating dynamic blocks.
9391 Update the dynamic block at point. With prefix ARG, update all dynamic
9392 blocks in the buffer."
9393 (interactive "P")
9394 (if arg
9395 (org-update-all-dblocks)
9396 (or (looking-at org-dblock-start-re)
9397 (org-beginning-of-dblock))
9398 (org-update-dblock)))
9400 (defun org-update-dblock ()
9401 "Update the dynamic block at point
9402 This means to empty the block, parse for parameters and then call
9403 the correct writing function."
9404 (save-window-excursion
9405 (let* ((pos (point))
9406 (line (org-current-line))
9407 (params (org-prepare-dblock))
9408 (name (plist-get params :name))
9409 (indent (plist-get params :indentation-column))
9410 (cmd (intern (concat "org-dblock-write:" name))))
9411 (message "Updating dynamic block `%s' at line %d..." name line)
9412 (funcall cmd params)
9413 (message "Updating dynamic block `%s' at line %d...done" name line)
9414 (goto-char pos)
9415 (when (and indent (> indent 0))
9416 (setq indent (make-string indent ?\ ))
9417 (save-excursion
9418 (org-beginning-of-dblock)
9419 (forward-line 1)
9420 (while (not (looking-at org-dblock-end-re))
9421 (insert indent)
9422 (beginning-of-line 2))
9423 (when (looking-at org-dblock-end-re)
9424 (and (looking-at "[ \t]+")
9425 (replace-match ""))
9426 (insert indent)))))))
9428 (defun org-beginning-of-dblock ()
9429 "Find the beginning of the dynamic block at point.
9430 Error if there is no such block at point."
9431 (let ((pos (point))
9432 beg)
9433 (end-of-line 1)
9434 (if (and (re-search-backward org-dblock-start-re nil t)
9435 (setq beg (match-beginning 0))
9436 (re-search-forward org-dblock-end-re nil t)
9437 (> (match-end 0) pos))
9438 (goto-char beg)
9439 (goto-char pos)
9440 (error "Not in a dynamic block"))))
9442 (defun org-update-all-dblocks ()
9443 "Update all dynamic blocks in the buffer.
9444 This function can be used in a hook."
9445 (when (org-mode-p)
9446 (org-map-dblocks 'org-update-dblock)))
9449 ;;;; Completion
9451 (defconst org-additional-option-like-keywords
9452 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9453 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9454 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "LATEX_CLASS:" "ATTR_LaTeX"
9455 "BEGIN:" "END:"
9456 "ORGTBL" "TBLFM:" "TBLNAME:"
9457 "BEGIN_EXAMPLE" "END_EXAMPLE"
9458 "BEGIN_QUOTE" "END_QUOTE"
9459 "BEGIN_VERSE" "END_VERSE"
9460 "BEGIN_CENTER" "END_CENTER"
9461 "BEGIN_SRC" "END_SRC"
9462 "CATEGORY" "COLUMNS"
9463 "CAPTION" "LABEL"
9464 "SETUPFILE"
9465 "BIND"
9466 "MACRO"))
9468 (defcustom org-structure-template-alist
9470 ("s" "#+begin_src ?\n\n#+end_src"
9471 "<src lang=\"?\">\n\n</src>")
9472 ("e" "#+begin_example\n?\n#+end_example"
9473 "<example>\n?\n</example>")
9474 ("q" "#+begin_quote\n?\n#+end_quote"
9475 "<quote>\n?\n</quote>")
9476 ("v" "#+begin_verse\n?\n#+end_verse"
9477 "<verse>\n?\n/verse>")
9478 ("c" "#+begin_center\n?\n#+end_center"
9479 "<center>\n?\n/center>")
9480 ("l" "#+begin_latex\n?\n#+end_latex"
9481 "<literal style=\"latex\">\n?\n</literal>")
9482 ("L" "#+latex: "
9483 "<literal style=\"latex\">?</literal>")
9484 ("h" "#+begin_html\n?\n#+end_html"
9485 "<literal style=\"html\">\n?\n</literal>")
9486 ("H" "#+html: "
9487 "<literal style=\"html\">?</literal>")
9488 ("a" "#+begin_ascii\n?\n#+end_ascii")
9489 ("A" "#+ascii: ")
9490 ("i" "#+include %file ?"
9491 "<include file=%file markup=\"?\">")
9493 "Structure completion elements.
9494 This is a list of abbreviation keys and values. The value gets inserted
9495 it you type @samp{.} followed by the key and then the completion key,
9496 usually `M-TAB'. %file will be replaced by a file name after prompting
9497 for the file using completion.
9498 There are two templates for each key, the first uses the original Org syntax,
9499 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9500 the default when the /org-mtags.el/ module has been loaded. See also the
9501 variable `org-mtags-prefer-muse-templates'.
9502 This is an experimental feature, it is undecided if it is going to stay in."
9503 :group 'org-completion
9504 :type '(repeat
9505 (string :tag "Key")
9506 (string :tag "Template")
9507 (string :tag "Muse Template")))
9509 (defun org-try-structure-completion ()
9510 "Try to complete a structure template before point.
9511 This looks for strings like \"<e\" on an otherwise empty line and
9512 expands them."
9513 (let ((l (buffer-substring (point-at-bol) (point)))
9515 (when (and (looking-at "[ \t]*$")
9516 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9517 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9518 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9519 (match-beginning 1)) a)
9520 t)))
9522 (defun org-complete-expand-structure-template (start cell)
9523 "Expand a structure template."
9524 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9525 (rpl (nth (if musep 2 1) cell))
9526 (ind ""))
9527 (delete-region start (point))
9528 (when (string-match "\\`#\\+" rpl)
9529 (cond
9530 ((bolp))
9531 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9532 (setq ind (buffer-substring (point-at-bol) (point))))
9533 (t (newline))))
9534 (setq start (point))
9535 (if (string-match "%file" rpl)
9536 (setq rpl (replace-match
9537 (concat
9538 "\""
9539 (save-match-data
9540 (abbreviate-file-name (read-file-name "Include file: ")))
9541 "\"")
9542 t t rpl)))
9543 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9544 (concat "\n" ind)))
9545 (insert rpl)
9546 (if (re-search-backward "\\?" start t) (delete-char 1))))
9549 (defun org-complete (&optional arg)
9550 "Perform completion on word at point.
9551 At the beginning of a headline, this completes TODO keywords as given in
9552 `org-todo-keywords'.
9553 If the current word is preceded by a backslash, completes the TeX symbols
9554 that are supported for HTML support.
9555 If the current word is preceded by \"#+\", completes special words for
9556 setting file options.
9557 In the line after \"#+STARTUP:, complete valid keywords.\"
9558 At all other locations, this simply calls the value of
9559 `org-completion-fallback-command'."
9560 (interactive "P")
9561 (org-without-partial-completion
9562 (catch 'exit
9563 (let* ((a nil)
9564 (end (point))
9565 (beg1 (save-excursion
9566 (skip-chars-backward (org-re "[:alnum:]_@"))
9567 (point)))
9568 (beg (save-excursion
9569 (skip-chars-backward "a-zA-Z0-9_:$")
9570 (point)))
9571 (confirm (lambda (x) (stringp (car x))))
9572 (searchhead (equal (char-before beg) ?*))
9573 (struct
9574 (when (and (member (char-before beg1) '(?. ?<))
9575 (setq a (assoc (buffer-substring beg1 (point))
9576 org-structure-template-alist)))
9577 (org-complete-expand-structure-template (1- beg1) a)
9578 (throw 'exit t)))
9579 (tag (and (equal (char-before beg1) ?:)
9580 (equal (char-after (point-at-bol)) ?*)))
9581 (prop (and (equal (char-before beg1) ?:)
9582 (not (equal (char-after (point-at-bol)) ?*))))
9583 (texp (equal (char-before beg) ?\\))
9584 (link (equal (char-before beg) ?\[))
9585 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9586 beg)
9587 "#+"))
9588 (startup (string-match "^#\\+STARTUP:.*"
9589 (buffer-substring (point-at-bol) (point))))
9590 (completion-ignore-case opt)
9591 (type nil)
9592 (tbl nil)
9593 (table (cond
9594 (opt
9595 (setq type :opt)
9596 (require 'org-exp)
9597 (append
9598 (delq nil
9599 (mapcar
9600 (lambda (x)
9601 (if (string-match
9602 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9603 (cons (match-string 2 x)
9604 (match-string 1 x))))
9605 (org-split-string (org-get-current-options) "\n")))
9606 (mapcar 'list org-additional-option-like-keywords)))
9607 (startup
9608 (setq type :startup)
9609 org-startup-options)
9610 (link (append org-link-abbrev-alist-local
9611 org-link-abbrev-alist))
9612 (texp
9613 (setq type :tex)
9614 org-html-entities)
9615 ((string-match "\\`\\*+[ \t]+\\'"
9616 (buffer-substring (point-at-bol) beg))
9617 (setq type :todo)
9618 (mapcar 'list org-todo-keywords-1))
9619 (searchhead
9620 (setq type :searchhead)
9621 (save-excursion
9622 (goto-char (point-min))
9623 (while (re-search-forward org-todo-line-regexp nil t)
9624 (push (list
9625 (org-make-org-heading-search-string
9626 (match-string 3) t))
9627 tbl)))
9628 tbl)
9629 (tag (setq type :tag beg beg1)
9630 (or org-tag-alist (org-get-buffer-tags)))
9631 (prop (setq type :prop beg beg1)
9632 (mapcar 'list (org-buffer-property-keys nil t t)))
9633 (t (progn
9634 (call-interactively org-completion-fallback-command)
9635 (throw 'exit nil)))))
9636 (pattern (buffer-substring-no-properties beg end))
9637 (completion (try-completion pattern table confirm)))
9638 (cond ((eq completion t)
9639 (if (not (assoc (upcase pattern) table))
9640 (message "Already complete")
9641 (if (and (equal type :opt)
9642 (not (member (car (assoc (upcase pattern) table))
9643 org-additional-option-like-keywords)))
9644 (insert (substring (cdr (assoc (upcase pattern) table))
9645 (length pattern)))
9646 (if (memq type '(:tag :prop)) (insert ":")))))
9647 ((null completion)
9648 (message "Can't find completion for \"%s\"" pattern)
9649 (ding))
9650 ((not (string= pattern completion))
9651 (delete-region beg end)
9652 (if (string-match " +$" completion)
9653 (setq completion (replace-match "" t t completion)))
9654 (insert completion)
9655 (if (get-buffer-window "*Completions*")
9656 (delete-window (get-buffer-window "*Completions*")))
9657 (if (assoc completion table)
9658 (if (eq type :todo) (insert " ")
9659 (if (memq type '(:tag :prop)) (insert ":"))))
9660 (if (and (equal type :opt) (assoc completion table))
9661 (message "%s" (substitute-command-keys
9662 "Press \\[org-complete] again to insert example settings"))))
9664 (message "Making completion list...")
9665 (let ((list (sort (all-completions pattern table confirm)
9666 'string<)))
9667 (with-output-to-temp-buffer "*Completions*"
9668 (condition-case nil
9669 ;; Protection needed for XEmacs and emacs 21
9670 (display-completion-list list pattern)
9671 (error (display-completion-list list)))))
9672 (message "Making completion list...%s" "done")))))))
9674 ;;;; TODO, DEADLINE, Comments
9676 (defun org-toggle-comment ()
9677 "Change the COMMENT state of an entry."
9678 (interactive)
9679 (save-excursion
9680 (org-back-to-heading)
9681 (let (case-fold-search)
9682 (if (looking-at (concat outline-regexp
9683 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9684 (replace-match "" t t nil 1)
9685 (if (looking-at outline-regexp)
9686 (progn
9687 (goto-char (match-end 0))
9688 (insert org-comment-string " ")))))))
9690 (defvar org-last-todo-state-is-todo nil
9691 "This is non-nil when the last TODO state change led to a TODO state.
9692 If the last change removed the TODO tag or switched to DONE, then
9693 this is nil.")
9695 (defvar org-setting-tags nil) ; dynamically skipped
9697 (defun org-parse-local-options (string var)
9698 "Parse STRING for startup setting relevant for variable VAR."
9699 (let ((rtn (symbol-value var))
9700 e opts)
9701 (save-match-data
9702 (if (or (not string) (not (string-match "\\S-" string)))
9704 (setq opts (delq nil (mapcar (lambda (x)
9705 (setq e (assoc x org-startup-options))
9706 (if (eq (nth 1 e) var) e nil))
9707 (org-split-string string "[ \t]+"))))
9708 (if (not opts)
9710 (setq rtn nil)
9711 (while (setq e (pop opts))
9712 (if (not (nth 3 e))
9713 (setq rtn (nth 2 e))
9714 (if (not (listp rtn)) (setq rtn nil))
9715 (push (nth 2 e) rtn)))
9716 rtn)))))
9718 (defvar org-todo-setup-filter-hook nil
9719 "Hook for functions that pre-filter todo specs.
9721 Each function takes a todo spec and returns either `nil' or the spec
9722 transformed into canonical form." )
9724 (defvar org-todo-get-default-hook nil
9725 "Hook for functions that get a default item for todo.
9727 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9728 `nil' or a string to be used for the todo mark." )
9730 (defvar org-agenda-headline-snapshot-before-repeat)
9732 (defun org-todo (&optional arg)
9733 "Change the TODO state of an item.
9734 The state of an item is given by a keyword at the start of the heading,
9735 like
9736 *** TODO Write paper
9737 *** DONE Call mom
9739 The different keywords are specified in the variable `org-todo-keywords'.
9740 By default the available states are \"TODO\" and \"DONE\".
9741 So for this example: when the item starts with TODO, it is changed to DONE.
9742 When it starts with DONE, the DONE is removed. And when neither TODO nor
9743 DONE are present, add TODO at the beginning of the heading.
9745 With C-u prefix arg, use completion to determine the new state.
9746 With numeric prefix arg, switch to that state.
9747 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9748 With a triple C-u prefix, circumvent any state blocking.
9750 For calling through lisp, arg is also interpreted in the following way:
9751 'none -> empty state
9752 \"\"(empty string) -> switch to empty state
9753 'done -> switch to DONE
9754 'nextset -> switch to the next set of keywords
9755 'previousset -> switch to the previous set of keywords
9756 \"WAITING\" -> switch to the specified keyword, but only if it
9757 really is a member of `org-todo-keywords'."
9758 (interactive "P")
9759 (if (equal arg '(16)) (setq arg 'nextset))
9760 (let ((org-blocker-hook org-blocker-hook)
9761 (case-fold-search nil))
9762 (when (equal arg '(64))
9763 (setq arg nil org-blocker-hook nil))
9764 (when (and org-blocker-hook
9765 (or org-inhibit-blocking
9766 (org-entry-get nil "NOBLOCKING")))
9767 (setq org-blocker-hook nil))
9768 (save-excursion
9769 (catch 'exit
9770 (org-back-to-heading t)
9771 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9772 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9773 (looking-at " *"))
9774 (let* ((match-data (match-data))
9775 (startpos (point-at-bol))
9776 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9777 (org-log-done org-log-done)
9778 (org-log-repeat org-log-repeat)
9779 (org-todo-log-states org-todo-log-states)
9780 (this (match-string 1))
9781 (hl-pos (match-beginning 0))
9782 (head (org-get-todo-sequence-head this))
9783 (ass (assoc head org-todo-kwd-alist))
9784 (interpret (nth 1 ass))
9785 (done-word (nth 3 ass))
9786 (final-done-word (nth 4 ass))
9787 (last-state (or this ""))
9788 (completion-ignore-case t)
9789 (member (member this org-todo-keywords-1))
9790 (tail (cdr member))
9791 (state (cond
9792 ((and org-todo-key-trigger
9793 (or (and (equal arg '(4))
9794 (eq org-use-fast-todo-selection 'prefix))
9795 (and (not arg) org-use-fast-todo-selection
9796 (not (eq org-use-fast-todo-selection
9797 'prefix)))))
9798 ;; Use fast selection
9799 (org-fast-todo-selection))
9800 ((and (equal arg '(4))
9801 (or (not org-use-fast-todo-selection)
9802 (not org-todo-key-trigger)))
9803 ;; Read a state with completion
9804 (org-icompleting-read
9805 "State: " (mapcar (lambda(x) (list x))
9806 org-todo-keywords-1)
9807 nil t))
9808 ((eq arg 'right)
9809 (if this
9810 (if tail (car tail) nil)
9811 (car org-todo-keywords-1)))
9812 ((eq arg 'left)
9813 (if (equal member org-todo-keywords-1)
9815 (if this
9816 (nth (- (length org-todo-keywords-1)
9817 (length tail) 2)
9818 org-todo-keywords-1)
9819 (org-last org-todo-keywords-1))))
9820 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9821 (setq arg nil))) ; hack to fall back to cycling
9822 (arg
9823 ;; user or caller requests a specific state
9824 (cond
9825 ((equal arg "") nil)
9826 ((eq arg 'none) nil)
9827 ((eq arg 'done) (or done-word (car org-done-keywords)))
9828 ((eq arg 'nextset)
9829 (or (car (cdr (member head org-todo-heads)))
9830 (car org-todo-heads)))
9831 ((eq arg 'previousset)
9832 (let ((org-todo-heads (reverse org-todo-heads)))
9833 (or (car (cdr (member head org-todo-heads)))
9834 (car org-todo-heads))))
9835 ((car (member arg org-todo-keywords-1)))
9836 ((stringp arg)
9837 (error "State `%s' not valid in this file" arg))
9838 ((nth (1- (prefix-numeric-value arg))
9839 org-todo-keywords-1))))
9840 ((null member) (or head (car org-todo-keywords-1)))
9841 ((equal this final-done-word) nil) ;; -> make empty
9842 ((null tail) nil) ;; -> first entry
9843 ((memq interpret '(type priority))
9844 (if (eq this-command last-command)
9845 (car tail)
9846 (if (> (length tail) 0)
9847 (or done-word (car org-done-keywords))
9848 nil)))
9850 (car tail))))
9851 (state (or
9852 (run-hook-with-args-until-success
9853 'org-todo-get-default-hook state last-state)
9854 state))
9855 (next (if state (concat " " state " ") " "))
9856 (change-plist (list :type 'todo-state-change :from this :to state
9857 :position startpos))
9858 dolog now-done-p)
9859 (when org-blocker-hook
9860 (setq org-last-todo-state-is-todo
9861 (not (member this org-done-keywords)))
9862 (unless (save-excursion
9863 (save-match-data
9864 (run-hook-with-args-until-failure
9865 'org-blocker-hook change-plist)))
9866 (if (interactive-p)
9867 (error "TODO state change from %s to %s blocked" this state)
9868 ;; fail silently
9869 (message "TODO state change from %s to %s blocked" this state)
9870 (throw 'exit nil))))
9871 (store-match-data match-data)
9872 (replace-match next t t)
9873 (unless (pos-visible-in-window-p hl-pos)
9874 (message "TODO state changed to %s" (org-trim next)))
9875 (unless head
9876 (setq head (org-get-todo-sequence-head state)
9877 ass (assoc head org-todo-kwd-alist)
9878 interpret (nth 1 ass)
9879 done-word (nth 3 ass)
9880 final-done-word (nth 4 ass)))
9881 (when (memq arg '(nextset previousset))
9882 (message "Keyword-Set %d/%d: %s"
9883 (- (length org-todo-sets) -1
9884 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9885 (length org-todo-sets)
9886 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9887 (setq org-last-todo-state-is-todo
9888 (not (member state org-done-keywords)))
9889 (setq now-done-p (and (member state org-done-keywords)
9890 (not (member this org-done-keywords))))
9891 (and logging (org-local-logging logging))
9892 (when (and (or org-todo-log-states org-log-done)
9893 (not (eq org-inhibit-logging t))
9894 (not (memq arg '(nextset previousset))))
9895 ;; we need to look at recording a time and note
9896 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9897 (nth 2 (assoc this org-todo-log-states))))
9898 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9899 (setq dolog 'time))
9900 (when (and state
9901 (member state org-not-done-keywords)
9902 (not (member this org-not-done-keywords)))
9903 ;; This is now a todo state and was not one before
9904 ;; If there was a CLOSED time stamp, get rid of it.
9905 (org-add-planning-info nil nil 'closed))
9906 (when (and now-done-p org-log-done)
9907 ;; It is now done, and it was not done before
9908 (org-add-planning-info 'closed (org-current-time))
9909 (if (and (not dolog) (eq 'note org-log-done))
9910 (org-add-log-setup 'done state this 'findpos 'note)))
9911 (when (and state dolog)
9912 ;; This is a non-nil state, and we need to log it
9913 (org-add-log-setup 'state state this 'findpos dolog)))
9914 ;; Fixup tag positioning
9915 (org-todo-trigger-tag-changes state)
9916 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9917 (when org-provide-todo-statistics
9918 (org-update-parent-todo-statistics))
9919 (run-hooks 'org-after-todo-state-change-hook)
9920 (if (and arg (not (member state org-done-keywords)))
9921 (setq head (org-get-todo-sequence-head state)))
9922 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9923 ;; Do we need to trigger a repeat?
9924 (when now-done-p
9925 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9926 ;; This is for the agenda, take a snapshot of the headline.
9927 (save-match-data
9928 (setq org-agenda-headline-snapshot-before-repeat
9929 (org-get-heading))))
9930 (org-auto-repeat-maybe state))
9931 ;; Fixup cursor location if close to the keyword
9932 (if (and (outline-on-heading-p)
9933 (not (bolp))
9934 (save-excursion (beginning-of-line 1)
9935 (looking-at org-todo-line-regexp))
9936 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9937 (progn
9938 (goto-char (or (match-end 2) (match-end 1)))
9939 (and (looking-at " ") (just-one-space))))
9940 (when org-trigger-hook
9941 (save-excursion
9942 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9944 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9945 "Block turning an entry into a TODO, using the hierarchy.
9946 This checks whether the current task should be blocked from state
9947 changes. Such blocking occurs when:
9949 1. The task has children which are not all in a completed state.
9951 2. A task has a parent with the property :ORDERED:, and there
9952 are siblings prior to the current task with incomplete
9953 status.
9955 3. The parent of the task is blocked because it has siblings that should
9956 be done first, or is child of a block grandparent TODO entry."
9958 (catch 'dont-block
9959 ;; If this is not a todo state change, or if this entry is already DONE,
9960 ;; do not block
9961 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9962 (member (plist-get change-plist :from)
9963 (cons 'done org-done-keywords))
9964 (member (plist-get change-plist :to)
9965 (cons 'todo org-not-done-keywords))
9966 (not (plist-get change-plist :to)))
9967 (throw 'dont-block t))
9968 ;; If this task has children, and any are undone, it's blocked
9969 (save-excursion
9970 (org-back-to-heading t)
9971 (let ((this-level (funcall outline-level)))
9972 (outline-next-heading)
9973 (let ((child-level (funcall outline-level)))
9974 (while (and (not (eobp))
9975 (> child-level this-level))
9976 ;; this todo has children, check whether they are all
9977 ;; completed
9978 (if (and (not (org-entry-is-done-p))
9979 (org-entry-is-todo-p))
9980 (throw 'dont-block nil))
9981 (outline-next-heading)
9982 (setq child-level (funcall outline-level))))))
9983 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9984 ;; any previous siblings are undone, it's blocked
9985 (save-excursion
9986 (org-back-to-heading t)
9987 (let* ((pos (point))
9988 (parent-pos (and (org-up-heading-safe) (point))))
9989 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9990 (when (and (org-entry-get (point) "ORDERED")
9991 (forward-line 1)
9992 (re-search-forward org-not-done-heading-regexp pos t))
9993 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9994 ;; Search further up the hierarchy, to see if an anchestor is blocked
9995 (while t
9996 (goto-char parent-pos)
9997 (if (not (looking-at org-not-done-heading-regexp))
9998 (throw 'dont-block t)) ; do not block, parent is not a TODO
9999 (setq pos (point))
10000 (setq parent-pos (and (org-up-heading-safe) (point)))
10001 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10002 (when (and (org-entry-get (point) "ORDERED")
10003 (forward-line 1)
10004 (re-search-forward org-not-done-heading-regexp pos t))
10005 (throw 'dont-block nil))))))) ; block, older sibling not done.
10007 (defcustom org-track-ordered-property-with-tag nil
10008 "Should the ORDERED property also be shown as a tag?
10009 The ORDERED property decides if an entry should require subtasks to be
10010 completed in sequence. Since a property is not very visible, setting
10011 this option means that toggling the ORDERED property with the command
10012 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10013 not relevant for the behavior, but it makes things more visible.
10015 Note that toggling the tag with tags commands will not change the property
10016 and therefore not influence behavior!
10018 This can be t, meaning the tag ORDERED should be used, It can also be a
10019 string to select a different tag for this task."
10020 :group 'org-todo
10021 :type '(choice
10022 (const :tag "No tracking" nil)
10023 (const :tag "Track with ORDERED tag" t)
10024 (string :tag "Use other tag")))
10026 (defun org-toggle-ordered-property ()
10027 "Toggle the ORDERED property of the current entry.
10028 For better visibility, you can track the value of this property with a tag.
10029 See variable `org-track-ordered-property-with-tag'."
10030 (interactive)
10031 (let* ((t1 org-track-ordered-property-with-tag)
10032 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10033 (save-excursion
10034 (org-back-to-heading)
10035 (if (org-entry-get nil "ORDERED")
10036 (progn
10037 (org-delete-property "ORDERED")
10038 (and tag (org-toggle-tag tag 'off))
10039 (message "Subtasks can be completed in arbitrary order"))
10040 (org-entry-put nil "ORDERED" "t")
10041 (and tag (org-toggle-tag tag 'on))
10042 (message "Subtasks must be completed in sequence")))))
10044 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10045 (defun org-block-todo-from-checkboxes (change-plist)
10046 "Block turning an entry into a TODO, using checkboxes.
10047 This checks whether the current task should be blocked from state
10048 changes because there are unchecked boxes in this entry."
10049 (catch 'dont-block
10050 ;; If this is not a todo state change, or if this entry is already DONE,
10051 ;; do not block
10052 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10053 (member (plist-get change-plist :from)
10054 (cons 'done org-done-keywords))
10055 (member (plist-get change-plist :to)
10056 (cons 'todo org-not-done-keywords))
10057 (not (plist-get change-plist :to)))
10058 (throw 'dont-block t))
10059 ;; If this task has checkboxes that are not checked, it's blocked
10060 (save-excursion
10061 (org-back-to-heading t)
10062 (let ((beg (point)) end)
10063 (outline-next-heading)
10064 (setq end (point))
10065 (goto-char beg)
10066 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10067 end t)
10068 (progn
10069 (if (boundp 'org-blocked-by-checkboxes)
10070 (setq org-blocked-by-checkboxes t))
10071 (throw 'dont-block nil)))))
10072 t)) ; do not block
10074 (defun org-update-statistics-cookies (all)
10075 "Update the statistics cookie, either from TODO or from checkboxes.
10076 This should be called with the cursor in a line with a statistics cookie."
10077 (interactive "P")
10078 (if all
10079 (progn
10080 (org-update-checkbox-count 'all)
10081 (org-map-entries 'org-update-parent-todo-statistics))
10082 (if (not (org-on-heading-p))
10083 (org-update-checkbox-count)
10084 (let ((pos (move-marker (make-marker) (point)))
10085 end l1 l2)
10086 (ignore-errors (org-back-to-heading t))
10087 (if (not (org-on-heading-p))
10088 (org-update-checkbox-count)
10089 (setq l1 (org-outline-level))
10090 (setq end (save-excursion
10091 (outline-next-heading)
10092 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10093 (point)))
10094 (if (and (save-excursion (re-search-forward
10095 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10096 (not (save-excursion (re-search-forward
10097 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10098 (org-update-checkbox-count)
10099 (if (and l2 (> l2 l1))
10100 (progn
10101 (goto-char end)
10102 (org-update-parent-todo-statistics))
10103 (error "No data for statistics cookie"))))
10104 (goto-char pos)
10105 (move-marker pos nil)))))
10107 (defvar org-entry-property-inherited-from) ;; defined below
10108 (defun org-update-parent-todo-statistics ()
10109 "Update any statistics cookie in the parent of the current headline.
10110 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10111 the entire subtree and this will travel up the hierarchy and update
10112 statistics everywhere."
10113 (interactive)
10114 (let* ((lim 0) prop
10115 (recursive (or (not org-hierarchical-todo-statistics)
10116 (string-match
10117 "\\<recursive\\>"
10118 (or (setq prop (org-entry-get
10119 nil "COOKIE_DATA" 'inherit)) ""))))
10120 (lim (or (and prop (marker-position
10121 org-entry-property-inherited-from))
10122 lim))
10123 (first t)
10124 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10125 level ltoggle l1 new ndel
10126 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10127 (catch 'exit
10128 (save-excursion
10129 (beginning-of-line 1)
10130 (if (org-at-heading-p)
10131 (setq ltoggle (funcall outline-level))
10132 (error "This should not happen"))
10133 (while (and (setq level (org-up-heading-safe))
10134 (or recursive first)
10135 (>= (point) lim))
10136 (setq first nil cookie-present nil)
10137 (unless (and level
10138 (not (string-match
10139 "\\<checkbox\\>"
10140 (downcase
10141 (or (org-entry-get
10142 nil "COOKIE_DATA")
10143 "")))))
10144 (throw 'exit nil))
10145 (while (re-search-forward box-re (point-at-eol) t)
10146 (setq cnt-all 0 cnt-done 0 cookie-present t)
10147 (setq is-percent (match-end 2))
10148 (save-match-data
10149 (unless (outline-next-heading) (throw 'exit nil))
10150 (while (and (looking-at org-complex-heading-regexp)
10151 (> (setq l1 (length (match-string 1))) level))
10152 (setq kwd (and (or recursive (= l1 ltoggle))
10153 (match-string 2)))
10154 (if (or (eq org-provide-todo-statistics 'all-headlines)
10155 (and (listp org-provide-todo-statistics)
10156 (or (member kwd org-provide-todo-statistics)
10157 (member kwd org-done-keywords))))
10158 (setq cnt-all (1+ cnt-all))
10159 (if (eq org-provide-todo-statistics t)
10160 (and kwd (setq cnt-all (1+ cnt-all)))))
10161 (and (member kwd org-done-keywords)
10162 (setq cnt-done (1+ cnt-done)))
10163 (outline-next-heading)))
10164 (setq new
10165 (if is-percent
10166 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10167 (format "[%d/%d]" cnt-done cnt-all))
10168 ndel (- (match-end 0) (match-beginning 0)))
10169 (goto-char (match-beginning 0))
10170 (insert new)
10171 (delete-region (point) (+ (point) ndel)))
10172 (when cookie-present
10173 (run-hook-with-args 'org-after-todo-statistics-hook
10174 cnt-done (- cnt-all cnt-done))))))
10175 (run-hooks 'org-todo-statistics-hook)))
10177 (defvar org-after-todo-statistics-hook nil
10178 "Hook that is called after a TODO statistics cookie has been updated.
10179 Each function is called with two arguments: the number of not-done entries
10180 and the number of done entries.
10182 For example, the following function, when added to this hook, will switch
10183 an entry to DONE when all children are done, and back to TODO when new
10184 entries are set to a TODO status. Note that this hook is only called
10185 when there is a statistics cookie in the headline!
10187 (defun org-summary-todo (n-done n-not-done)
10188 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10189 (let (org-log-done org-log-states) ; turn off logging
10190 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10193 (defvar org-todo-statistics-hook nil
10194 "Hook that is run whenever Org thinks TODO statistics should be updated.
10195 This hook runs even if there is no statistics cookie present, in which case
10196 `org-after-todo-statistics-hook' would not run.")
10198 (defun org-todo-trigger-tag-changes (state)
10199 "Apply the changes defined in `org-todo-state-tags-triggers'."
10200 (let ((l org-todo-state-tags-triggers)
10201 changes)
10202 (when (or (not state) (equal state ""))
10203 (setq changes (append changes (cdr (assoc "" l)))))
10204 (when (and (stringp state) (> (length state) 0))
10205 (setq changes (append changes (cdr (assoc state l)))))
10206 (when (member state org-not-done-keywords)
10207 (setq changes (append changes (cdr (assoc 'todo l)))))
10208 (when (member state org-done-keywords)
10209 (setq changes (append changes (cdr (assoc 'done l)))))
10210 (dolist (c changes)
10211 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10213 (defun org-local-logging (value)
10214 "Get logging settings from a property VALUE."
10215 (let* (words w a)
10216 ;; directly set the variables, they are already local.
10217 (setq org-log-done nil
10218 org-log-repeat nil
10219 org-todo-log-states nil)
10220 (setq words (org-split-string value))
10221 (while (setq w (pop words))
10222 (cond
10223 ((setq a (assoc w org-startup-options))
10224 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10225 (set (nth 1 a) (nth 2 a))))
10226 ((setq a (org-extract-log-state-settings w))
10227 (and (member (car a) org-todo-keywords-1)
10228 (push a org-todo-log-states)))))))
10230 (defun org-get-todo-sequence-head (kwd)
10231 "Return the head of the TODO sequence to which KWD belongs.
10232 If KWD is not set, check if there is a text property remembering the
10233 right sequence."
10234 (let (p)
10235 (cond
10236 ((not kwd)
10237 (or (get-text-property (point-at-bol) 'org-todo-head)
10238 (progn
10239 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10240 nil (point-at-eol)))
10241 (get-text-property p 'org-todo-head))))
10242 ((not (member kwd org-todo-keywords-1))
10243 (car org-todo-keywords-1))
10244 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10246 (defun org-fast-todo-selection ()
10247 "Fast TODO keyword selection with single keys.
10248 Returns the new TODO keyword, or nil if no state change should occur."
10249 (let* ((fulltable org-todo-key-alist)
10250 (done-keywords org-done-keywords) ;; needed for the faces.
10251 (maxlen (apply 'max (mapcar
10252 (lambda (x)
10253 (if (stringp (car x)) (string-width (car x)) 0))
10254 fulltable)))
10255 (expert nil)
10256 (fwidth (+ maxlen 3 1 3))
10257 (ncol (/ (- (window-width) 4) fwidth))
10258 tg cnt e c tbl
10259 groups ingroup)
10260 (save-excursion
10261 (save-window-excursion
10262 (if expert
10263 (set-buffer (get-buffer-create " *Org todo*"))
10264 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10265 (erase-buffer)
10266 (org-set-local 'org-done-keywords done-keywords)
10267 (setq tbl fulltable cnt 0)
10268 (while (setq e (pop tbl))
10269 (cond
10270 ((equal e '(:startgroup))
10271 (push '() groups) (setq ingroup t)
10272 (when (not (= cnt 0))
10273 (setq cnt 0)
10274 (insert "\n"))
10275 (insert "{ "))
10276 ((equal e '(:endgroup))
10277 (setq ingroup nil cnt 0)
10278 (insert "}\n"))
10279 ((equal e '(:newline))
10280 (when (not (= cnt 0))
10281 (setq cnt 0)
10282 (insert "\n")
10283 (setq e (car tbl))
10284 (while (equal (car tbl) '(:newline))
10285 (insert "\n")
10286 (setq tbl (cdr tbl)))))
10288 (setq tg (car e) c (cdr e))
10289 (if ingroup (push tg (car groups)))
10290 (setq tg (org-add-props tg nil 'face
10291 (org-get-todo-face tg)))
10292 (if (and (= cnt 0) (not ingroup)) (insert " "))
10293 (insert "[" c "] " tg (make-string
10294 (- fwidth 4 (length tg)) ?\ ))
10295 (when (= (setq cnt (1+ cnt)) ncol)
10296 (insert "\n")
10297 (if ingroup (insert " "))
10298 (setq cnt 0)))))
10299 (insert "\n")
10300 (goto-char (point-min))
10301 (if (not expert) (org-fit-window-to-buffer))
10302 (message "[a-z..]:Set [SPC]:clear")
10303 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10304 (cond
10305 ((or (= c ?\C-g)
10306 (and (= c ?q) (not (rassoc c fulltable))))
10307 (setq quit-flag t))
10308 ((= c ?\ ) nil)
10309 ((setq e (rassoc c fulltable) tg (car e))
10311 (t (setq quit-flag t)))))))
10313 (defun org-entry-is-todo-p ()
10314 (member (org-get-todo-state) org-not-done-keywords))
10316 (defun org-entry-is-done-p ()
10317 (member (org-get-todo-state) org-done-keywords))
10319 (defun org-get-todo-state ()
10320 (save-excursion
10321 (org-back-to-heading t)
10322 (and (looking-at org-todo-line-regexp)
10323 (match-end 2)
10324 (match-string 2))))
10326 (defun org-at-date-range-p (&optional inactive-ok)
10327 "Is the cursor inside a date range?"
10328 (interactive)
10329 (save-excursion
10330 (catch 'exit
10331 (let ((pos (point)))
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 (skip-chars-backward "^<[\r\n")
10338 (skip-chars-backward "<[")
10339 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10340 (>= (match-end 0) pos)
10341 (throw 'exit t)))
10342 nil)))
10344 (defun org-get-repeat (&optional tagline)
10345 "Check if there is a deadline/schedule with repeater in this entry."
10346 (save-match-data
10347 (save-excursion
10348 (org-back-to-heading t)
10349 (and (re-search-forward (if tagline
10350 (concat tagline "\\s-*" org-repeat-re)
10351 org-repeat-re)
10352 (org-entry-end-position) t)
10353 (match-string-no-properties 1)))))
10355 (defvar org-last-changed-timestamp)
10356 (defvar org-last-inserted-timestamp)
10357 (defvar org-log-post-message)
10358 (defvar org-log-note-purpose)
10359 (defvar org-log-note-how)
10360 (defvar org-log-note-extra)
10361 (defun org-auto-repeat-maybe (done-word)
10362 "Check if the current headline contains a repeated deadline/schedule.
10363 If yes, set TODO state back to what it was and change the base date
10364 of repeating deadline/scheduled time stamps to new date.
10365 This function is run automatically after each state change to a DONE state."
10366 ;; last-state is dynamically scoped into this function
10367 (let* ((repeat (org-get-repeat))
10368 (aa (assoc last-state org-todo-kwd-alist))
10369 (interpret (nth 1 aa))
10370 (head (nth 2 aa))
10371 (whata '(("d" . day) ("m" . month) ("y" . year)))
10372 (msg "Entry repeats: ")
10373 (org-log-done nil)
10374 (org-todo-log-states nil)
10375 (nshiftmax 10) (nshift 0)
10376 re type n what ts time)
10377 (when repeat
10378 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10379 (org-todo (if (eq interpret 'type) last-state head))
10380 (org-entry-put nil "LAST_REPEAT" (format-time-string
10381 (org-time-stamp-format t t)))
10382 (when org-log-repeat
10383 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10384 (memq 'org-add-log-note post-command-hook))
10385 ;; OK, we are already setup for some record
10386 (if (eq org-log-repeat 'note)
10387 ;; make sure we take a note, not only a time stamp
10388 (setq org-log-note-how 'note))
10389 ;; Set up for taking a record
10390 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10391 last-state
10392 'findpos org-log-repeat)))
10393 (org-back-to-heading t)
10394 (org-add-planning-info nil nil 'closed)
10395 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10396 org-deadline-time-regexp "\\)\\|\\("
10397 org-ts-regexp "\\)"))
10398 (while (re-search-forward
10399 re (save-excursion (outline-next-heading) (point)) t)
10400 (setq type (if (match-end 1) org-scheduled-string
10401 (if (match-end 3) org-deadline-string "Plain:"))
10402 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10403 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10404 (setq n (string-to-number (match-string 2 ts))
10405 what (match-string 3 ts))
10406 (if (equal what "w") (setq n (* n 7) what "d"))
10407 ;; Preparation, see if we need to modify the start date for the change
10408 (when (match-end 1)
10409 (setq time (save-match-data (org-time-string-to-time ts)))
10410 (cond
10411 ((equal (match-string 1 ts) ".")
10412 ;; Shift starting date to today
10413 (org-timestamp-change
10414 (- (time-to-days (current-time)) (time-to-days time))
10415 'day))
10416 ((equal (match-string 1 ts) "+")
10417 (while (or (= nshift 0)
10418 (<= (time-to-days time) (time-to-days (current-time))))
10419 (when (= (incf nshift) nshiftmax)
10420 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10421 (error "Abort")))
10422 (org-timestamp-change n (cdr (assoc what whata)))
10423 (org-at-timestamp-p t)
10424 (setq ts (match-string 1))
10425 (setq time (save-match-data (org-time-string-to-time ts))))
10426 (org-timestamp-change (- n) (cdr (assoc what whata)))
10427 ;; rematch, so that we have everything in place for the real shift
10428 (org-at-timestamp-p t)
10429 (setq ts (match-string 1))
10430 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10431 (org-timestamp-change n (cdr (assoc what whata)))
10432 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10433 (setq org-log-post-message msg)
10434 (message "%s" msg))))
10436 (defun org-show-todo-tree (arg)
10437 "Make a compact tree which shows all headlines marked with TODO.
10438 The tree will show the lines where the regexp matches, and all higher
10439 headlines above the match.
10440 With a \\[universal-argument] prefix, prompt for a regexp to match.
10441 With a numeric prefix N, construct a sparse tree for the Nth element
10442 of `org-todo-keywords-1'."
10443 (interactive "P")
10444 (let ((case-fold-search nil)
10445 (kwd-re
10446 (cond ((null arg) org-not-done-regexp)
10447 ((equal arg '(4))
10448 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10449 (mapcar 'list org-todo-keywords-1))))
10450 (concat "\\("
10451 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10452 "\\)\\>")))
10453 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10454 (regexp-quote (nth (1- (prefix-numeric-value arg))
10455 org-todo-keywords-1)))
10456 (t (error "Invalid prefix argument: %s" arg)))))
10457 (message "%d TODO entries found"
10458 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10460 (defun org-deadline (&optional remove time)
10461 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10462 With argument REMOVE, remove any deadline from the item.
10463 When TIME is set, it should be an internal time specification, and the
10464 scheduling will use the corresponding date."
10465 (interactive "P")
10466 (let ((old-date (org-entry-get nil "DEADLINE")))
10467 (if remove
10468 (progn
10469 (org-remove-timestamp-with-keyword org-deadline-string)
10470 (message "Item no longer has a deadline."))
10471 (if (org-get-repeat)
10472 (error "Cannot change deadline on task with repeater, please do that by hand")
10473 (org-add-planning-info 'deadline time 'closed)
10474 (when (and old-date org-log-redeadline
10475 (not (equal old-date
10476 (substring org-last-inserted-timestamp 1 -1))))
10477 (org-add-log-setup 'redeadline nil old-date 'findpos
10478 org-log-redeadline))
10479 (message "Deadline on %s" org-last-inserted-timestamp)))))
10481 (defun org-schedule (&optional remove time)
10482 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10483 With argument REMOVE, remove any scheduling date from the item.
10484 When TIME is set, it should be an internal time specification, and the
10485 scheduling will use the corresponding date."
10486 (interactive "P")
10487 (let ((old-date (org-entry-get nil "SCHEDULED")))
10488 (if remove
10489 (progn
10490 (org-remove-timestamp-with-keyword org-scheduled-string)
10491 (message "Item is no longer scheduled."))
10492 (if (org-get-repeat)
10493 (error "Cannot reschedule task with repeater, please do that by hand")
10494 (org-add-planning-info 'scheduled time 'closed)
10495 (when (and old-date org-log-reschedule
10496 (not (equal old-date
10497 (substring org-last-inserted-timestamp 1 -1))))
10498 (org-add-log-setup 'reschedule nil old-date 'findpos
10499 org-log-reschedule))
10500 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10502 (defun org-get-scheduled-time (pom &optional inherit)
10503 "Get the scheduled time as a time tuple, of a format suitable
10504 for calling org-schedule with, or if there is no scheduling,
10505 returns nil."
10506 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10507 (when time
10508 (apply 'encode-time (org-parse-time-string time)))))
10510 (defun org-get-deadline-time (pom &optional inherit)
10511 "Get the deadine as a time tuple, of a format suitable for
10512 calling org-deadline with, or if there is no scheduling, returns
10513 nil."
10514 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10515 (when time
10516 (apply 'encode-time (org-parse-time-string time)))))
10518 (defun org-remove-timestamp-with-keyword (keyword)
10519 "Remove all time stamps with KEYWORD in the current entry."
10520 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10521 beg)
10522 (save-excursion
10523 (org-back-to-heading t)
10524 (setq beg (point))
10525 (outline-next-heading)
10526 (while (re-search-backward re beg t)
10527 (replace-match "")
10528 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10529 (equal (char-before) ?\ ))
10530 (backward-delete-char 1)
10531 (if (string-match "^[ \t]*$" (buffer-substring
10532 (point-at-bol) (point-at-eol)))
10533 (delete-region (point-at-bol)
10534 (min (point-max) (1+ (point-at-eol))))))))))
10536 (defun org-add-planning-info (what &optional time &rest remove)
10537 "Insert new timestamp with keyword in the line directly after the headline.
10538 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10539 If non is given, the user is prompted for a date.
10540 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10541 be removed."
10542 (interactive)
10543 (let (org-time-was-given org-end-time-was-given ts
10544 end default-time default-input)
10546 (catch 'exit
10547 (when (and (not time) (memq what '(scheduled deadline)))
10548 ;; Try to get a default date/time from existing timestamp
10549 (save-excursion
10550 (org-back-to-heading t)
10551 (setq end (save-excursion (outline-next-heading) (point)))
10552 (when (re-search-forward (if (eq what 'scheduled)
10553 org-scheduled-time-regexp
10554 org-deadline-time-regexp)
10555 end t)
10556 (setq ts (match-string 1)
10557 default-time
10558 (apply 'encode-time (org-parse-time-string ts))
10559 default-input (and ts (org-get-compact-tod ts))))))
10560 (when what
10561 ;; If necessary, get the time from the user
10562 (setq time (or time (org-read-date nil 'to-time nil nil
10563 default-time default-input))))
10565 (when (and org-insert-labeled-timestamps-at-point
10566 (member what '(scheduled deadline)))
10567 (insert
10568 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10569 (org-insert-time-stamp time org-time-was-given
10570 nil nil nil (list org-end-time-was-given))
10571 (setq what nil))
10572 (save-excursion
10573 (save-restriction
10574 (let (col list elt ts buffer-invisibility-spec)
10575 (org-back-to-heading t)
10576 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10577 (goto-char (match-end 1))
10578 (setq col (current-column))
10579 (goto-char (match-end 0))
10580 (if (eobp) (insert "\n") (forward-char 1))
10581 (when (and (not what)
10582 (not (looking-at
10583 (concat "[ \t]*"
10584 org-keyword-time-not-clock-regexp))))
10585 ;; Nothing to add, nothing to remove...... :-)
10586 (throw 'exit nil))
10587 (if (and (not (looking-at outline-regexp))
10588 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10589 "[^\r\n]*"))
10590 (not (equal (match-string 1) org-clock-string)))
10591 (narrow-to-region (match-beginning 0) (match-end 0))
10592 (insert-before-markers "\n")
10593 (backward-char 1)
10594 (narrow-to-region (point) (point))
10595 (and org-adapt-indentation (org-indent-to-column col)))
10596 ;; Check if we have to remove something.
10597 (setq list (cons what remove))
10598 (while list
10599 (setq elt (pop list))
10600 (goto-char (point-min))
10601 (when (or (and (eq elt 'scheduled)
10602 (re-search-forward org-scheduled-time-regexp nil t))
10603 (and (eq elt 'deadline)
10604 (re-search-forward org-deadline-time-regexp nil t))
10605 (and (eq elt 'closed)
10606 (re-search-forward org-closed-time-regexp nil t)))
10607 (replace-match "")
10608 (if (looking-at "--+<[^>]+>") (replace-match ""))
10609 (skip-chars-backward " ")
10610 (if (looking-at " +") (replace-match ""))))
10611 (goto-char (point-max))
10612 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10613 (when what
10614 (insert
10615 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10616 (cond ((eq what 'scheduled) org-scheduled-string)
10617 ((eq what 'deadline) org-deadline-string)
10618 ((eq what 'closed) org-closed-string))
10619 " ")
10620 (setq ts (org-insert-time-stamp
10621 time
10622 (or org-time-was-given
10623 (and (eq what 'closed) org-log-done-with-time))
10624 (eq what 'closed)
10625 nil nil (list org-end-time-was-given)))
10626 (end-of-line 1))
10627 (goto-char (point-min))
10628 (widen)
10629 (if (and (looking-at "[ \t]+\n")
10630 (equal (char-before) ?\n))
10631 (delete-region (1- (point)) (point-at-eol)))
10632 ts))))))
10634 (defvar org-log-note-marker (make-marker))
10635 (defvar org-log-note-purpose nil)
10636 (defvar org-log-note-state nil)
10637 (defvar org-log-note-previous-state nil)
10638 (defvar org-log-note-how nil)
10639 (defvar org-log-note-extra nil)
10640 (defvar org-log-note-window-configuration nil)
10641 (defvar org-log-note-return-to (make-marker))
10642 (defvar org-log-post-message nil
10643 "Message to be displayed after a log note has been stored.
10644 The auto-repeater uses this.")
10646 (defun org-add-note ()
10647 "Add a note to the current entry.
10648 This is done in the same way as adding a state change note."
10649 (interactive)
10650 (org-add-log-setup 'note nil nil 'findpos nil))
10652 (defvar org-property-end-re)
10653 (defun org-add-log-setup (&optional purpose state prev-state
10654 findpos how &optional extra)
10655 "Set up the post command hook to take a note.
10656 If this is about to TODO state change, the new state is expected in STATE.
10657 When FINDPOS is non-nil, find the correct position for the note in
10658 the current entry. If not, assume that it can be inserted at point.
10659 HOW is an indicator what kind of note should be created.
10660 EXTRA is additional text that will be inserted into the notes buffer."
10661 (let* ((org-log-into-drawer (org-log-into-drawer))
10662 (drawer (cond ((stringp org-log-into-drawer)
10663 org-log-into-drawer)
10664 (org-log-into-drawer "LOGBOOK")
10665 (t nil))))
10666 (save-restriction
10667 (save-excursion
10668 (when findpos
10669 (org-back-to-heading t)
10670 (narrow-to-region (point) (save-excursion
10671 (outline-next-heading) (point)))
10672 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10673 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10674 "[^\r\n]*\\)?"))
10675 (goto-char (match-end 0))
10676 (cond
10677 (drawer
10678 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10679 nil t)
10680 (progn
10681 (goto-char (match-end 0))
10682 (or org-log-states-order-reversed
10683 (and (re-search-forward org-property-end-re nil t)
10684 (goto-char (1- (match-beginning 0))))))
10685 (insert "\n:" drawer ":\n:END:")
10686 (beginning-of-line 0)
10687 (org-indent-line-function)
10688 (beginning-of-line 2)
10689 (org-indent-line-function)
10690 (end-of-line 0)))
10691 ((and org-log-state-notes-insert-after-drawers
10692 (save-excursion
10693 (forward-line) (looking-at org-drawer-regexp)))
10694 (forward-line)
10695 (while (looking-at org-drawer-regexp)
10696 (goto-char (match-end 0))
10697 (re-search-forward org-property-end-re (point-max) t)
10698 (forward-line))
10699 (forward-line -1)))
10700 (unless org-log-states-order-reversed
10701 (and (= (char-after) ?\n) (forward-char 1))
10702 (org-skip-over-state-notes)
10703 (skip-chars-backward " \t\n\r")))
10704 (move-marker org-log-note-marker (point))
10705 (setq org-log-note-purpose purpose
10706 org-log-note-state state
10707 org-log-note-previous-state prev-state
10708 org-log-note-how how
10709 org-log-note-extra extra)
10710 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10712 (defun org-skip-over-state-notes ()
10713 "Skip past the list of State notes in an entry."
10714 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10715 (while (looking-at "[ \t]*- State")
10716 (condition-case nil
10717 (org-next-item)
10718 (error (org-end-of-item)))))
10720 (defun org-add-log-note (&optional purpose)
10721 "Pop up a window for taking a note, and add this note later at point."
10722 (remove-hook 'post-command-hook 'org-add-log-note)
10723 (setq org-log-note-window-configuration (current-window-configuration))
10724 (delete-other-windows)
10725 (move-marker org-log-note-return-to (point))
10726 (switch-to-buffer (marker-buffer org-log-note-marker))
10727 (goto-char org-log-note-marker)
10728 (org-switch-to-buffer-other-window "*Org Note*")
10729 (erase-buffer)
10730 (if (memq org-log-note-how '(time state))
10731 (let (current-prefix-arg) (org-store-log-note))
10732 (let ((org-inhibit-startup t)) (org-mode))
10733 (insert (format "# Insert note for %s.
10734 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10735 (cond
10736 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10737 ((eq org-log-note-purpose 'done) "closed todo item")
10738 ((eq org-log-note-purpose 'state)
10739 (format "state change from \"%s\" to \"%s\""
10740 (or org-log-note-previous-state "")
10741 (or org-log-note-state "")))
10742 ((eq org-log-note-purpose 'reschedule)
10743 "rescheduling")
10744 ((eq org-log-note-purpose 'redeadline)
10745 "changing deadline")
10746 ((eq org-log-note-purpose 'note)
10747 "this entry")
10748 (t (error "This should not happen")))))
10749 (if org-log-note-extra (insert org-log-note-extra))
10750 (org-set-local 'org-finish-function 'org-store-log-note)))
10752 (defvar org-note-abort nil) ; dynamically scoped
10753 (defun org-store-log-note ()
10754 "Finish taking a log note, and insert it to where it belongs."
10755 (let ((txt (buffer-string))
10756 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10757 lines ind)
10758 (kill-buffer (current-buffer))
10759 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10760 (setq txt (replace-match "" t t txt)))
10761 (if (string-match "\\s-+\\'" txt)
10762 (setq txt (replace-match "" t t txt)))
10763 (setq lines (org-split-string txt "\n"))
10764 (when (and note (string-match "\\S-" note))
10765 (setq note
10766 (org-replace-escapes
10767 note
10768 (list (cons "%u" (user-login-name))
10769 (cons "%U" user-full-name)
10770 (cons "%t" (format-time-string
10771 (org-time-stamp-format 'long 'inactive)
10772 (current-time)))
10773 (cons "%s" (if org-log-note-state
10774 (concat "\"" org-log-note-state "\"")
10775 ""))
10776 (cons "%S" (if org-log-note-previous-state
10777 (concat "\"" org-log-note-previous-state "\"")
10778 "\"\"")))))
10779 (if lines (setq note (concat note " \\\\")))
10780 (push note lines))
10781 (when (or current-prefix-arg org-note-abort)
10782 (when org-log-into-drawer
10783 (org-remove-empty-drawer-at
10784 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10785 org-log-note-marker))
10786 (setq lines nil))
10787 (when lines
10788 (with-current-buffer (marker-buffer org-log-note-marker)
10789 (save-excursion
10790 (goto-char org-log-note-marker)
10791 (move-marker org-log-note-marker nil)
10792 (end-of-line 1)
10793 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10794 (insert "- " (pop lines))
10795 (org-indent-line-function)
10796 (beginning-of-line 1)
10797 (looking-at "[ \t]*")
10798 (setq ind (concat (match-string 0) " "))
10799 (end-of-line 1)
10800 (while lines (insert "\n" ind (pop lines)))
10801 (message "Note stored")
10802 (org-back-to-heading t)
10803 (org-cycle-hide-drawers 'children)))))
10804 (set-window-configuration org-log-note-window-configuration)
10805 (with-current-buffer (marker-buffer org-log-note-return-to)
10806 (goto-char org-log-note-return-to))
10807 (move-marker org-log-note-return-to nil)
10808 (and org-log-post-message (message "%s" org-log-post-message)))
10810 (defun org-remove-empty-drawer-at (drawer pos)
10811 "Remove an empty drawer DRAWER at position POS.
10812 POS may also be a marker."
10813 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10814 (save-excursion
10815 (save-restriction
10816 (widen)
10817 (goto-char pos)
10818 (if (org-in-regexp
10819 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10820 (replace-match ""))))))
10822 (defun org-sparse-tree (&optional arg)
10823 "Create a sparse tree, prompt for the details.
10824 This command can create sparse trees. You first need to select the type
10825 of match used to create the tree:
10827 t Show entries with a specific TODO keyword.
10828 m Show entries selected by a tags/property match.
10829 p Enter a property name and its value (both with completion on existing
10830 names/values) and show entries with that property.
10831 / Show entries matching a regular expression (`r' can be used as well)
10832 d Show deadlines due within `org-deadline-warning-days'.
10833 b Show deadlines and scheduled items before a date.
10834 a Show deadlines and scheduled items after a date."
10835 (interactive "P")
10836 (let (ans kwd value)
10837 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10838 (setq ans (read-char-exclusive))
10839 (cond
10840 ((equal ans ?d)
10841 (call-interactively 'org-check-deadlines))
10842 ((equal ans ?b)
10843 (call-interactively 'org-check-before-date))
10844 ((equal ans ?a)
10845 (call-interactively 'org-check-after-date))
10846 ((equal ans ?t)
10847 (org-show-todo-tree '(4)))
10848 ((member ans '(?T ?m))
10849 (call-interactively 'org-match-sparse-tree))
10850 ((member ans '(?p ?P))
10851 (setq kwd (org-icompleting-read "Property: "
10852 (mapcar 'list (org-buffer-property-keys))))
10853 (setq value (org-icompleting-read "Value: "
10854 (mapcar 'list (org-property-values kwd))))
10855 (unless (string-match "\\`{.*}\\'" value)
10856 (setq value (concat "\"" value "\"")))
10857 (org-match-sparse-tree arg (concat kwd "=" value)))
10858 ((member ans '(?r ?R ?/))
10859 (call-interactively 'org-occur))
10860 (t (error "No such sparse tree command \"%c\"" ans)))))
10862 (defvar org-occur-highlights nil
10863 "List of overlays used for occur matches.")
10864 (make-variable-buffer-local 'org-occur-highlights)
10865 (defvar org-occur-parameters nil
10866 "Parameters of the active org-occur calls.
10867 This is a list, each call to org-occur pushes as cons cell,
10868 containing the regular expression and the callback, onto the list.
10869 The list can contain several entries if `org-occur' has been called
10870 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10871 will only contain one set of parameters. When the highlights are
10872 removed (for example with `C-c C-c', or with the next edit (depending
10873 on `org-remove-highlights-with-change'), this variable is emptied
10874 as well.")
10875 (make-variable-buffer-local 'org-occur-parameters)
10877 (defun org-occur (regexp &optional keep-previous callback)
10878 "Make a compact tree which shows all matches of REGEXP.
10879 The tree will show the lines where the regexp matches, and all higher
10880 headlines above the match. It will also show the heading after the match,
10881 to make sure editing the matching entry is easy.
10882 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10883 call to `org-occur' will be kept, to allow stacking of calls to this
10884 command.
10885 If CALLBACK is non-nil, it is a function which is called to confirm
10886 that the match should indeed be shown."
10887 (interactive "sRegexp: \nP")
10888 (when (equal regexp "")
10889 (error "Regexp cannot be empty"))
10890 (unless keep-previous
10891 (org-remove-occur-highlights nil nil t))
10892 (push (cons regexp callback) org-occur-parameters)
10893 (let ((cnt 0))
10894 (save-excursion
10895 (goto-char (point-min))
10896 (if (or (not keep-previous) ; do not want to keep
10897 (not org-occur-highlights)) ; no previous matches
10898 ;; hide everything
10899 (org-overview))
10900 (while (re-search-forward regexp nil t)
10901 (when (or (not callback)
10902 (save-match-data (funcall callback)))
10903 (setq cnt (1+ cnt))
10904 (when org-highlight-sparse-tree-matches
10905 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10906 (org-show-context 'occur-tree))))
10907 (when org-remove-highlights-with-change
10908 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10909 nil 'local))
10910 (unless org-sparse-tree-open-archived-trees
10911 (org-hide-archived-subtrees (point-min) (point-max)))
10912 (run-hooks 'org-occur-hook)
10913 (if (interactive-p)
10914 (message "%d match(es) for regexp %s" cnt regexp))
10915 cnt))
10917 (defun org-show-context (&optional key)
10918 "Make sure point and context and visible.
10919 How much context is shown depends upon the variables
10920 `org-show-hierarchy-above', `org-show-following-heading'. and
10921 `org-show-siblings'."
10922 (let ((heading-p (org-on-heading-p t))
10923 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10924 (following-p (org-get-alist-option org-show-following-heading key))
10925 (entry-p (org-get-alist-option org-show-entry-below key))
10926 (siblings-p (org-get-alist-option org-show-siblings key)))
10927 (catch 'exit
10928 ;; Show heading or entry text
10929 (if (and heading-p (not entry-p))
10930 (org-flag-heading nil) ; only show the heading
10931 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10932 (org-show-hidden-entry))) ; show entire entry
10933 (when following-p
10934 ;; Show next sibling, or heading below text
10935 (save-excursion
10936 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10937 (org-flag-heading nil))))
10938 (when siblings-p (org-show-siblings))
10939 (when hierarchy-p
10940 ;; show all higher headings, possibly with siblings
10941 (save-excursion
10942 (while (and (condition-case nil
10943 (progn (org-up-heading-all 1) t)
10944 (error nil))
10945 (not (bobp)))
10946 (org-flag-heading nil)
10947 (when siblings-p (org-show-siblings))))))))
10949 (defun org-reveal (&optional siblings)
10950 "Show current entry, hierarchy above it, and the following headline.
10951 This can be used to show a consistent set of context around locations
10952 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10953 not t for the search context.
10955 With optional argument SIBLINGS, on each level of the hierarchy all
10956 siblings are shown. This repairs the tree structure to what it would
10957 look like when opened with hierarchical calls to `org-cycle'."
10958 (interactive "P")
10959 (let ((org-show-hierarchy-above t)
10960 (org-show-following-heading t)
10961 (org-show-siblings (if siblings t org-show-siblings)))
10962 (org-show-context nil)))
10964 (defun org-highlight-new-match (beg end)
10965 "Highlight from BEG to END and mark the highlight is an occur headline."
10966 (let ((ov (org-make-overlay beg end)))
10967 (org-overlay-put ov 'face 'secondary-selection)
10968 (push ov org-occur-highlights)))
10970 (defun org-remove-occur-highlights (&optional beg end noremove)
10971 "Remove the occur highlights from the buffer.
10972 BEG and END are ignored. If NOREMOVE is nil, remove this function
10973 from the `before-change-functions' in the current buffer."
10974 (interactive)
10975 (unless org-inhibit-highlight-removal
10976 (mapc 'org-delete-overlay org-occur-highlights)
10977 (setq org-occur-highlights nil)
10978 (setq org-occur-parameters nil)
10979 (unless noremove
10980 (remove-hook 'before-change-functions
10981 'org-remove-occur-highlights 'local))))
10983 ;;;; Priorities
10985 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10986 "Regular expression matching the priority indicator.")
10988 (defvar org-remove-priority-next-time nil)
10990 (defun org-priority-up ()
10991 "Increase the priority of the current item."
10992 (interactive)
10993 (org-priority 'up))
10995 (defun org-priority-down ()
10996 "Decrease the priority of the current item."
10997 (interactive)
10998 (org-priority 'down))
11000 (defun org-priority (&optional action)
11001 "Change the priority of an item by ARG.
11002 ACTION can be `set', `up', `down', or a character."
11003 (interactive)
11004 (unless org-enable-priority-commands
11005 (error "Priority commands are disabled"))
11006 (setq action (or action 'set))
11007 (let (current new news have remove)
11008 (save-excursion
11009 (org-back-to-heading t)
11010 (if (looking-at org-priority-regexp)
11011 (setq current (string-to-char (match-string 2))
11012 have t)
11013 (setq current org-default-priority))
11014 (cond
11015 ((eq action 'remove)
11016 (setq remove t new ?\ ))
11017 ((or (eq action 'set)
11018 (if (featurep 'xemacs) (characterp action) (integerp action)))
11019 (if (not (eq action 'set))
11020 (setq new action)
11021 (message "Priority %c-%c, SPC to remove: "
11022 org-highest-priority org-lowest-priority)
11023 (setq new (read-char-exclusive)))
11024 (if (and (= (upcase org-highest-priority) org-highest-priority)
11025 (= (upcase org-lowest-priority) org-lowest-priority))
11026 (setq new (upcase new)))
11027 (cond ((equal new ?\ ) (setq remove t))
11028 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11029 (error "Priority must be between `%c' and `%c'"
11030 org-highest-priority org-lowest-priority))))
11031 ((eq action 'up)
11032 (if (and (not have) (eq last-command this-command))
11033 (setq new org-lowest-priority)
11034 (setq new (if (and org-priority-start-cycle-with-default (not have))
11035 org-default-priority (1- current)))))
11036 ((eq action 'down)
11037 (if (and (not have) (eq last-command this-command))
11038 (setq new org-highest-priority)
11039 (setq new (if (and org-priority-start-cycle-with-default (not have))
11040 org-default-priority (1+ current)))))
11041 (t (error "Invalid action")))
11042 (if (or (< (upcase new) org-highest-priority)
11043 (> (upcase new) org-lowest-priority))
11044 (setq remove t))
11045 (setq news (format "%c" new))
11046 (if have
11047 (if remove
11048 (replace-match "" t t nil 1)
11049 (replace-match news t t nil 2))
11050 (if remove
11051 (error "No priority cookie found in line")
11052 (let ((case-fold-search nil))
11053 (looking-at org-todo-line-regexp))
11054 (if (match-end 2)
11055 (progn
11056 (goto-char (match-end 2))
11057 (insert " [#" news "]"))
11058 (goto-char (match-beginning 3))
11059 (insert "[#" news "] "))))
11060 (org-preserve-lc (org-set-tags nil 'align)))
11061 (if remove
11062 (message "Priority removed")
11063 (message "Priority of current item set to %s" news))))
11065 (defun org-get-priority (s)
11066 "Find priority cookie and return priority."
11067 (save-match-data
11068 (if (not (string-match org-priority-regexp s))
11069 (* 1000 (- org-lowest-priority org-default-priority))
11070 (* 1000 (- org-lowest-priority
11071 (string-to-char (match-string 2 s)))))))
11073 ;;;; Tags
11075 (defvar org-agenda-archives-mode)
11076 (defvar org-map-continue-from nil
11077 "Position from where mapping should continue.
11078 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11080 (defvar org-scanner-tags nil
11081 "The current tag list while the tags scanner is running.")
11082 (defvar org-trust-scanner-tags nil
11083 "Should `org-get-tags-at' use the tags fro the scanner.
11084 This is for internal dynamical scoping only.
11085 When this is non-nil, the function `org-get-tags-at' will return the value
11086 of `org-scanner-tags' instead of building the list by itself. This
11087 can lead to large speed-ups when the tags scanner is used in a file with
11088 many entries, and when the list of tags is retrieved, for example to
11089 obtain a list of properties. Building the tags list for each entry in such
11090 a file becomes an N^2 operation - but with this variable set, it scales
11091 as N.")
11093 (defun org-scan-tags (action matcher &optional todo-only)
11094 "Scan headline tags with inheritance and produce output ACTION.
11096 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11097 or `agenda' to produce an entry list for an agenda view. It can also be
11098 a Lisp form or a function that should be called at each matched headline, in
11099 this case the return value is a list of all return values from these calls.
11101 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11102 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11103 only lines with a TODO keyword are included in the output."
11104 (require 'org-agenda)
11105 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11106 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11107 (org-re
11108 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11109 (props (list 'face 'default
11110 'done-face 'org-agenda-done
11111 'undone-face 'default
11112 'mouse-face 'highlight
11113 'org-not-done-regexp org-not-done-regexp
11114 'org-todo-regexp org-todo-regexp
11115 'help-echo
11116 (format "mouse-2 or RET jump to org file %s"
11117 (abbreviate-file-name
11118 (or (buffer-file-name (buffer-base-buffer))
11119 (buffer-name (buffer-base-buffer)))))))
11120 (case-fold-search nil)
11121 (org-map-continue-from nil)
11122 lspos tags tags-list
11123 (tags-alist (list (cons 0 org-file-tags)))
11124 (llast 0) rtn rtn1 level category i txt
11125 todo marker entry priority)
11126 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11127 (setq action (list 'lambda nil action)))
11128 (save-excursion
11129 (goto-char (point-min))
11130 (when (eq action 'sparse-tree)
11131 (org-overview)
11132 (org-remove-occur-highlights))
11133 (while (re-search-forward re nil t)
11134 (catch :skip
11135 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11136 tags (if (match-end 4) (org-match-string-no-properties 4)))
11137 (goto-char (setq lspos (match-beginning 0)))
11138 (setq level (org-reduced-level (funcall outline-level))
11139 category (org-get-category))
11140 (setq i llast llast level)
11141 ;; remove tag lists from same and sublevels
11142 (while (>= i level)
11143 (when (setq entry (assoc i tags-alist))
11144 (setq tags-alist (delete entry tags-alist)))
11145 (setq i (1- i)))
11146 ;; add the next tags
11147 (when tags
11148 (setq tags (org-split-string tags ":")
11149 tags-alist
11150 (cons (cons level tags) tags-alist)))
11151 ;; compile tags for current headline
11152 (setq tags-list
11153 (if org-use-tag-inheritance
11154 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11155 tags)
11156 org-scanner-tags tags-list)
11157 (when org-use-tag-inheritance
11158 (setcdr (car tags-alist)
11159 (mapcar (lambda (x)
11160 (setq x (copy-sequence x))
11161 (org-add-prop-inherited x))
11162 (cdar tags-alist))))
11163 (when (and tags org-use-tag-inheritance
11164 (or (not (eq t org-use-tag-inheritance))
11165 org-tags-exclude-from-inheritance))
11166 ;; selective inheritance, remove uninherited ones
11167 (setcdr (car tags-alist)
11168 (org-remove-uniherited-tags (cdar tags-alist))))
11169 (when (and (or (not todo-only)
11170 (and (member todo org-not-done-keywords)
11171 (or (not org-agenda-tags-todo-honor-ignore-options)
11172 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11173 (let ((case-fold-search t)) (eval matcher))
11175 (not (member org-archive-tag tags-list))
11176 ;; we have an archive tag, should we use this anyway?
11177 (or (not org-agenda-skip-archived-trees)
11178 (and (eq action 'agenda) org-agenda-archives-mode))))
11179 (unless (eq action 'sparse-tree) (org-agenda-skip))
11181 ;; select this headline
11183 (cond
11184 ((eq action 'sparse-tree)
11185 (and org-highlight-sparse-tree-matches
11186 (org-get-heading) (match-end 0)
11187 (org-highlight-new-match
11188 (match-beginning 0) (match-beginning 1)))
11189 (org-show-context 'tags-tree))
11190 ((eq action 'agenda)
11191 (setq txt (org-format-agenda-item
11193 (concat
11194 (if (eq org-tags-match-list-sublevels 'indented)
11195 (make-string (1- level) ?.) "")
11196 (org-get-heading))
11197 category
11198 tags-list
11200 priority (org-get-priority txt))
11201 (goto-char lspos)
11202 (setq marker (org-agenda-new-marker))
11203 (org-add-props txt props
11204 'org-marker marker 'org-hd-marker marker 'org-category category
11205 'todo-state todo
11206 'priority priority 'type "tagsmatch")
11207 (push txt rtn))
11208 ((functionp action)
11209 (setq org-map-continue-from nil)
11210 (save-excursion
11211 (setq rtn1 (funcall action))
11212 (push rtn1 rtn)))
11213 (t (error "Invalid action")))
11215 ;; if we are to skip sublevels, jump to end of subtree
11216 (unless org-tags-match-list-sublevels
11217 (org-end-of-subtree t)
11218 (backward-char 1))))
11219 ;; Get the correct position from where to continue
11220 (if org-map-continue-from
11221 (goto-char org-map-continue-from)
11222 (and (= (point) lspos) (end-of-line 1)))))
11223 (when (and (eq action 'sparse-tree)
11224 (not org-sparse-tree-open-archived-trees))
11225 (org-hide-archived-subtrees (point-min) (point-max)))
11226 (nreverse rtn)))
11228 (defun org-remove-uniherited-tags (tags)
11229 "Remove all tags that are not inherited from the list TAGS."
11230 (cond
11231 ((eq org-use-tag-inheritance t)
11232 (if org-tags-exclude-from-inheritance
11233 (org-delete-all org-tags-exclude-from-inheritance tags)
11234 tags))
11235 ((not org-use-tag-inheritance) nil)
11236 ((stringp org-use-tag-inheritance)
11237 (delq nil (mapcar
11238 (lambda (x)
11239 (if (and (string-match org-use-tag-inheritance x)
11240 (not (member x org-tags-exclude-from-inheritance)))
11241 x nil))
11242 tags)))
11243 ((listp org-use-tag-inheritance)
11244 (delq nil (mapcar
11245 (lambda (x)
11246 (if (member x org-use-tag-inheritance) x nil))
11247 tags)))))
11249 (defvar todo-only) ;; dynamically scoped
11251 (defun org-match-sparse-tree (&optional todo-only match)
11252 "Create a sparse tree according to tags string MATCH.
11253 MATCH can contain positive and negative selection of tags, like
11254 \"+WORK+URGENT-WITHBOSS\".
11255 If optional argument TODO-ONLY is non-nil, only select lines that are
11256 also TODO lines."
11257 (interactive "P")
11258 (org-prepare-agenda-buffers (list (current-buffer)))
11259 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11261 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11263 (defvar org-cached-props nil)
11264 (defun org-cached-entry-get (pom property)
11265 (if (or (eq t org-use-property-inheritance)
11266 (and (stringp org-use-property-inheritance)
11267 (string-match org-use-property-inheritance property))
11268 (and (listp org-use-property-inheritance)
11269 (member property org-use-property-inheritance)))
11270 ;; Caching is not possible, check it directly
11271 (org-entry-get pom property 'inherit)
11272 ;; Get all properties, so that we can do complicated checks easily
11273 (cdr (assoc property (or org-cached-props
11274 (setq org-cached-props
11275 (org-entry-properties pom)))))))
11277 (defun org-global-tags-completion-table (&optional files)
11278 "Return the list of all tags in all agenda buffer/files."
11279 (save-excursion
11280 (org-uniquify
11281 (delq nil
11282 (apply 'append
11283 (mapcar
11284 (lambda (file)
11285 (set-buffer (find-file-noselect file))
11286 (append (org-get-buffer-tags)
11287 (mapcar (lambda (x) (if (stringp (car-safe x))
11288 (list (car-safe x)) nil))
11289 org-tag-alist)))
11290 (if (and files (car files))
11291 files
11292 (org-agenda-files))))))))
11294 (defun org-make-tags-matcher (match)
11295 "Create the TAGS//TODO matcher form for the selection string MATCH."
11296 ;; todo-only is scoped dynamically into this function, and the function
11297 ;; may change it if the matcher asks for it.
11298 (unless match
11299 ;; Get a new match request, with completion
11300 (let ((org-last-tags-completion-table
11301 (org-global-tags-completion-table)))
11302 (setq match (org-completing-read-no-i
11303 "Match: " 'org-tags-completion-function nil nil nil
11304 'org-tags-history))))
11306 ;; Parse the string and create a lisp form
11307 (let ((match0 match)
11308 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11309 minus tag mm
11310 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11311 orterms term orlist re-p str-p level-p level-op time-p
11312 prop-p pn pv po cat-p gv rest)
11313 (if (string-match "/+" match)
11314 ;; match contains also a todo-matching request
11315 (progn
11316 (setq tagsmatch (substring match 0 (match-beginning 0))
11317 todomatch (substring match (match-end 0)))
11318 (if (string-match "^!" todomatch)
11319 (setq todo-only t todomatch (substring todomatch 1)))
11320 (if (string-match "^\\s-*$" todomatch)
11321 (setq todomatch nil)))
11322 ;; only matching tags
11323 (setq tagsmatch match todomatch nil))
11325 ;; Make the tags matcher
11326 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11327 (setq tagsmatcher t)
11328 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11329 (while (setq term (pop orterms))
11330 (while (and (equal (substring term -1) "\\") orterms)
11331 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11332 (while (string-match re term)
11333 (setq rest (substring term (match-end 0))
11334 minus (and (match-end 1)
11335 (equal (match-string 1 term) "-"))
11336 tag (match-string 2 term)
11337 re-p (equal (string-to-char tag) ?{)
11338 level-p (match-end 4)
11339 prop-p (match-end 5)
11340 mm (cond
11341 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11342 (level-p
11343 (setq level-op (org-op-to-function (match-string 3 term)))
11344 `(,level-op level ,(string-to-number
11345 (match-string 4 term))))
11346 (prop-p
11347 (setq pn (match-string 5 term)
11348 po (match-string 6 term)
11349 pv (match-string 7 term)
11350 cat-p (equal pn "CATEGORY")
11351 re-p (equal (string-to-char pv) ?{)
11352 str-p (equal (string-to-char pv) ?\")
11353 time-p (save-match-data
11354 (string-match "^\"[[<].*[]>]\"$" pv))
11355 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11356 (if time-p (setq pv (org-matcher-time pv)))
11357 (setq po (org-op-to-function po (if time-p 'time str-p)))
11358 (cond
11359 ((equal pn "CATEGORY")
11360 (setq gv '(get-text-property (point) 'org-category)))
11361 ((equal pn "TODO")
11362 (setq gv 'todo))
11364 (setq gv `(org-cached-entry-get nil ,pn))))
11365 (if re-p
11366 (if (eq po 'org<>)
11367 `(not (string-match ,pv (or ,gv "")))
11368 `(string-match ,pv (or ,gv "")))
11369 (if str-p
11370 `(,po (or ,gv "") ,pv)
11371 `(,po (string-to-number (or ,gv ""))
11372 ,(string-to-number pv) ))))
11373 (t `(member ,tag tags-list)))
11374 mm (if minus (list 'not mm) mm)
11375 term rest)
11376 (push mm tagsmatcher))
11377 (push (if (> (length tagsmatcher) 1)
11378 (cons 'and tagsmatcher)
11379 (car tagsmatcher))
11380 orlist)
11381 (setq tagsmatcher nil))
11382 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11383 (setq tagsmatcher
11384 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11385 ;; Make the todo matcher
11386 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11387 (setq todomatcher t)
11388 (setq orterms (org-split-string todomatch "|") orlist nil)
11389 (while (setq term (pop orterms))
11390 (while (string-match re term)
11391 (setq minus (and (match-end 1)
11392 (equal (match-string 1 term) "-"))
11393 kwd (match-string 2 term)
11394 re-p (equal (string-to-char kwd) ?{)
11395 term (substring term (match-end 0))
11396 mm (if re-p
11397 `(string-match ,(substring kwd 1 -1) todo)
11398 (list 'equal 'todo kwd))
11399 mm (if minus (list 'not mm) mm))
11400 (push mm todomatcher))
11401 (push (if (> (length todomatcher) 1)
11402 (cons 'and todomatcher)
11403 (car todomatcher))
11404 orlist)
11405 (setq todomatcher nil))
11406 (setq todomatcher (if (> (length orlist) 1)
11407 (cons 'or orlist) (car orlist))))
11409 ;; Return the string and lisp forms of the matcher
11410 (setq matcher (if todomatcher
11411 (list 'and tagsmatcher todomatcher)
11412 tagsmatcher))
11413 (cons match0 matcher)))
11415 (defun org-op-to-function (op &optional stringp)
11416 "Turn an operator into the appropriate function."
11417 (setq op
11418 (cond
11419 ((equal op "<" ) '(< string< org-time<))
11420 ((equal op ">" ) '(> org-string> org-time>))
11421 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11422 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11423 ((member op '("=" "==")) '(= string= org-time=))
11424 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11425 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11427 (defun org<> (a b) (not (= a b)))
11428 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11429 (defun org-string>= (a b) (not (string< a b)))
11430 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11431 (defun org-string<> (a b) (not (string= a b)))
11432 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11433 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11434 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11435 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11436 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11437 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11438 (defun org-2ft (s)
11439 "Convert S to a floating point time.
11440 If S is already a number, just return it. If it is a string, parse
11441 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11442 (cond
11443 ((numberp s) s)
11444 ((stringp s)
11445 (condition-case nil
11446 (float-time (apply 'encode-time (org-parse-time-string s)))
11447 (error 0.)))
11448 (t 0.)))
11450 (defun org-time-today ()
11451 "Time in seconds today at 0:00.
11452 Returns the float number of seconds since the beginning of the
11453 epoch to the beginning of today (00:00)."
11454 (float-time (apply 'encode-time
11455 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11457 (defun org-matcher-time (s)
11458 "Interpret a time comparison value."
11459 (save-match-data
11460 (cond
11461 ((string= s "<now>") (float-time))
11462 ((string= s "<today>") (org-time-today))
11463 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11464 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11465 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11466 (+ (org-time-today)
11467 (* (string-to-number (match-string 1 s))
11468 (cdr (assoc (match-string 2 s)
11469 '(("d" . 86400.0) ("w" . 604800.0)
11470 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11471 (t (org-2ft s)))))
11473 (defun org-match-any-p (re list)
11474 "Does re match any element of list?"
11475 (setq list (mapcar (lambda (x) (string-match re x)) list))
11476 (delq nil list))
11478 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11479 (defvar org-tags-overlay (org-make-overlay 1 1))
11480 (org-detach-overlay org-tags-overlay)
11482 (defun org-get-local-tags-at (&optional pos)
11483 "Get a list of tags defined in the current headline."
11484 (org-get-tags-at pos 'local))
11486 (defun org-get-local-tags ()
11487 "Get a list of tags defined in the current headline."
11488 (org-get-tags-at nil 'local))
11490 (defun org-get-tags-at (&optional pos local)
11491 "Get a list of all headline tags applicable at POS.
11492 POS defaults to point. If tags are inherited, the list contains
11493 the targets in the same sequence as the headlines appear, i.e.
11494 the tags of the current headline come last.
11495 When LOCAL is non-nil, only return tags from the current headline,
11496 ignore inherited ones."
11497 (interactive)
11498 (if (and org-trust-scanner-tags
11499 (or (not pos) (equal pos (point)))
11500 (not local))
11501 org-scanner-tags
11502 (let (tags ltags lastpos parent)
11503 (save-excursion
11504 (save-restriction
11505 (widen)
11506 (goto-char (or pos (point)))
11507 (save-match-data
11508 (catch 'done
11509 (condition-case nil
11510 (progn
11511 (org-back-to-heading t)
11512 (while (not (equal lastpos (point)))
11513 (setq lastpos (point))
11514 (when (looking-at
11515 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11516 (setq ltags (org-split-string
11517 (org-match-string-no-properties 1) ":"))
11518 (when parent
11519 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11520 (setq tags (append
11521 (if parent
11522 (org-remove-uniherited-tags ltags)
11523 ltags)
11524 tags)))
11525 (or org-use-tag-inheritance (throw 'done t))
11526 (if local (throw 'done t))
11527 (or (org-up-heading-safe) (error nil))
11528 (setq parent t)))
11529 (error nil)))))
11530 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11532 (defun org-add-prop-inherited (s)
11533 (add-text-properties 0 (length s) '(inherited t) s)
11536 (defun org-toggle-tag (tag &optional onoff)
11537 "Toggle the tag TAG for the current line.
11538 If ONOFF is `on' or `off', don't toggle but set to this state."
11539 (let (res current)
11540 (save-excursion
11541 (org-back-to-heading t)
11542 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11543 (point-at-eol) t)
11544 (progn
11545 (setq current (match-string 1))
11546 (replace-match ""))
11547 (setq current ""))
11548 (setq current (nreverse (org-split-string current ":")))
11549 (cond
11550 ((eq onoff 'on)
11551 (setq res t)
11552 (or (member tag current) (push tag current)))
11553 ((eq onoff 'off)
11554 (or (not (member tag current)) (setq current (delete tag current))))
11555 (t (if (member tag current)
11556 (setq current (delete tag current))
11557 (setq res t)
11558 (push tag current))))
11559 (end-of-line 1)
11560 (if current
11561 (progn
11562 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11563 (org-set-tags nil t))
11564 (delete-horizontal-space))
11565 (run-hooks 'org-after-tags-change-hook))
11566 res))
11568 (defun org-align-tags-here (to-col)
11569 ;; Assumes that this is a headline
11570 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11571 (beginning-of-line 1)
11572 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11573 (< pos (match-beginning 2)))
11574 (progn
11575 (setq tags-l (- (match-end 2) (match-beginning 2)))
11576 (goto-char (match-beginning 1))
11577 (insert " ")
11578 (delete-region (point) (1+ (match-beginning 2)))
11579 (setq ncol (max (1+ (current-column))
11580 (1+ col)
11581 (if (> to-col 0)
11582 to-col
11583 (- (abs to-col) tags-l))))
11584 (setq p (point))
11585 (insert (make-string (- ncol (current-column)) ?\ ))
11586 (setq ncol (current-column))
11587 (when indent-tabs-mode (tabify p (point-at-eol)))
11588 (org-move-to-column (min ncol col) t))
11589 (goto-char pos))))
11591 (defun org-set-tags-command (&optional arg just-align)
11592 "Call the set-tags command for the current entry."
11593 (interactive "P")
11594 (if (org-on-heading-p)
11595 (org-set-tags arg just-align)
11596 (save-excursion
11597 (org-back-to-heading t)
11598 (org-set-tags arg just-align))))
11600 (defun org-set-tags-to (data)
11601 "Set the tags of the current entry to DATA, replacing the current tags.
11602 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11603 If DATA is nil or the empty string, any tags will be removed."
11604 (interactive "sTags: ")
11605 (setq data
11606 (cond
11607 ((eq data nil) "")
11608 ((equal data "") "")
11609 ((stringp data)
11610 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11611 ":"))
11612 ((listp data)
11613 (concat ":" (mapconcat 'identity data ":") ":"))
11614 (t nil)))
11615 (when data
11616 (save-excursion
11617 (org-back-to-heading t)
11618 (when (looking-at org-complex-heading-regexp)
11619 (if (match-end 5)
11620 (progn
11621 (goto-char (match-beginning 5))
11622 (insert data)
11623 (delete-region (point) (point-at-eol))
11624 (org-set-tags nil 'align))
11625 (goto-char (point-at-eol))
11626 (insert " " data)
11627 (org-set-tags nil 'align)))
11628 (beginning-of-line 1)
11629 (if (looking-at ".*?\\([ \t]+\\)$")
11630 (delete-region (match-beginning 1) (match-end 1))))))
11632 (defun org-set-tags (&optional arg just-align)
11633 "Set the tags for the current headline.
11634 With prefix ARG, realign all tags in headings in the current buffer."
11635 (interactive "P")
11636 (let* ((re (concat "^" outline-regexp))
11637 (current (org-get-tags-string))
11638 (col (current-column))
11639 (org-setting-tags t)
11640 table current-tags inherited-tags ; computed below when needed
11641 tags p0 c0 c1 rpl)
11642 (if arg
11643 (save-excursion
11644 (goto-char (point-min))
11645 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11646 (while (re-search-forward re nil t)
11647 (org-set-tags nil t)
11648 (end-of-line 1)))
11649 (message "All tags realigned to column %d" org-tags-column))
11650 (if just-align
11651 (setq tags current)
11652 ;; Get a new set of tags from the user
11653 (save-excursion
11654 (setq table (append org-tag-persistent-alist
11655 (or org-tag-alist (org-get-buffer-tags)))
11656 org-last-tags-completion-table table
11657 current-tags (org-split-string current ":")
11658 inherited-tags (nreverse
11659 (nthcdr (length current-tags)
11660 (nreverse (org-get-tags-at))))
11661 tags
11662 (if (or (eq t org-use-fast-tag-selection)
11663 (and org-use-fast-tag-selection
11664 (delq nil (mapcar 'cdr table))))
11665 (org-fast-tag-selection
11666 current-tags inherited-tags table
11667 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11668 (let ((org-add-colon-after-tag-completion t))
11669 (org-trim
11670 (org-without-partial-completion
11671 (org-icompleting-read "Tags: " 'org-tags-completion-function
11672 nil nil current 'org-tags-history)))))))
11673 (while (string-match "[-+&]+" tags)
11674 ;; No boolean logic, just a list
11675 (setq tags (replace-match ":" t t tags))))
11677 (if org-tags-sort-function
11678 (setq tags (mapconcat 'identity
11679 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11680 org-tags-sort-function) ":")))
11682 (if (string-match "\\`[\t ]*\\'" tags)
11683 (setq tags "")
11684 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11685 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11687 ;; Insert new tags at the correct column
11688 (beginning-of-line 1)
11689 (cond
11690 ((and (equal current "") (equal tags "")))
11691 ((re-search-forward
11692 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11693 (point-at-eol) t)
11694 (if (equal tags "")
11695 (setq rpl "")
11696 (goto-char (match-beginning 0))
11697 (setq c0 (current-column) p0 (point)
11698 c1 (max (1+ c0) (if (> org-tags-column 0)
11699 org-tags-column
11700 (- (- org-tags-column) (length tags))))
11701 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11702 (replace-match rpl t t)
11703 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11704 tags)
11705 (t (error "Tags alignment failed")))
11706 (org-move-to-column col)
11707 (unless just-align
11708 (run-hooks 'org-after-tags-change-hook)))))
11710 (defun org-change-tag-in-region (beg end tag off)
11711 "Add or remove TAG for each entry in the region.
11712 This works in the agenda, and also in an org-mode buffer."
11713 (interactive
11714 (list (region-beginning) (region-end)
11715 (let ((org-last-tags-completion-table
11716 (if (org-mode-p)
11717 (org-get-buffer-tags)
11718 (org-global-tags-completion-table))))
11719 (org-icompleting-read
11720 "Tag: " 'org-tags-completion-function nil nil nil
11721 'org-tags-history))
11722 (progn
11723 (message "[s]et or [r]emove? ")
11724 (equal (read-char-exclusive) ?r))))
11725 (if (fboundp 'deactivate-mark) (deactivate-mark))
11726 (let ((agendap (equal major-mode 'org-agenda-mode))
11727 l1 l2 m buf pos newhead (cnt 0))
11728 (goto-char end)
11729 (setq l2 (1- (org-current-line)))
11730 (goto-char beg)
11731 (setq l1 (org-current-line))
11732 (loop for l from l1 to l2 do
11733 (org-goto-line l)
11734 (setq m (get-text-property (point) 'org-hd-marker))
11735 (when (or (and (org-mode-p) (org-on-heading-p))
11736 (and agendap m))
11737 (setq buf (if agendap (marker-buffer m) (current-buffer))
11738 pos (if agendap m (point)))
11739 (with-current-buffer buf
11740 (save-excursion
11741 (save-restriction
11742 (goto-char pos)
11743 (setq cnt (1+ cnt))
11744 (org-toggle-tag tag (if off 'off 'on))
11745 (setq newhead (org-get-heading)))))
11746 (and agendap (org-agenda-change-all-lines newhead m))))
11747 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11749 (defun org-tags-completion-function (string predicate &optional flag)
11750 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11751 (confirm (lambda (x) (stringp (car x)))))
11752 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11753 (setq s1 (match-string 1 string)
11754 s2 (match-string 2 string))
11755 (setq s1 "" s2 string))
11756 (cond
11757 ((eq flag nil)
11758 ;; try completion
11759 (setq rtn (try-completion s2 ctable confirm))
11760 (if (stringp rtn)
11761 (setq rtn
11762 (concat s1 s2 (substring rtn (length s2))
11763 (if (and org-add-colon-after-tag-completion
11764 (assoc rtn ctable))
11765 ":" ""))))
11766 rtn)
11767 ((eq flag t)
11768 ;; all-completions
11769 (all-completions s2 ctable confirm)
11771 ((eq flag 'lambda)
11772 ;; exact match?
11773 (assoc s2 ctable)))
11776 (defun org-fast-tag-insert (kwd tags face &optional end)
11777 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11778 (insert (format "%-12s" (concat kwd ":"))
11779 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11780 (or end "")))
11782 (defun org-fast-tag-show-exit (flag)
11783 (save-excursion
11784 (org-goto-line 3)
11785 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11786 (replace-match ""))
11787 (when flag
11788 (end-of-line 1)
11789 (org-move-to-column (- (window-width) 19) t)
11790 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11792 (defun org-set-current-tags-overlay (current prefix)
11793 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11794 (if (featurep 'xemacs)
11795 (org-overlay-display org-tags-overlay (concat prefix s)
11796 'secondary-selection)
11797 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11798 (org-overlay-display org-tags-overlay (concat prefix s)))))
11800 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11801 "Fast tag selection with single keys.
11802 CURRENT is the current list of tags in the headline, INHERITED is the
11803 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11804 possibly with grouping information. TODO-TABLE is a similar table with
11805 TODO keywords, should these have keys assigned to them.
11806 If the keys are nil, a-z are automatically assigned.
11807 Returns the new tags string, or nil to not change the current settings."
11808 (let* ((fulltable (append table todo-table))
11809 (maxlen (apply 'max (mapcar
11810 (lambda (x)
11811 (if (stringp (car x)) (string-width (car x)) 0))
11812 fulltable)))
11813 (buf (current-buffer))
11814 (expert (eq org-fast-tag-selection-single-key 'expert))
11815 (buffer-tags nil)
11816 (fwidth (+ maxlen 3 1 3))
11817 (ncol (/ (- (window-width) 4) fwidth))
11818 (i-face 'org-done)
11819 (c-face 'org-todo)
11820 tg cnt e c char c1 c2 ntable tbl rtn
11821 ov-start ov-end ov-prefix
11822 (exit-after-next org-fast-tag-selection-single-key)
11823 (done-keywords org-done-keywords)
11824 groups ingroup)
11825 (save-excursion
11826 (beginning-of-line 1)
11827 (if (looking-at
11828 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11829 (setq ov-start (match-beginning 1)
11830 ov-end (match-end 1)
11831 ov-prefix "")
11832 (setq ov-start (1- (point-at-eol))
11833 ov-end (1+ ov-start))
11834 (skip-chars-forward "^\n\r")
11835 (setq ov-prefix
11836 (concat
11837 (buffer-substring (1- (point)) (point))
11838 (if (> (current-column) org-tags-column)
11840 (make-string (- org-tags-column (current-column)) ?\ ))))))
11841 (org-move-overlay org-tags-overlay ov-start ov-end)
11842 (save-window-excursion
11843 (if expert
11844 (set-buffer (get-buffer-create " *Org tags*"))
11845 (delete-other-windows)
11846 (split-window-vertically)
11847 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11848 (erase-buffer)
11849 (org-set-local 'org-done-keywords done-keywords)
11850 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11851 (org-fast-tag-insert "Current" current c-face "\n\n")
11852 (org-fast-tag-show-exit exit-after-next)
11853 (org-set-current-tags-overlay current ov-prefix)
11854 (setq tbl fulltable char ?a cnt 0)
11855 (while (setq e (pop tbl))
11856 (cond
11857 ((equal (car e) :startgroup)
11858 (push '() groups) (setq ingroup t)
11859 (when (not (= cnt 0))
11860 (setq cnt 0)
11861 (insert "\n"))
11862 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11863 ((equal (car e) :endgroup)
11864 (setq ingroup nil cnt 0)
11865 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11866 ((equal e '(:newline))
11867 (when (not (= cnt 0))
11868 (setq cnt 0)
11869 (insert "\n")
11870 (setq e (car tbl))
11871 (while (equal (car tbl) '(:newline))
11872 (insert "\n")
11873 (setq tbl (cdr tbl)))))
11875 (setq tg (copy-sequence (car e)) c2 nil)
11876 (if (cdr e)
11877 (setq c (cdr e))
11878 ;; automatically assign a character.
11879 (setq c1 (string-to-char
11880 (downcase (substring
11881 tg (if (= (string-to-char tg) ?@) 1 0)))))
11882 (if (or (rassoc c1 ntable) (rassoc c1 table))
11883 (while (or (rassoc char ntable) (rassoc char table))
11884 (setq char (1+ char)))
11885 (setq c2 c1))
11886 (setq c (or c2 char)))
11887 (if ingroup (push tg (car groups)))
11888 (setq tg (org-add-props tg nil 'face
11889 (cond
11890 ((not (assoc tg table))
11891 (org-get-todo-face tg))
11892 ((member tg current) c-face)
11893 ((member tg inherited) i-face)
11894 (t nil))))
11895 (if (and (= cnt 0) (not ingroup)) (insert " "))
11896 (insert "[" c "] " tg (make-string
11897 (- fwidth 4 (length tg)) ?\ ))
11898 (push (cons tg c) ntable)
11899 (when (= (setq cnt (1+ cnt)) ncol)
11900 (insert "\n")
11901 (if ingroup (insert " "))
11902 (setq cnt 0)))))
11903 (setq ntable (nreverse ntable))
11904 (insert "\n")
11905 (goto-char (point-min))
11906 (if (not expert) (org-fit-window-to-buffer))
11907 (setq rtn
11908 (catch 'exit
11909 (while t
11910 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11911 (if (not groups) "no " "")
11912 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11913 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11914 (cond
11915 ((= c ?\r) (throw 'exit t))
11916 ((= c ?!)
11917 (setq groups (not groups))
11918 (goto-char (point-min))
11919 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11920 ((= c ?\C-c)
11921 (if (not expert)
11922 (org-fast-tag-show-exit
11923 (setq exit-after-next (not exit-after-next)))
11924 (setq expert nil)
11925 (delete-other-windows)
11926 (split-window-vertically)
11927 (org-switch-to-buffer-other-window " *Org tags*")
11928 (org-fit-window-to-buffer)))
11929 ((or (= c ?\C-g)
11930 (and (= c ?q) (not (rassoc c ntable))))
11931 (org-detach-overlay org-tags-overlay)
11932 (setq quit-flag t))
11933 ((= c ?\ )
11934 (setq current nil)
11935 (if exit-after-next (setq exit-after-next 'now)))
11936 ((= c ?\t)
11937 (condition-case nil
11938 (setq tg (org-icompleting-read
11939 "Tag: "
11940 (or buffer-tags
11941 (with-current-buffer buf
11942 (org-get-buffer-tags)))))
11943 (quit (setq tg "")))
11944 (when (string-match "\\S-" tg)
11945 (add-to-list 'buffer-tags (list tg))
11946 (if (member tg current)
11947 (setq current (delete tg current))
11948 (push tg current)))
11949 (if exit-after-next (setq exit-after-next 'now)))
11950 ((setq e (rassoc c todo-table) tg (car e))
11951 (with-current-buffer buf
11952 (save-excursion (org-todo tg)))
11953 (if exit-after-next (setq exit-after-next 'now)))
11954 ((setq e (rassoc c ntable) tg (car e))
11955 (if (member tg current)
11956 (setq current (delete tg current))
11957 (loop for g in groups do
11958 (if (member tg g)
11959 (mapc (lambda (x)
11960 (setq current (delete x current)))
11961 g)))
11962 (push tg current))
11963 (if exit-after-next (setq exit-after-next 'now))))
11965 ;; Create a sorted list
11966 (setq current
11967 (sort current
11968 (lambda (a b)
11969 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11970 (if (eq exit-after-next 'now) (throw 'exit t))
11971 (goto-char (point-min))
11972 (beginning-of-line 2)
11973 (delete-region (point) (point-at-eol))
11974 (org-fast-tag-insert "Current" current c-face)
11975 (org-set-current-tags-overlay current ov-prefix)
11976 (while (re-search-forward
11977 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11978 (setq tg (match-string 1))
11979 (add-text-properties
11980 (match-beginning 1) (match-end 1)
11981 (list 'face
11982 (cond
11983 ((member tg current) c-face)
11984 ((member tg inherited) i-face)
11985 (t (get-text-property (match-beginning 1) 'face))))))
11986 (goto-char (point-min)))))
11987 (org-detach-overlay org-tags-overlay)
11988 (if rtn
11989 (mapconcat 'identity current ":")
11990 nil))))
11992 (defun org-get-tags-string ()
11993 "Get the TAGS string in the current headline."
11994 (unless (org-on-heading-p t)
11995 (error "Not on a heading"))
11996 (save-excursion
11997 (beginning-of-line 1)
11998 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11999 (org-match-string-no-properties 1)
12000 "")))
12002 (defun org-get-tags ()
12003 "Get the list of tags specified in the current headline."
12004 (org-split-string (org-get-tags-string) ":"))
12006 (defun org-get-buffer-tags ()
12007 "Get a table of all tags used in the buffer, for completion."
12008 (let (tags)
12009 (save-excursion
12010 (goto-char (point-min))
12011 (while (re-search-forward
12012 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12013 (when (equal (char-after (point-at-bol 0)) ?*)
12014 (mapc (lambda (x) (add-to-list 'tags x))
12015 (org-split-string (org-match-string-no-properties 1) ":")))))
12016 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12017 (mapcar 'list tags)))
12019 ;;;; The mapping API
12021 ;;;###autoload
12022 (defun org-map-entries (func &optional match scope &rest skip)
12023 "Call FUNC at each headline selected by MATCH in SCOPE.
12025 FUNC is a function or a lisp form. The function will be called without
12026 arguments, with the cursor positioned at the beginning of the headline.
12027 The return values of all calls to the function will be collected and
12028 returned as a list.
12030 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12031 does not need to preserve point. After evaluation, the cursor will be
12032 moved to the end of the line (presumably of the headline of the
12033 processed entry) and search continues from there. Under some
12034 circumstances, this may not produce the wanted results. For example,
12035 if you have removed (e.g. archived) the current (sub)tree it could
12036 mean that the next entry will be skipped entirely. In such cases, you
12037 can specify the position from where search should continue by making
12038 FUNC set the variable `org-map-continue-from' to the desired buffer
12039 position.
12041 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12042 Only headlines that are matched by this query will be considered during
12043 the iteration. When MATCH is nil or t, all headlines will be
12044 visited by the iteration.
12046 SCOPE determines the scope of this command. It can be any of:
12048 nil The current buffer, respecting the restriction if any
12049 tree The subtree started with the entry at point
12050 file The current buffer, without restriction
12051 file-with-archives
12052 The current buffer, and any archives associated with it
12053 agenda All agenda files
12054 agenda-with-archives
12055 All agenda files with any archive files associated with them
12056 \(file1 file2 ...)
12057 If this is a list, all files in the list will be scanned
12059 The remaining args are treated as settings for the skipping facilities of
12060 the scanner. The following items can be given here:
12062 archive skip trees with the archive tag.
12063 comment skip trees with the COMMENT keyword
12064 function or Emacs Lisp form:
12065 will be used as value for `org-agenda-skip-function', so whenever
12066 the function returns t, FUNC will not be called for that
12067 entry and search will continue from the point where the
12068 function leaves it.
12070 If your function needs to retrieve the tags including inherited tags
12071 at the *current* entry, you can use the value of the variable
12072 `org-scanner-tags' which will be much faster than getting the value
12073 with `org-get-tags-at'. If your function gets properties with
12074 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12075 to t around the call to `org-entry-properties' to get the same speedup.
12076 Note that if your function moves around to retrieve tags and properties at
12077 a *different* entry, you cannot use these techniques."
12078 (let* ((org-agenda-archives-mode nil) ; just to make sure
12079 (org-agenda-skip-archived-trees (memq 'archive skip))
12080 (org-agenda-skip-comment-trees (memq 'comment skip))
12081 (org-agenda-skip-function
12082 (car (org-delete-all '(comment archive) skip)))
12083 (org-tags-match-list-sublevels t)
12084 matcher file res
12085 org-todo-keywords-for-agenda
12086 org-done-keywords-for-agenda
12087 org-todo-keyword-alist-for-agenda
12088 org-drawers-for-agenda
12089 org-tag-alist-for-agenda)
12091 (cond
12092 ((eq match t) (setq matcher t))
12093 ((eq match nil) (setq matcher t))
12094 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12096 (save-excursion
12097 (save-restriction
12098 (when (eq scope 'tree)
12099 (org-back-to-heading t)
12100 (org-narrow-to-subtree)
12101 (setq scope nil))
12103 (if (not scope)
12104 (progn
12105 (org-prepare-agenda-buffers
12106 (list (buffer-file-name (current-buffer))))
12107 (setq res (org-scan-tags func matcher)))
12108 ;; Get the right scope
12109 (cond
12110 ((and scope (listp scope) (symbolp (car scope)))
12111 (setq scope (eval scope)))
12112 ((eq scope 'agenda)
12113 (setq scope (org-agenda-files t)))
12114 ((eq scope 'agenda-with-archives)
12115 (setq scope (org-agenda-files t))
12116 (setq scope (org-add-archive-files scope)))
12117 ((eq scope 'file)
12118 (setq scope (list (buffer-file-name))))
12119 ((eq scope 'file-with-archives)
12120 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12121 (org-prepare-agenda-buffers scope)
12122 (while (setq file (pop scope))
12123 (with-current-buffer (org-find-base-buffer-visiting file)
12124 (save-excursion
12125 (save-restriction
12126 (widen)
12127 (goto-char (point-min))
12128 (setq res (append res (org-scan-tags func matcher))))))))))
12129 res))
12131 ;;;; Properties
12133 ;;; Setting and retrieving properties
12135 (defconst org-special-properties
12136 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12137 "TIMESTAMP" "TIMESTAMP_IA")
12138 "The special properties valid in Org-mode.
12140 These are properties that are not defined in the property drawer,
12141 but in some other way.")
12143 (defconst org-default-properties
12144 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12145 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12146 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12147 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12148 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12149 "CLOCK_MODELINE_TOTAL" "STYLE")
12150 "Some properties that are used by Org-mode for various purposes.
12151 Being in this list makes sure that they are offered for completion.")
12153 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12154 "Regular expression matching the first line of a property drawer.")
12156 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12157 "Regular expression matching the first line of a property drawer.")
12159 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12160 "Regular expression matching the first line of a property drawer.")
12162 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12163 "Regular expression matching the first line of a property drawer.")
12165 (defconst org-property-drawer-re
12166 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12167 org-property-end-re "\\)\n?")
12168 "Matches an entire property drawer.")
12170 (defconst org-clock-drawer-re
12171 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12172 org-property-end-re "\\)\n?")
12173 "Matches an entire clock drawer.")
12175 (defun org-property-action ()
12176 "Do an action on properties."
12177 (interactive)
12178 (let (c)
12179 (org-at-property-p)
12180 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12181 (setq c (read-char-exclusive))
12182 (cond
12183 ((equal c ?s)
12184 (call-interactively 'org-set-property))
12185 ((equal c ?d)
12186 (call-interactively 'org-delete-property))
12187 ((equal c ?D)
12188 (call-interactively 'org-delete-property-globally))
12189 ((equal c ?c)
12190 (call-interactively 'org-compute-property-at-point))
12191 (t (error "No such property action %c" c)))))
12193 (defun org-set-effort (&optional value)
12194 "Set the effort property of the current entry.
12195 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12196 allowed value."
12197 (interactive "P")
12198 (if (equal value 0) (setq value 10))
12199 (let* ((completion-ignore-case t)
12200 (prop org-effort-property)
12201 (cur (org-entry-get nil prop))
12202 (allowed (org-property-get-allowed-values nil prop 'table))
12203 (existing (mapcar 'list (org-property-values prop)))
12205 (val (cond
12206 ((stringp value) value)
12207 ((and allowed (integerp value))
12208 (or (car (nth (1- value) allowed))
12209 (car (org-last allowed))))
12210 (allowed
12211 (message "Select 1-9,0, [RET%s]: %s"
12212 (if cur (concat "=" cur) "")
12213 (mapconcat 'car allowed " "))
12214 (setq rpl (read-char-exclusive))
12215 (if (equal rpl ?\r)
12217 (setq rpl (- rpl ?0))
12218 (if (equal rpl 0) (setq rpl 10))
12219 (if (and (> rpl 0) (<= rpl (length allowed)))
12220 (car (nth (1- rpl) allowed))
12221 (org-completing-read "Value: " allowed nil))))
12223 (let (org-completion-use-ido org-completion-use-iswitchb)
12224 (org-completing-read
12225 (concat "Value " (if (and cur (string-match "\\S-" cur))
12226 (concat "[" cur "]") "")
12227 ": ")
12228 existing nil nil "" nil cur))))))
12229 (unless (equal (org-entry-get nil prop) val)
12230 (org-entry-put nil prop val))
12231 (message "%s is now %s" prop val)))
12233 (defun org-at-property-p ()
12234 "Is the cursor in a property line?"
12235 ;; FIXME: Does not check if we are actually in the drawer.
12236 ;; FIXME: also returns true on any drawers.....
12237 ;; This is used by C-c C-c for property action.
12238 (save-excursion
12239 (beginning-of-line 1)
12240 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12242 (defun org-get-property-block (&optional beg end force)
12243 "Return the (beg . end) range of the body of the property drawer.
12244 BEG and END can be beginning and end of subtree, if not given
12245 they will be found.
12246 If the drawer does not exist and FORCE is non-nil, create the drawer."
12247 (catch 'exit
12248 (save-excursion
12249 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12250 (end (or end (progn (outline-next-heading) (point)))))
12251 (goto-char beg)
12252 (if (re-search-forward org-property-start-re end t)
12253 (setq beg (1+ (match-end 0)))
12254 (if force
12255 (save-excursion
12256 (org-insert-property-drawer)
12257 (setq end (progn (outline-next-heading) (point))))
12258 (throw 'exit nil))
12259 (goto-char beg)
12260 (if (re-search-forward org-property-start-re end t)
12261 (setq beg (1+ (match-end 0)))))
12262 (if (re-search-forward org-property-end-re end t)
12263 (setq end (match-beginning 0))
12264 (or force (throw 'exit nil))
12265 (goto-char beg)
12266 (setq end beg)
12267 (org-indent-line-function)
12268 (insert ":END:\n"))
12269 (cons beg end)))))
12271 (defun org-entry-properties (&optional pom which)
12272 "Get all properties of the entry at point-or-marker POM.
12273 This includes the TODO keyword, the tags, time strings for deadline,
12274 scheduled, and clocking, and any additional properties defined in the
12275 entry. The return value is an alist, keys may occur multiple times
12276 if the property key was used several times.
12277 POM may also be nil, in which case the current entry is used.
12278 If WHICH is nil or `all', get all properties. If WHICH is
12279 `special' or `standard', only get that subclass."
12280 (setq which (or which 'all))
12281 (org-with-point-at pom
12282 (let ((clockstr (substring org-clock-string 0 -1))
12283 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12284 beg end range props sum-props key value string clocksum)
12285 (save-excursion
12286 (when (condition-case nil
12287 (and (org-mode-p) (org-back-to-heading t))
12288 (error nil))
12289 (setq beg (point))
12290 (setq sum-props (get-text-property (point) 'org-summaries))
12291 (setq clocksum (get-text-property (point) :org-clock-minutes))
12292 (outline-next-heading)
12293 (setq end (point))
12294 (when (memq which '(all special))
12295 ;; Get the special properties, like TODO and tags
12296 (goto-char beg)
12297 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12298 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12299 (when (looking-at org-priority-regexp)
12300 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12301 (when (and (setq value (org-get-tags-string))
12302 (string-match "\\S-" value))
12303 (push (cons "TAGS" value) props))
12304 (when (setq value (org-get-tags-at))
12305 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12306 props))
12307 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12308 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12309 string (if (equal key clockstr)
12310 (org-no-properties
12311 (org-trim
12312 (buffer-substring
12313 (match-beginning 3) (goto-char (point-at-eol)))))
12314 (substring (org-match-string-no-properties 3) 1 -1)))
12315 (unless key
12316 (if (= (char-after (match-beginning 3)) ?\[)
12317 (setq key "TIMESTAMP_IA")
12318 (setq key "TIMESTAMP")))
12319 (when (or (equal key clockstr) (not (assoc key props)))
12320 (push (cons key string) props)))
12324 (when (memq which '(all standard))
12325 ;; Get the standard properties, like :PROP: ...
12326 (setq range (org-get-property-block beg end))
12327 (when range
12328 (goto-char (car range))
12329 (while (re-search-forward
12330 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12331 (cdr range) t)
12332 (setq key (org-match-string-no-properties 1)
12333 value (org-trim (or (org-match-string-no-properties 2) "")))
12334 (unless (member key excluded)
12335 (push (cons key (or value "")) props)))))
12336 (if clocksum
12337 (push (cons "CLOCKSUM"
12338 (org-columns-number-to-string (/ (float clocksum) 60.)
12339 'add_times))
12340 props))
12341 (unless (assoc "CATEGORY" props)
12342 (setq value (or (org-get-category)
12343 (progn (org-refresh-category-properties)
12344 (org-get-category))))
12345 (push (cons "CATEGORY" value) props))
12346 (append sum-props (nreverse props)))))))
12348 (defun org-entry-get (pom property &optional inherit)
12349 "Get value of PROPERTY for entry at point-or-marker POM.
12350 If INHERIT is non-nil and the entry does not have the property,
12351 then also check higher levels of the hierarchy.
12352 If INHERIT is the symbol `selective', use inheritance only if the setting
12353 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12354 If the property is present but empty, the return value is the empty string.
12355 If the property is not present at all, nil is returned."
12356 (org-with-point-at pom
12357 (if (and inherit (if (eq inherit 'selective)
12358 (org-property-inherit-p property)
12360 (org-entry-get-with-inheritance property)
12361 (if (member property org-special-properties)
12362 ;; We need a special property. Use brute force, get all properties.
12363 (cdr (assoc property (org-entry-properties nil 'special)))
12364 (let ((range (org-get-property-block)))
12365 (if (and range
12366 (goto-char (car range))
12367 (re-search-forward
12368 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12369 (cdr range) t))
12370 ;; Found the property, return it.
12371 (if (match-end 1)
12372 (org-match-string-no-properties 1)
12373 "")))))))
12375 (defun org-property-or-variable-value (var &optional inherit)
12376 "Check if there is a property fixing the value of VAR.
12377 If yes, return this value. If not, return the current value of the variable."
12378 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12379 (if (and prop (stringp prop) (string-match "\\S-" prop))
12380 (read prop)
12381 (symbol-value var))))
12383 (defun org-entry-delete (pom property)
12384 "Delete the property PROPERTY from entry at point-or-marker POM."
12385 (org-with-point-at pom
12386 (if (member property org-special-properties)
12387 nil ; cannot delete these properties.
12388 (let ((range (org-get-property-block)))
12389 (if (and range
12390 (goto-char (car range))
12391 (re-search-forward
12392 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12393 (cdr range) t))
12394 (progn
12395 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12397 nil)))))
12399 ;; Multi-values properties are properties that contain multiple values
12400 ;; These values are assumed to be single words, separated by whitespace.
12401 (defun org-entry-add-to-multivalued-property (pom property value)
12402 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12403 (let* ((old (org-entry-get pom property))
12404 (values (and old (org-split-string old "[ \t]"))))
12405 (setq value (org-entry-protect-space value))
12406 (unless (member value values)
12407 (setq values (cons value values))
12408 (org-entry-put pom property
12409 (mapconcat 'identity values " ")))))
12411 (defun org-entry-remove-from-multivalued-property (pom property value)
12412 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12413 (let* ((old (org-entry-get pom property))
12414 (values (and old (org-split-string old "[ \t]"))))
12415 (setq value (org-entry-protect-space value))
12416 (when (member value values)
12417 (setq values (delete value values))
12418 (org-entry-put pom property
12419 (mapconcat 'identity values " ")))))
12421 (defun org-entry-member-in-multivalued-property (pom property value)
12422 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12423 (let* ((old (org-entry-get pom property))
12424 (values (and old (org-split-string old "[ \t]"))))
12425 (setq value (org-entry-protect-space value))
12426 (member value values)))
12428 (defun org-entry-get-multivalued-property (pom property)
12429 "Return a list of values in a multivalued property."
12430 (let* ((value (org-entry-get pom property))
12431 (values (and value (org-split-string value "[ \t]"))))
12432 (mapcar 'org-entry-restore-space values)))
12434 (defun org-entry-put-multivalued-property (pom property &rest values)
12435 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12436 VALUES should be a list of strings. Spaces will be protected."
12437 (org-entry-put pom property
12438 (mapconcat 'org-entry-protect-space values " "))
12439 (let* ((value (org-entry-get pom property))
12440 (values (and value (org-split-string value "[ \t]"))))
12441 (mapcar 'org-entry-restore-space values)))
12443 (defun org-entry-protect-space (s)
12444 "Protect spaces and newline in string S."
12445 (while (string-match " " s)
12446 (setq s (replace-match "%20" t t s)))
12447 (while (string-match "\n" s)
12448 (setq s (replace-match "%0A" t t s)))
12451 (defun org-entry-restore-space (s)
12452 "Restore spaces and newline in string S."
12453 (while (string-match "%20" s)
12454 (setq s (replace-match " " t t s)))
12455 (while (string-match "%0A" s)
12456 (setq s (replace-match "\n" t t s)))
12459 (defvar org-entry-property-inherited-from (make-marker)
12460 "Marker pointing to the entry from where a property was inherited.
12461 Each call to `org-entry-get-with-inheritance' will set this marker to the
12462 location of the entry where the inheritance search matched. If there was
12463 no match, the marker will point nowhere.
12464 Note that also `org-entry-get' calls this function, if the INHERIT flag
12465 is set.")
12467 (defun org-entry-get-with-inheritance (property)
12468 "Get entry property, and search higher levels if not present."
12469 (move-marker org-entry-property-inherited-from nil)
12470 (let (tmp)
12471 (save-excursion
12472 (save-restriction
12473 (widen)
12474 (catch 'ex
12475 (while t
12476 (when (setq tmp (org-entry-get nil property))
12477 (org-back-to-heading t)
12478 (move-marker org-entry-property-inherited-from (point))
12479 (throw 'ex tmp))
12480 (or (org-up-heading-safe) (throw 'ex nil)))))
12481 (or tmp
12482 (cdr (assoc property org-file-properties))
12483 (cdr (assoc property org-global-properties))
12484 (cdr (assoc property org-global-properties-fixed))))))
12486 (defun org-entry-put (pom property value)
12487 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12488 (org-with-point-at pom
12489 (org-back-to-heading t)
12490 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12491 range)
12492 (cond
12493 ((equal property "TODO")
12494 (when (and (stringp value) (string-match "\\S-" value)
12495 (not (member value org-todo-keywords-1)))
12496 (error "\"%s\" is not a valid TODO state" value))
12497 (if (or (not value)
12498 (not (string-match "\\S-" value)))
12499 (setq value 'none))
12500 (org-todo value)
12501 (org-set-tags nil 'align))
12502 ((equal property "PRIORITY")
12503 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12504 (string-to-char value) ?\ ))
12505 (org-set-tags nil 'align))
12506 ((equal property "SCHEDULED")
12507 (if (re-search-forward org-scheduled-time-regexp end t)
12508 (cond
12509 ((eq value 'earlier) (org-timestamp-change -1 'day))
12510 ((eq value 'later) (org-timestamp-change 1 'day))
12511 (t (call-interactively 'org-schedule)))
12512 (call-interactively 'org-schedule)))
12513 ((equal property "DEADLINE")
12514 (if (re-search-forward org-deadline-time-regexp end t)
12515 (cond
12516 ((eq value 'earlier) (org-timestamp-change -1 'day))
12517 ((eq value 'later) (org-timestamp-change 1 'day))
12518 (t (call-interactively 'org-deadline)))
12519 (call-interactively 'org-deadline)))
12520 ((member property org-special-properties)
12521 (error "The %s property can not yet be set with `org-entry-put'"
12522 property))
12523 (t ; a non-special property
12524 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12525 (setq range (org-get-property-block beg end 'force))
12526 (goto-char (car range))
12527 (if (re-search-forward
12528 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12529 (progn
12530 (delete-region (match-beginning 1) (match-end 1))
12531 (goto-char (match-beginning 1)))
12532 (goto-char (cdr range))
12533 (insert "\n")
12534 (backward-char 1)
12535 (org-indent-line-function)
12536 (insert ":" property ":"))
12537 (and value (insert " " value))
12538 (org-indent-line-function)))))))
12540 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12541 "Get all property keys in the current buffer.
12542 With INCLUDE-SPECIALS, also list the special properties that reflect things
12543 like tags and TODO state.
12544 With INCLUDE-DEFAULTS, also include properties that has special meaning
12545 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12546 With INCLUDE-COLUMNS, also include property names given in COLUMN
12547 formats in the current buffer."
12548 (let (rtn range cfmt s p)
12549 (save-excursion
12550 (save-restriction
12551 (widen)
12552 (goto-char (point-min))
12553 (while (re-search-forward org-property-start-re nil t)
12554 (setq range (org-get-property-block))
12555 (goto-char (car range))
12556 (while (re-search-forward
12557 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12558 (cdr range) t)
12559 (add-to-list 'rtn (org-match-string-no-properties 1)))
12560 (outline-next-heading))))
12562 (when include-specials
12563 (setq rtn (append org-special-properties rtn)))
12565 (when include-defaults
12566 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12567 (add-to-list 'rtn org-effort-property))
12569 (when include-columns
12570 (save-excursion
12571 (save-restriction
12572 (widen)
12573 (goto-char (point-min))
12574 (while (re-search-forward
12575 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12576 nil t)
12577 (setq cfmt (match-string 2) s 0)
12578 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12579 cfmt s)
12580 (setq s (match-end 0)
12581 p (match-string 1 cfmt))
12582 (unless (or (equal p "ITEM")
12583 (member p org-special-properties))
12584 (add-to-list 'rtn (match-string 1 cfmt))))))))
12586 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12588 (defun org-property-values (key)
12589 "Return a list of all values of property KEY."
12590 (save-excursion
12591 (save-restriction
12592 (widen)
12593 (goto-char (point-min))
12594 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12595 values)
12596 (while (re-search-forward re nil t)
12597 (add-to-list 'values (org-trim (match-string 1))))
12598 (delete "" values)))))
12600 (defun org-insert-property-drawer ()
12601 "Insert a property drawer into the current entry."
12602 (interactive)
12603 (org-back-to-heading t)
12604 (looking-at outline-regexp)
12605 (let ((indent (if org-adapt-indentation
12606 (- (match-end 0)(match-beginning 0))
12608 (beg (point))
12609 (re (concat "^[ \t]*" org-keyword-time-regexp))
12610 end hiddenp)
12611 (outline-next-heading)
12612 (setq end (point))
12613 (goto-char beg)
12614 (while (re-search-forward re end t))
12615 (setq hiddenp (org-invisible-p))
12616 (end-of-line 1)
12617 (and (equal (char-after) ?\n) (forward-char 1))
12618 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12619 (if (member (match-string 1) '("CLOCK:" ":END:"))
12620 ;; just skip this line
12621 (beginning-of-line 2)
12622 ;; Drawer start, find the end
12623 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12624 (beginning-of-line 1)))
12625 (org-skip-over-state-notes)
12626 (skip-chars-backward " \t\n\r")
12627 (if (eq (char-before) ?*) (forward-char 1))
12628 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12629 (beginning-of-line 0)
12630 (org-indent-to-column indent)
12631 (beginning-of-line 2)
12632 (org-indent-to-column indent)
12633 (beginning-of-line 0)
12634 (if hiddenp
12635 (save-excursion
12636 (org-back-to-heading t)
12637 (hide-entry))
12638 (org-flag-drawer t))))
12640 (defun org-set-property (property value)
12641 "In the current entry, set PROPERTY to VALUE.
12642 When called interactively, this will prompt for a property name, offering
12643 completion on existing and default properties. And then it will prompt
12644 for a value, offering completion either on allowed values (via an inherited
12645 xxx_ALL property) or on existing values in other instances of this property
12646 in the current file."
12647 (interactive
12648 (let* ((completion-ignore-case t)
12649 (keys (org-buffer-property-keys nil t t))
12650 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12651 (prop (if (member prop0 keys)
12652 prop0
12653 (or (cdr (assoc (downcase prop0)
12654 (mapcar (lambda (x) (cons (downcase x) x))
12655 keys)))
12656 prop0)))
12657 (cur (org-entry-get nil prop))
12658 (allowed (org-property-get-allowed-values nil prop 'table))
12659 (existing (mapcar 'list (org-property-values prop)))
12660 (val (if allowed
12661 (org-completing-read "Value: " allowed nil 'req-match)
12662 (let (org-completion-use-ido org-completion-use-iswitchb)
12663 (org-completing-read
12664 (concat "Value " (if (and cur (string-match "\\S-" cur))
12665 (concat "[" cur "]") "")
12666 ": ")
12667 existing nil nil "" nil cur)))))
12668 (list prop (if (equal val "") cur val))))
12669 (unless (equal (org-entry-get nil property) value)
12670 (org-entry-put nil property value)))
12672 (defun org-delete-property (property)
12673 "In the current entry, delete PROPERTY."
12674 (interactive
12675 (let* ((completion-ignore-case t)
12676 (prop (org-icompleting-read
12677 "Property: " (org-entry-properties nil 'standard))))
12678 (list prop)))
12679 (message "Property %s %s" property
12680 (if (org-entry-delete nil property)
12681 "deleted"
12682 "was not present in the entry")))
12684 (defun org-delete-property-globally (property)
12685 "Remove PROPERTY globally, from all entries."
12686 (interactive
12687 (let* ((completion-ignore-case t)
12688 (prop (org-icompleting-read
12689 "Globally remove property: "
12690 (mapcar 'list (org-buffer-property-keys)))))
12691 (list prop)))
12692 (save-excursion
12693 (save-restriction
12694 (widen)
12695 (goto-char (point-min))
12696 (let ((cnt 0))
12697 (while (re-search-forward
12698 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12699 nil t)
12700 (setq cnt (1+ cnt))
12701 (replace-match ""))
12702 (message "Property \"%s\" removed from %d entries" property cnt)))))
12704 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12706 (defun org-compute-property-at-point ()
12707 "Compute the property at point.
12708 This looks for an enclosing column format, extracts the operator and
12709 then applies it to the property in the column format's scope."
12710 (interactive)
12711 (unless (org-at-property-p)
12712 (error "Not at a property"))
12713 (let ((prop (org-match-string-no-properties 2)))
12714 (org-columns-get-format-and-top-level)
12715 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12716 (error "No operator defined for property %s" prop))
12717 (org-columns-compute prop)))
12719 (defun org-property-get-allowed-values (pom property &optional table)
12720 "Get allowed values for the property PROPERTY.
12721 When TABLE is non-nil, return an alist that can directly be used for
12722 completion."
12723 (let (vals)
12724 (cond
12725 ((equal property "TODO")
12726 (setq vals (org-with-point-at pom
12727 (append org-todo-keywords-1 '("")))))
12728 ((equal property "PRIORITY")
12729 (let ((n org-lowest-priority))
12730 (while (>= n org-highest-priority)
12731 (push (char-to-string n) vals)
12732 (setq n (1- n)))))
12733 ((member property org-special-properties))
12735 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12737 (when (and vals (string-match "\\S-" vals))
12738 (setq vals (car (read-from-string (concat "(" vals ")"))))
12739 (setq vals (mapcar (lambda (x)
12740 (cond ((stringp x) x)
12741 ((numberp x) (number-to-string x))
12742 ((symbolp x) (symbol-name x))
12743 (t "???")))
12744 vals)))))
12745 (if table (mapcar 'list vals) vals)))
12747 (defun org-property-previous-allowed-value (&optional previous)
12748 "Switch to the next allowed value for this property."
12749 (interactive)
12750 (org-property-next-allowed-value t))
12752 (defun org-property-next-allowed-value (&optional previous)
12753 "Switch to the next allowed value for this property."
12754 (interactive)
12755 (unless (org-at-property-p)
12756 (error "Not at a property"))
12757 (let* ((key (match-string 2))
12758 (value (match-string 3))
12759 (allowed (or (org-property-get-allowed-values (point) key)
12760 (and (member value '("[ ]" "[-]" "[X]"))
12761 '("[ ]" "[X]"))))
12762 nval)
12763 (unless allowed
12764 (error "Allowed values for this property have not been defined"))
12765 (if previous (setq allowed (reverse allowed)))
12766 (if (member value allowed)
12767 (setq nval (car (cdr (member value allowed)))))
12768 (setq nval (or nval (car allowed)))
12769 (if (equal nval value)
12770 (error "Only one allowed value for this property"))
12771 (org-at-property-p)
12772 (replace-match (concat " :" key ": " nval) t t)
12773 (org-indent-line-function)
12774 (beginning-of-line 1)
12775 (skip-chars-forward " \t")))
12777 (defun org-find-entry-with-id (ident)
12778 "Locate the entry that contains the ID property with exact value IDENT.
12779 IDENT can be a string, a symbol or a number, this function will search for
12780 the string representation of it.
12781 Return the position where this entry starts, or nil if there is no such entry."
12782 (interactive "sID: ")
12783 (let ((id (cond
12784 ((stringp ident) ident)
12785 ((symbol-name ident) (symbol-name ident))
12786 ((numberp ident) (number-to-string ident))
12787 (t (error "IDENT %s must be a string, symbol or number" ident))))
12788 (case-fold-search nil))
12789 (save-excursion
12790 (save-restriction
12791 (widen)
12792 (goto-char (point-min))
12793 (when (re-search-forward
12794 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12795 nil t)
12796 (org-back-to-heading t)
12797 (point))))))
12799 ;;;; Timestamps
12801 (defvar org-last-changed-timestamp nil)
12802 (defvar org-last-inserted-timestamp nil
12803 "The last time stamp inserted with `org-insert-time-stamp'.")
12804 (defvar org-time-was-given) ; dynamically scoped parameter
12805 (defvar org-end-time-was-given) ; dynamically scoped parameter
12806 (defvar org-ts-what) ; dynamically scoped parameter
12808 (defun org-time-stamp (arg &optional inactive)
12809 "Prompt for a date/time and insert a time stamp.
12810 If the user specifies a time like HH:MM, or if this command is called
12811 with a prefix argument, the time stamp will contain date and time.
12812 Otherwise, only the date will be included. All parts of a date not
12813 specified by the user will be filled in from the current date/time.
12814 So if you press just return without typing anything, the time stamp
12815 will represent the current date/time. If there is already a timestamp
12816 at the cursor, it will be modified."
12817 (interactive "P")
12818 (let* ((ts nil)
12819 (default-time
12820 ;; Default time is either today, or, when entering a range,
12821 ;; the range start.
12822 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12823 (save-excursion
12824 (re-search-backward
12825 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12826 (- (point) 20) t)))
12827 (apply 'encode-time (org-parse-time-string (match-string 1)))
12828 (current-time)))
12829 (default-input (and ts (org-get-compact-tod ts)))
12830 org-time-was-given org-end-time-was-given time)
12831 (cond
12832 ((and (org-at-timestamp-p t)
12833 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12834 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12835 (insert "--")
12836 (setq time (let ((this-command this-command))
12837 (org-read-date arg 'totime nil nil
12838 default-time default-input)))
12839 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12840 ((org-at-timestamp-p t)
12841 (setq time (let ((this-command this-command))
12842 (org-read-date arg 'totime nil nil default-time default-input)))
12843 (when (org-at-timestamp-p t) ; just to get the match data
12844 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12845 (replace-match "")
12846 (setq org-last-changed-timestamp
12847 (org-insert-time-stamp
12848 time (or org-time-was-given arg)
12849 inactive nil nil (list org-end-time-was-given))))
12850 (message "Timestamp updated"))
12852 (setq time (let ((this-command this-command))
12853 (org-read-date arg 'totime nil nil default-time default-input)))
12854 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12855 nil nil (list org-end-time-was-given))))))
12857 ;; FIXME: can we use this for something else, like computing time differences?
12858 (defun org-get-compact-tod (s)
12859 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12860 (let* ((t1 (match-string 1 s))
12861 (h1 (string-to-number (match-string 2 s)))
12862 (m1 (string-to-number (match-string 3 s)))
12863 (t2 (and (match-end 4) (match-string 5 s)))
12864 (h2 (and t2 (string-to-number (match-string 6 s))))
12865 (m2 (and t2 (string-to-number (match-string 7 s))))
12866 dh dm)
12867 (if (not t2)
12869 (setq dh (- h2 h1) dm (- m2 m1))
12870 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12871 (concat t1 "+" (number-to-string dh)
12872 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12874 (defun org-time-stamp-inactive (&optional arg)
12875 "Insert an inactive time stamp.
12876 An inactive time stamp is enclosed in square brackets instead of angle
12877 brackets. It is inactive in the sense that it does not trigger agenda entries,
12878 does not link to the calendar and cannot be changed with the S-cursor keys.
12879 So these are more for recording a certain time/date."
12880 (interactive "P")
12881 (org-time-stamp arg 'inactive))
12883 (defvar org-date-ovl (org-make-overlay 1 1))
12884 (org-overlay-put org-date-ovl 'face 'org-warning)
12885 (org-detach-overlay org-date-ovl)
12887 (defvar org-ans1) ; dynamically scoped parameter
12888 (defvar org-ans2) ; dynamically scoped parameter
12890 (defvar org-plain-time-of-day-regexp) ; defined below
12892 (defvar org-overriding-default-time nil) ; dynamically scoped
12893 (defvar org-read-date-overlay nil)
12894 (defvar org-dcst nil) ; dynamically scoped
12895 (defvar org-read-date-history nil)
12896 (defvar org-read-date-final-answer nil)
12898 (defun org-read-date (&optional with-time to-time from-string prompt
12899 default-time default-input)
12900 "Read a date, possibly a time, and make things smooth for the user.
12901 The prompt will suggest to enter an ISO date, but you can also enter anything
12902 which will at least partially be understood by `parse-time-string'.
12903 Unrecognized parts of the date will default to the current day, month, year,
12904 hour and minute. If this command is called to replace a timestamp at point,
12905 of to enter the second timestamp of a range, the default time is taken from the
12906 existing stamp. For example,
12907 3-2-5 --> 2003-02-05
12908 feb 15 --> currentyear-02-15
12909 sep 12 9 --> 2009-09-12
12910 12:45 --> today 12:45
12911 22 sept 0:34 --> currentyear-09-22 0:34
12912 12 --> currentyear-currentmonth-12
12913 Fri --> nearest Friday (today or later)
12914 etc.
12916 Furthermore you can specify a relative date by giving, as the *first* thing
12917 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12918 change in days weeks, months, years.
12919 With a single plus or minus, the date is relative to today. With a double
12920 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12921 +4d --> four days from today
12922 +4 --> same as above
12923 +2w --> two weeks from today
12924 ++5 --> five days from default date
12926 The function understands only English month and weekday abbreviations,
12927 but this can be configured with the variables `parse-time-months' and
12928 `parse-time-weekdays'.
12930 While prompting, a calendar is popped up - you can also select the
12931 date with the mouse (button 1). The calendar shows a period of three
12932 months. To scroll it to other months, use the keys `>' and `<'.
12933 If you don't like the calendar, turn it off with
12934 \(setq org-read-date-popup-calendar nil)
12936 With optional argument TO-TIME, the date will immediately be converted
12937 to an internal time.
12938 With an optional argument WITH-TIME, the prompt will suggest to also
12939 insert a time. Note that when WITH-TIME is not set, you can still
12940 enter a time, and this function will inform the calling routine about
12941 this change. The calling routine may then choose to change the format
12942 used to insert the time stamp into the buffer to include the time.
12943 With optional argument FROM-STRING, read from this string instead from
12944 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12945 the time/date that is used for everything that is not specified by the
12946 user."
12947 (require 'parse-time)
12948 (let* ((org-time-stamp-rounding-minutes
12949 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12950 (org-dcst org-display-custom-times)
12951 (ct (org-current-time))
12952 (def (or org-overriding-default-time default-time ct))
12953 (defdecode (decode-time def))
12954 (dummy (progn
12955 (when (< (nth 2 defdecode) org-extend-today-until)
12956 (setcar (nthcdr 2 defdecode) -1)
12957 (setcar (nthcdr 1 defdecode) 59)
12958 (setq def (apply 'encode-time defdecode)
12959 defdecode (decode-time def)))))
12960 (calendar-frame-setup nil)
12961 (calendar-move-hook nil)
12962 (calendar-view-diary-initially-flag nil)
12963 (view-diary-entries-initially nil)
12964 (calendar-view-holidays-initially-flag nil)
12965 (view-calendar-holidays-initially nil)
12966 (timestr (format-time-string
12967 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12968 (prompt (concat (if prompt (concat prompt " ") "")
12969 (format "Date+time [%s]: " timestr)))
12970 ans (org-ans0 "") org-ans1 org-ans2 final)
12972 (cond
12973 (from-string (setq ans from-string))
12974 (org-read-date-popup-calendar
12975 (save-excursion
12976 (save-window-excursion
12977 (calendar)
12978 (calendar-forward-day (- (time-to-days def)
12979 (calendar-absolute-from-gregorian
12980 (calendar-current-date))))
12981 (org-eval-in-calendar nil t)
12982 (let* ((old-map (current-local-map))
12983 (map (copy-keymap calendar-mode-map))
12984 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12985 (org-defkey map (kbd "RET") 'org-calendar-select)
12986 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12987 'org-calendar-select-mouse)
12988 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12989 'org-calendar-select-mouse)
12990 (org-defkey minibuffer-local-map [(meta shift left)]
12991 (lambda () (interactive)
12992 (org-eval-in-calendar '(calendar-backward-month 1))))
12993 (org-defkey minibuffer-local-map [(meta shift right)]
12994 (lambda () (interactive)
12995 (org-eval-in-calendar '(calendar-forward-month 1))))
12996 (org-defkey minibuffer-local-map [(meta shift up)]
12997 (lambda () (interactive)
12998 (org-eval-in-calendar '(calendar-backward-year 1))))
12999 (org-defkey minibuffer-local-map [(meta shift down)]
13000 (lambda () (interactive)
13001 (org-eval-in-calendar '(calendar-forward-year 1))))
13002 (org-defkey minibuffer-local-map [?\e (shift left)]
13003 (lambda () (interactive)
13004 (org-eval-in-calendar '(calendar-backward-month 1))))
13005 (org-defkey minibuffer-local-map [?\e (shift right)]
13006 (lambda () (interactive)
13007 (org-eval-in-calendar '(calendar-forward-month 1))))
13008 (org-defkey minibuffer-local-map [?\e (shift up)]
13009 (lambda () (interactive)
13010 (org-eval-in-calendar '(calendar-backward-year 1))))
13011 (org-defkey minibuffer-local-map [?\e (shift down)]
13012 (lambda () (interactive)
13013 (org-eval-in-calendar '(calendar-forward-year 1))))
13014 (org-defkey minibuffer-local-map [(shift up)]
13015 (lambda () (interactive)
13016 (org-eval-in-calendar '(calendar-backward-week 1))))
13017 (org-defkey minibuffer-local-map [(shift down)]
13018 (lambda () (interactive)
13019 (org-eval-in-calendar '(calendar-forward-week 1))))
13020 (org-defkey minibuffer-local-map [(shift left)]
13021 (lambda () (interactive)
13022 (org-eval-in-calendar '(calendar-backward-day 1))))
13023 (org-defkey minibuffer-local-map [(shift right)]
13024 (lambda () (interactive)
13025 (org-eval-in-calendar '(calendar-forward-day 1))))
13026 (org-defkey minibuffer-local-map ">"
13027 (lambda () (interactive)
13028 (org-eval-in-calendar '(scroll-calendar-left 1))))
13029 (org-defkey minibuffer-local-map "<"
13030 (lambda () (interactive)
13031 (org-eval-in-calendar '(scroll-calendar-right 1))))
13032 (run-hooks 'org-read-date-minibuffer-setup-hook)
13033 (unwind-protect
13034 (progn
13035 (use-local-map map)
13036 (add-hook 'post-command-hook 'org-read-date-display)
13037 (setq org-ans0 (read-string prompt default-input
13038 'org-read-date-history nil))
13039 ;; org-ans0: from prompt
13040 ;; org-ans1: from mouse click
13041 ;; org-ans2: from calendar motion
13042 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13043 (remove-hook 'post-command-hook 'org-read-date-display)
13044 (use-local-map old-map)
13045 (when org-read-date-overlay
13046 (org-delete-overlay org-read-date-overlay)
13047 (setq org-read-date-overlay nil)))))))
13049 (t ; Naked prompt only
13050 (unwind-protect
13051 (setq ans (read-string prompt default-input
13052 'org-read-date-history timestr))
13053 (when org-read-date-overlay
13054 (org-delete-overlay org-read-date-overlay)
13055 (setq org-read-date-overlay nil)))))
13057 (setq final (org-read-date-analyze ans def defdecode))
13058 (setq org-read-date-final-answer ans)
13060 (if to-time
13061 (apply 'encode-time final)
13062 (if (and (boundp 'org-time-was-given) org-time-was-given)
13063 (format "%04d-%02d-%02d %02d:%02d"
13064 (nth 5 final) (nth 4 final) (nth 3 final)
13065 (nth 2 final) (nth 1 final))
13066 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13068 (defvar def)
13069 (defvar defdecode)
13070 (defvar with-time)
13071 (defvar org-read-date-analyze-futurep nil)
13072 (defun org-read-date-display ()
13073 "Display the current date prompt interpretation in the minibuffer."
13074 (when org-read-date-display-live
13075 (when org-read-date-overlay
13076 (org-delete-overlay org-read-date-overlay))
13077 (let ((p (point)))
13078 (end-of-line 1)
13079 (while (not (equal (buffer-substring
13080 (max (point-min) (- (point) 4)) (point))
13081 " "))
13082 (insert " "))
13083 (goto-char p))
13084 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13085 " " (or org-ans1 org-ans2)))
13086 (org-end-time-was-given nil)
13087 (f (org-read-date-analyze ans def defdecode))
13088 (fmts (if org-dcst
13089 org-time-stamp-custom-formats
13090 org-time-stamp-formats))
13091 (fmt (if (or with-time
13092 (and (boundp 'org-time-was-given) org-time-was-given))
13093 (cdr fmts)
13094 (car fmts)))
13095 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13096 (when (and org-end-time-was-given
13097 (string-match org-plain-time-of-day-regexp txt))
13098 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13099 org-end-time-was-given
13100 (substring txt (match-end 0)))))
13101 (when org-read-date-analyze-futurep
13102 (setq txt (concat txt " (=>F)")))
13103 (setq org-read-date-overlay
13104 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13105 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13107 (defun org-read-date-analyze (ans def defdecode)
13108 "Analyse the combined answer of the date prompt."
13109 ;; FIXME: cleanup and comment
13110 (let (delta deltan deltaw deltadef year month day
13111 hour minute second wday pm h2 m2 tl wday1
13112 iso-year iso-weekday iso-week iso-year iso-date futurep)
13113 (setq org-read-date-analyze-futurep nil)
13114 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13115 (setq ans "+0"))
13117 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13118 (setq ans (replace-match "" t t ans)
13119 deltan (car delta)
13120 deltaw (nth 1 delta)
13121 deltadef (nth 2 delta)))
13123 ;; Check if there is an iso week date in there
13124 ;; If yes, sore the info and postpone interpreting it until the rest
13125 ;; of the parsing is done
13126 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13127 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13128 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13129 iso-week (string-to-number (match-string 2 ans)))
13130 (setq ans (replace-match "" t t ans)))
13132 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13133 (when (string-match
13134 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13135 (setq year (if (match-end 2)
13136 (string-to-number (match-string 2 ans))
13137 (string-to-number (format-time-string "%Y")))
13138 month (string-to-number (match-string 3 ans))
13139 day (string-to-number (match-string 4 ans)))
13140 (if (< year 100) (setq year (+ 2000 year)))
13141 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13142 t nil ans)))
13143 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13144 ;; If there is a time with am/pm, and *no* time without it, we convert
13145 ;; so that matching will be successful.
13146 (loop for i from 1 to 2 do ; twice, for end time as well
13147 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13148 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13149 (setq hour (string-to-number (match-string 1 ans))
13150 minute (if (match-end 3)
13151 (string-to-number (match-string 3 ans))
13153 pm (equal ?p
13154 (string-to-char (downcase (match-string 4 ans)))))
13155 (if (and (= hour 12) (not pm))
13156 (setq hour 0)
13157 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13158 (setq ans (replace-match (format "%02d:%02d" hour minute)
13159 t t ans))))
13161 ;; Check if a time range is given as a duration
13162 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13163 (setq hour (string-to-number (match-string 1 ans))
13164 h2 (+ hour (string-to-number (match-string 3 ans)))
13165 minute (string-to-number (match-string 2 ans))
13166 m2 (+ minute (if (match-end 5) (string-to-number
13167 (match-string 5 ans))0)))
13168 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13169 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13170 t t ans)))
13172 ;; Check if there is a time range
13173 (when (boundp 'org-end-time-was-given)
13174 (setq org-time-was-given nil)
13175 (when (and (string-match org-plain-time-of-day-regexp ans)
13176 (match-end 8))
13177 (setq org-end-time-was-given (match-string 8 ans))
13178 (setq ans (concat (substring ans 0 (match-beginning 7))
13179 (substring ans (match-end 7))))))
13181 (setq tl (parse-time-string ans)
13182 day (or (nth 3 tl) (nth 3 defdecode))
13183 month (or (nth 4 tl)
13184 (if (and org-read-date-prefer-future
13185 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13186 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13187 (nth 4 defdecode)))
13188 year (or (nth 5 tl)
13189 (if (and org-read-date-prefer-future
13190 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13191 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13192 (nth 5 defdecode)))
13193 hour (or (nth 2 tl) (nth 2 defdecode))
13194 minute (or (nth 1 tl) (nth 1 defdecode))
13195 second (or (nth 0 tl) 0)
13196 wday (nth 6 tl))
13198 (when (and (eq org-read-date-prefer-future 'time)
13199 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13200 (equal day (nth 3 defdecode))
13201 (equal month (nth 4 defdecode))
13202 (equal year (nth 5 defdecode))
13203 (nth 2 tl)
13204 (or (< (nth 2 tl) (nth 2 defdecode))
13205 (and (= (nth 2 tl) (nth 2 defdecode))
13206 (nth 1 tl)
13207 (< (nth 1 tl) (nth 1 defdecode)))))
13208 (setq day (1+ day)
13209 futurep t))
13211 ;; Special date definitions below
13212 (cond
13213 (iso-week
13214 ;; There was an iso week
13215 (setq futurep nil)
13216 (setq year (or iso-year year)
13217 day (or iso-weekday wday 1)
13218 wday nil ; to make sure that the trigger below does not match
13219 iso-date (calendar-gregorian-from-absolute
13220 (calendar-absolute-from-iso
13221 (list iso-week day year))))
13222 ; FIXME: Should we also push ISO weeks into the future?
13223 ; (when (and org-read-date-prefer-future
13224 ; (not iso-year)
13225 ; (< (calendar-absolute-from-gregorian iso-date)
13226 ; (time-to-days (current-time))))
13227 ; (setq year (1+ year)
13228 ; iso-date (calendar-gregorian-from-absolute
13229 ; (calendar-absolute-from-iso
13230 ; (list iso-week day year)))))
13231 (setq month (car iso-date)
13232 year (nth 2 iso-date)
13233 day (nth 1 iso-date)))
13234 (deltan
13235 (setq futurep nil)
13236 (unless deltadef
13237 (let ((now (decode-time (current-time))))
13238 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13239 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13240 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13241 ((equal deltaw "m") (setq month (+ month deltan)))
13242 ((equal deltaw "y") (setq year (+ year deltan)))))
13243 ((and wday (not (nth 3 tl)))
13244 (setq futurep nil)
13245 ;; Weekday was given, but no day, so pick that day in the week
13246 ;; on or after the derived date.
13247 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13248 (unless (equal wday wday1)
13249 (setq day (+ day (% (- wday wday1 -7) 7))))))
13250 (if (and (boundp 'org-time-was-given)
13251 (nth 2 tl))
13252 (setq org-time-was-given t))
13253 (if (< year 100) (setq year (+ 2000 year)))
13254 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13255 (setq org-read-date-analyze-futurep futurep)
13256 (list second minute hour day month year)))
13258 (defvar parse-time-weekdays)
13260 (defun org-read-date-get-relative (s today default)
13261 "Check string S for special relative date string.
13262 TODAY and DEFAULT are internal times, for today and for a default.
13263 Return shift list (N what def-flag)
13264 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13265 N is the number of WHATs to shift.
13266 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13267 the DEFAULT date rather than TODAY."
13268 (when (and
13269 (string-match
13270 (concat
13271 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13272 "\\([0-9]+\\)?"
13273 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13274 "\\([ \t]\\|$\\)") s)
13275 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13276 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13277 (string-to-char (substring (match-string 1 s) -1))
13278 ?+))
13279 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13280 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13281 (what (if (match-end 3) (match-string 3 s) "d"))
13282 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13283 (date (if rel default today))
13284 (wday (nth 6 (decode-time date)))
13285 delta)
13286 (if wday1
13287 (progn
13288 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13289 (if (= dir ?-) (setq delta (- delta 7)))
13290 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13291 (list delta "d" rel))
13292 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13294 (defun org-eval-in-calendar (form &optional keepdate)
13295 "Eval FORM in the calendar window and return to current window.
13296 Also, store the cursor date in variable org-ans2."
13297 (let ((sf (selected-frame))
13298 (sw (selected-window)))
13299 (select-window (get-buffer-window "*Calendar*" t))
13300 (eval form)
13301 (when (and (not keepdate) (calendar-cursor-to-date))
13302 (let* ((date (calendar-cursor-to-date))
13303 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13304 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13305 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13306 (select-window sw)
13307 (org-select-frame-set-input-focus sf)))
13309 (defun org-calendar-select ()
13310 "Return to `org-read-date' with the date currently selected.
13311 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13312 (interactive)
13313 (when (calendar-cursor-to-date)
13314 (let* ((date (calendar-cursor-to-date))
13315 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13316 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13317 (if (active-minibuffer-window) (exit-minibuffer))))
13319 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13320 "Insert a date stamp for the date given by the internal TIME.
13321 WITH-HM means, use the stamp format that includes the time of the day.
13322 INACTIVE means use square brackets instead of angular ones, so that the
13323 stamp will not contribute to the agenda.
13324 PRE and POST are optional strings to be inserted before and after the
13325 stamp.
13326 The command returns the inserted time stamp."
13327 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13328 stamp)
13329 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13330 (insert-before-markers (or pre ""))
13331 (insert-before-markers (setq stamp (format-time-string fmt time)))
13332 (when (listp extra)
13333 (setq extra (car extra))
13334 (if (and (stringp extra)
13335 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13336 (setq extra (format "-%02d:%02d"
13337 (string-to-number (match-string 1 extra))
13338 (string-to-number (match-string 2 extra))))
13339 (setq extra nil)))
13340 (when extra
13341 (backward-char 1)
13342 (insert-before-markers extra)
13343 (forward-char 1))
13344 (insert-before-markers (or post ""))
13345 (setq org-last-inserted-timestamp stamp)))
13347 (defun org-toggle-time-stamp-overlays ()
13348 "Toggle the use of custom time stamp formats."
13349 (interactive)
13350 (setq org-display-custom-times (not org-display-custom-times))
13351 (unless org-display-custom-times
13352 (let ((p (point-min)) (bmp (buffer-modified-p)))
13353 (while (setq p (next-single-property-change p 'display))
13354 (if (and (get-text-property p 'display)
13355 (eq (get-text-property p 'face) 'org-date))
13356 (remove-text-properties
13357 p (setq p (next-single-property-change p 'display))
13358 '(display t))))
13359 (set-buffer-modified-p bmp)))
13360 (if (featurep 'xemacs)
13361 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13362 (org-restart-font-lock)
13363 (setq org-table-may-need-update t)
13364 (if org-display-custom-times
13365 (message "Time stamps are overlayed with custom format")
13366 (message "Time stamp overlays removed")))
13368 (defun org-display-custom-time (beg end)
13369 "Overlay modified time stamp format over timestamp between BEG and END."
13370 (let* ((ts (buffer-substring beg end))
13371 t1 w1 with-hm tf time str w2 (off 0))
13372 (save-match-data
13373 (setq t1 (org-parse-time-string ts t))
13374 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13375 (setq off (- (match-end 0) (match-beginning 0)))))
13376 (setq end (- end off))
13377 (setq w1 (- end beg)
13378 with-hm (and (nth 1 t1) (nth 2 t1))
13379 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13380 time (org-fix-decoded-time t1)
13381 str (org-add-props
13382 (format-time-string
13383 (substring tf 1 -1) (apply 'encode-time time))
13384 nil 'mouse-face 'highlight)
13385 w2 (length str))
13386 (if (not (= w2 w1))
13387 (add-text-properties (1+ beg) (+ 2 beg)
13388 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13389 (if (featurep 'xemacs)
13390 (progn
13391 (put-text-property beg end 'invisible t)
13392 (put-text-property beg end 'end-glyph (make-glyph str)))
13393 (put-text-property beg end 'display str))))
13395 (defun org-translate-time (string)
13396 "Translate all timestamps in STRING to custom format.
13397 But do this only if the variable `org-display-custom-times' is set."
13398 (when org-display-custom-times
13399 (save-match-data
13400 (let* ((start 0)
13401 (re org-ts-regexp-both)
13402 t1 with-hm inactive tf time str beg end)
13403 (while (setq start (string-match re string start))
13404 (setq beg (match-beginning 0)
13405 end (match-end 0)
13406 t1 (save-match-data
13407 (org-parse-time-string (substring string beg end) t))
13408 with-hm (and (nth 1 t1) (nth 2 t1))
13409 inactive (equal (substring string beg (1+ beg)) "[")
13410 tf (funcall (if with-hm 'cdr 'car)
13411 org-time-stamp-custom-formats)
13412 time (org-fix-decoded-time t1)
13413 str (format-time-string
13414 (concat
13415 (if inactive "[" "<") (substring tf 1 -1)
13416 (if inactive "]" ">"))
13417 (apply 'encode-time time))
13418 string (replace-match str t t string)
13419 start (+ start (length str)))))))
13420 string)
13422 (defun org-fix-decoded-time (time)
13423 "Set 0 instead of nil for the first 6 elements of time.
13424 Don't touch the rest."
13425 (let ((n 0))
13426 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13428 (defun org-days-to-time (timestamp-string)
13429 "Difference between TIMESTAMP-STRING and now in days."
13430 (- (time-to-days (org-time-string-to-time timestamp-string))
13431 (time-to-days (current-time))))
13433 (defun org-deadline-close (timestamp-string &optional ndays)
13434 "Is the time in TIMESTAMP-STRING close to the current date?"
13435 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13436 (and (< (org-days-to-time timestamp-string) ndays)
13437 (not (org-entry-is-done-p))))
13439 (defun org-get-wdays (ts)
13440 "Get the deadline lead time appropriate for timestring TS."
13441 (cond
13442 ((<= org-deadline-warning-days 0)
13443 ;; 0 or negative, enforce this value no matter what
13444 (- org-deadline-warning-days))
13445 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13446 ;; lead time is specified.
13447 (floor (* (string-to-number (match-string 1 ts))
13448 (cdr (assoc (match-string 2 ts)
13449 '(("d" . 1) ("w" . 7)
13450 ("m" . 30.4) ("y" . 365.25)))))))
13451 ;; go for the default.
13452 (t org-deadline-warning-days)))
13454 (defun org-calendar-select-mouse (ev)
13455 "Return to `org-read-date' with the date currently selected.
13456 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13457 (interactive "e")
13458 (mouse-set-point ev)
13459 (when (calendar-cursor-to-date)
13460 (let* ((date (calendar-cursor-to-date))
13461 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13462 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13463 (if (active-minibuffer-window) (exit-minibuffer))))
13465 (defun org-check-deadlines (ndays)
13466 "Check if there are any deadlines due or past due.
13467 A deadline is considered due if it happens within `org-deadline-warning-days'
13468 days from today's date. If the deadline appears in an entry marked DONE,
13469 it is not shown. The prefix arg NDAYS can be used to test that many
13470 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13471 (interactive "P")
13472 (let* ((org-warn-days
13473 (cond
13474 ((equal ndays '(4)) 100000)
13475 (ndays (prefix-numeric-value ndays))
13476 (t (abs org-deadline-warning-days))))
13477 (case-fold-search nil)
13478 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13479 (callback
13480 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13482 (message "%d deadlines past-due or due within %d days"
13483 (org-occur regexp nil callback)
13484 org-warn-days)))
13486 (defun org-check-before-date (date)
13487 "Check if there are deadlines or scheduled entries before DATE."
13488 (interactive (list (org-read-date)))
13489 (let ((case-fold-search nil)
13490 (regexp (concat "\\<\\(" org-deadline-string
13491 "\\|" org-scheduled-string
13492 "\\) *<\\([^>]+\\)>"))
13493 (callback
13494 (lambda () (time-less-p
13495 (org-time-string-to-time (match-string 2))
13496 (org-time-string-to-time date)))))
13497 (message "%d entries before %s"
13498 (org-occur regexp nil callback) date)))
13500 (defun org-check-after-date (date)
13501 "Check if there are deadlines or scheduled entries after DATE."
13502 (interactive (list (org-read-date)))
13503 (let ((case-fold-search nil)
13504 (regexp (concat "\\<\\(" org-deadline-string
13505 "\\|" org-scheduled-string
13506 "\\) *<\\([^>]+\\)>"))
13507 (callback
13508 (lambda () (not
13509 (time-less-p
13510 (org-time-string-to-time (match-string 2))
13511 (org-time-string-to-time date))))))
13512 (message "%d entries after %s"
13513 (org-occur regexp nil callback) date)))
13515 (defun org-evaluate-time-range (&optional to-buffer)
13516 "Evaluate a time range by computing the difference between start and end.
13517 Normally the result is just printed in the echo area, but with prefix arg
13518 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13519 If the time range is actually in a table, the result is inserted into the
13520 next column.
13521 For time difference computation, a year is assumed to be exactly 365
13522 days in order to avoid rounding problems."
13523 (interactive "P")
13525 (org-clock-update-time-maybe)
13526 (save-excursion
13527 (unless (org-at-date-range-p t)
13528 (goto-char (point-at-bol))
13529 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13530 (if (not (org-at-date-range-p t))
13531 (error "Not at a time-stamp range, and none found in current line")))
13532 (let* ((ts1 (match-string 1))
13533 (ts2 (match-string 2))
13534 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13535 (match-end (match-end 0))
13536 (time1 (org-time-string-to-time ts1))
13537 (time2 (org-time-string-to-time ts2))
13538 (t1 (org-float-time time1))
13539 (t2 (org-float-time time2))
13540 (diff (abs (- t2 t1)))
13541 (negative (< (- t2 t1) 0))
13542 ;; (ys (floor (* 365 24 60 60)))
13543 (ds (* 24 60 60))
13544 (hs (* 60 60))
13545 (fy "%dy %dd %02d:%02d")
13546 (fy1 "%dy %dd")
13547 (fd "%dd %02d:%02d")
13548 (fd1 "%dd")
13549 (fh "%02d:%02d")
13550 y d h m align)
13551 (if havetime
13552 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13554 d (floor (/ diff ds)) diff (mod diff ds)
13555 h (floor (/ diff hs)) diff (mod diff hs)
13556 m (floor (/ diff 60)))
13557 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13559 d (floor (+ (/ diff ds) 0.5))
13560 h 0 m 0))
13561 (if (not to-buffer)
13562 (message "%s" (org-make-tdiff-string y d h m))
13563 (if (org-at-table-p)
13564 (progn
13565 (goto-char match-end)
13566 (setq align t)
13567 (and (looking-at " *|") (goto-char (match-end 0))))
13568 (goto-char match-end))
13569 (if (looking-at
13570 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13571 (replace-match ""))
13572 (if negative (insert " -"))
13573 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13574 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13575 (insert " " (format fh h m))))
13576 (if align (org-table-align))
13577 (message "Time difference inserted")))))
13579 (defun org-make-tdiff-string (y d h m)
13580 (let ((fmt "")
13581 (l nil))
13582 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13583 l (push y l)))
13584 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13585 l (push d l)))
13586 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13587 l (push h l)))
13588 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13589 l (push m l)))
13590 (apply 'format fmt (nreverse l))))
13592 (defun org-time-string-to-time (s)
13593 (apply 'encode-time (org-parse-time-string s)))
13594 (defun org-time-string-to-seconds (s)
13595 (org-float-time (org-time-string-to-time s)))
13597 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13598 "Convert a time stamp to an absolute day number.
13599 If there is a specifyer for a cyclic time stamp, get the closest date to
13600 DAYNR.
13601 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13602 the variable date is bound by the calendar when this is called."
13603 (cond
13604 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13605 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13606 daynr
13607 (+ daynr 1000)))
13608 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13609 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13610 (time-to-days (current-time))) (match-string 0 s)
13611 prefer show-all))
13612 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13614 (defun org-days-to-iso-week (days)
13615 "Return the iso week number."
13616 (require 'cal-iso)
13617 (car (calendar-iso-from-absolute days)))
13619 (defun org-small-year-to-year (year)
13620 "Convert 2-digit years into 4-digit years.
13621 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13622 The year 2000 cannot be abbreviated. Any year larger than 99
13623 is returned unchanged."
13624 (if (< year 38)
13625 (setq year (+ 2000 year))
13626 (if (< year 100)
13627 (setq year (+ 1900 year))))
13628 year)
13630 (defun org-time-from-absolute (d)
13631 "Return the time corresponding to date D.
13632 D may be an absolute day number, or a calendar-type list (month day year)."
13633 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13634 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13636 (defun org-calendar-holiday ()
13637 "List of holidays, for Diary display in Org-mode."
13638 (require 'holidays)
13639 (let ((hl (funcall
13640 (if (fboundp 'calendar-check-holidays)
13641 'calendar-check-holidays 'check-calendar-holidays) date)))
13642 (if hl (mapconcat 'identity hl "; "))))
13644 (defun org-diary-sexp-entry (sexp entry date)
13645 "Process a SEXP diary ENTRY for DATE."
13646 (require 'diary-lib)
13647 (let ((result (if calendar-debug-sexp
13648 (let ((stack-trace-on-error t))
13649 (eval (car (read-from-string sexp))))
13650 (condition-case nil
13651 (eval (car (read-from-string sexp)))
13652 (error
13653 (beep)
13654 (message "Bad sexp at line %d in %s: %s"
13655 (org-current-line)
13656 (buffer-file-name) sexp)
13657 (sleep-for 2))))))
13658 (cond ((stringp result) result)
13659 ((and (consp result)
13660 (stringp (cdr result))) (cdr result))
13661 (result entry)
13662 (t nil))))
13664 (defun org-diary-to-ical-string (frombuf)
13665 "Get iCalendar entries from diary entries in buffer FROMBUF.
13666 This uses the icalendar.el library."
13667 (let* ((tmpdir (if (featurep 'xemacs)
13668 (temp-directory)
13669 temporary-file-directory))
13670 (tmpfile (make-temp-name
13671 (expand-file-name "orgics" tmpdir)))
13672 buf rtn b e)
13673 (with-current-buffer frombuf
13674 (icalendar-export-region (point-min) (point-max) tmpfile)
13675 (setq buf (find-buffer-visiting tmpfile))
13676 (set-buffer buf)
13677 (goto-char (point-min))
13678 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13679 (setq b (match-beginning 0)))
13680 (goto-char (point-max))
13681 (if (re-search-backward "^END:VEVENT" nil t)
13682 (setq e (match-end 0)))
13683 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13684 (kill-buffer buf)
13685 (delete-file tmpfile)
13686 rtn))
13688 (defun org-closest-date (start current change prefer show-all)
13689 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13690 When PREFER is `past' return a date that is either CURRENT or past.
13691 When PREFER is `future', return a date that is either CURRENT or future.
13692 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13693 ;; Make the proper lists from the dates
13694 (catch 'exit
13695 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13696 dn dw sday cday n1 n2 n0
13697 d m y y1 y2 date1 date2 nmonths nm ny m2)
13699 (setq start (org-date-to-gregorian start)
13700 current (org-date-to-gregorian
13701 (if show-all
13702 current
13703 (time-to-days (current-time))))
13704 sday (calendar-absolute-from-gregorian start)
13705 cday (calendar-absolute-from-gregorian current))
13707 (if (<= cday sday) (throw 'exit sday))
13709 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13710 (setq dn (string-to-number (match-string 1 change))
13711 dw (cdr (assoc (match-string 2 change) a1)))
13712 (error "Invalid change specifyer: %s" change))
13713 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13714 (cond
13715 ((eq dw 'day)
13716 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13717 n2 (+ n1 dn)))
13718 ((eq dw 'year)
13719 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13720 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13721 (setq date1 (list m d y1)
13722 n1 (calendar-absolute-from-gregorian date1)
13723 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13724 n2 (calendar-absolute-from-gregorian date2)))
13725 ((eq dw 'month)
13726 ;; approx number of month between the two dates
13727 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13728 ;; How often does dn fit in there?
13729 (setq d (nth 1 start) m (car start) y (nth 2 start)
13730 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13731 m (+ m nm)
13732 ny (floor (/ m 12))
13733 y (+ y ny)
13734 m (- m (* ny 12)))
13735 (while (> m 12) (setq m (- m 12) y (1+ y)))
13736 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
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 (while (<= n2 cday)
13741 (setq n1 n2 m m2 y y2)
13742 (setq m2 (+ m dn) y2 y)
13743 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13744 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13745 ;; Make sure n1 is the earlier date
13746 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13747 (if show-all
13748 (cond
13749 ((eq prefer 'past) (if (= cday n2) n2 n1))
13750 ((eq prefer 'future) (if (= cday n1) n1 n2))
13751 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13752 (cond
13753 ((eq prefer 'past) (if (= cday n2) n2 n1))
13754 ((eq prefer 'future) (if (= cday n1) n1 n2))
13755 (t (if (= cday n1) n1 n2)))))))
13757 (defun org-date-to-gregorian (date)
13758 "Turn any specification of DATE into a gregorian date for the calendar."
13759 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13760 ((and (listp date) (= (length date) 3)) date)
13761 ((stringp date)
13762 (setq date (org-parse-time-string date))
13763 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13764 ((listp date)
13765 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13767 (defun org-parse-time-string (s &optional nodefault)
13768 "Parse the standard Org-mode time string.
13769 This should be a lot faster than the normal `parse-time-string'.
13770 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13771 hour and minute fields will be nil if not given."
13772 (if (string-match org-ts-regexp0 s)
13773 (list 0
13774 (if (or (match-beginning 8) (not nodefault))
13775 (string-to-number (or (match-string 8 s) "0")))
13776 (if (or (match-beginning 7) (not nodefault))
13777 (string-to-number (or (match-string 7 s) "0")))
13778 (string-to-number (match-string 4 s))
13779 (string-to-number (match-string 3 s))
13780 (string-to-number (match-string 2 s))
13781 nil nil nil)
13782 (error "Not a standard Org-mode time string: %s" s)))
13784 (defun org-timestamp-up (&optional arg)
13785 "Increase the date item at the cursor by one.
13786 If the cursor is on the year, change the year. If it is on the month or
13787 the day, change that.
13788 With prefix ARG, change by that many units."
13789 (interactive "p")
13790 (org-timestamp-change (prefix-numeric-value arg)))
13792 (defun org-timestamp-down (&optional arg)
13793 "Decrease the date item at the cursor by one.
13794 If the cursor is on the year, change the year. If it is on the month or
13795 the day, change that.
13796 With prefix ARG, change by that many units."
13797 (interactive "p")
13798 (org-timestamp-change (- (prefix-numeric-value arg))))
13800 (defun org-timestamp-up-day (&optional arg)
13801 "Increase the date in the time stamp by one day.
13802 With prefix ARG, change that many days."
13803 (interactive "p")
13804 (if (and (not (org-at-timestamp-p t))
13805 (org-on-heading-p))
13806 (org-todo 'up)
13807 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13809 (defun org-timestamp-down-day (&optional arg)
13810 "Decrease the date in the time stamp by one day.
13811 With prefix ARG, change that many days."
13812 (interactive "p")
13813 (if (and (not (org-at-timestamp-p t))
13814 (org-on-heading-p))
13815 (org-todo 'down)
13816 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13818 (defun org-at-timestamp-p (&optional inactive-ok)
13819 "Determine if the cursor is in or at a timestamp."
13820 (interactive)
13821 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13822 (pos (point))
13823 (ans (or (looking-at tsr)
13824 (save-excursion
13825 (skip-chars-backward "^[<\n\r\t")
13826 (if (> (point) (point-min)) (backward-char 1))
13827 (and (looking-at tsr)
13828 (> (- (match-end 0) pos) -1))))))
13829 (and ans
13830 (boundp 'org-ts-what)
13831 (setq org-ts-what
13832 (cond
13833 ((= pos (match-beginning 0)) 'bracket)
13834 ((= pos (1- (match-end 0))) 'bracket)
13835 ((org-pos-in-match-range pos 2) 'year)
13836 ((org-pos-in-match-range pos 3) 'month)
13837 ((org-pos-in-match-range pos 7) 'hour)
13838 ((org-pos-in-match-range pos 8) 'minute)
13839 ((or (org-pos-in-match-range pos 4)
13840 (org-pos-in-match-range pos 5)) 'day)
13841 ((and (> pos (or (match-end 8) (match-end 5)))
13842 (< pos (match-end 0)))
13843 (- pos (or (match-end 8) (match-end 5))))
13844 (t 'day))))
13845 ans))
13847 (defun org-toggle-timestamp-type ()
13848 "Toggle the type (<active> or [inactive]) of a time stamp."
13849 (interactive)
13850 (when (org-at-timestamp-p t)
13851 (let ((beg (match-beginning 0)) (end (match-end 0))
13852 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13853 (save-excursion
13854 (goto-char beg)
13855 (while (re-search-forward "[][<>]" end t)
13856 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13857 t t)))
13858 (message "Timestamp is now %sactive"
13859 (if (equal (char-after beg) ?<) "" "in")))))
13861 (defun org-timestamp-change (n &optional what)
13862 "Change the date in the time stamp at point.
13863 The date will be changed by N times WHAT. WHAT can be `day', `month',
13864 `year', `minute', `second'. If WHAT is not given, the cursor position
13865 in the timestamp determines what will be changed."
13866 (let ((pos (point))
13867 with-hm inactive
13868 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13869 org-ts-what
13870 extra rem
13871 ts time time0)
13872 (if (not (org-at-timestamp-p t))
13873 (error "Not at a timestamp"))
13874 (if (and (not what) (eq org-ts-what 'bracket))
13875 (org-toggle-timestamp-type)
13876 (if (and (not what) (not (eq org-ts-what 'day))
13877 org-display-custom-times
13878 (get-text-property (point) 'display)
13879 (not (get-text-property (1- (point)) 'display)))
13880 (setq org-ts-what 'day))
13881 (setq org-ts-what (or what org-ts-what)
13882 inactive (= (char-after (match-beginning 0)) ?\[)
13883 ts (match-string 0))
13884 (replace-match "")
13885 (if (string-match
13886 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13888 (setq extra (match-string 1 ts)))
13889 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13890 (setq with-hm t))
13891 (setq time0 (org-parse-time-string ts))
13892 (when (and (eq org-ts-what 'minute)
13893 (eq current-prefix-arg nil))
13894 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13895 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13896 (setcar (cdr time0) (+ (nth 1 time0)
13897 (if (> n 0) (- rem) (- dm rem))))))
13898 (setq time
13899 (encode-time (or (car time0) 0)
13900 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13901 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13902 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13903 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13904 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13905 (nthcdr 6 time0)))
13906 (when (and (member org-ts-what '(hour minute))
13907 extra
13908 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13909 (setq extra (org-modify-ts-extra
13910 extra
13911 (if (eq org-ts-what 'hour) 2 5)
13912 n dm)))
13913 (when (integerp org-ts-what)
13914 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13915 (if (eq what 'calendar)
13916 (let ((cal-date (org-get-date-from-calendar)))
13917 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13918 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13919 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13920 (setcar time0 (or (car time0) 0))
13921 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13922 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13923 (setq time (apply 'encode-time time0))))
13924 (setq org-last-changed-timestamp
13925 (org-insert-time-stamp time with-hm inactive nil nil extra))
13926 (org-clock-update-time-maybe)
13927 (goto-char pos)
13928 ;; Try to recenter the calendar window, if any
13929 (if (and org-calendar-follow-timestamp-change
13930 (get-buffer-window "*Calendar*" t)
13931 (memq org-ts-what '(day month year)))
13932 (org-recenter-calendar (time-to-days time))))))
13934 (defun org-modify-ts-extra (s pos n dm)
13935 "Change the different parts of the lead-time and repeat fields in timestamp."
13936 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13937 ng h m new rem)
13938 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13939 (cond
13940 ((or (org-pos-in-match-range pos 2)
13941 (org-pos-in-match-range pos 3))
13942 (setq m (string-to-number (match-string 3 s))
13943 h (string-to-number (match-string 2 s)))
13944 (if (org-pos-in-match-range pos 2)
13945 (setq h (+ h n))
13946 (setq n (* dm (org-no-warnings (signum n))))
13947 (when (not (= 0 (setq rem (% m dm))))
13948 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13949 (setq m (+ m n)))
13950 (if (< m 0) (setq m (+ m 60) h (1- h)))
13951 (if (> m 59) (setq m (- m 60) h (1+ h)))
13952 (setq h (min 24 (max 0 h)))
13953 (setq ng 1 new (format "-%02d:%02d" h m)))
13954 ((org-pos-in-match-range pos 6)
13955 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13956 ((org-pos-in-match-range pos 5)
13957 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13959 ((org-pos-in-match-range pos 9)
13960 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13961 ((org-pos-in-match-range pos 8)
13962 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13964 (when ng
13965 (setq s (concat
13966 (substring s 0 (match-beginning ng))
13968 (substring s (match-end ng))))))
13971 (defun org-recenter-calendar (date)
13972 "If the calendar is visible, recenter it to DATE."
13973 (let* ((win (selected-window))
13974 (cwin (get-buffer-window "*Calendar*" t))
13975 (calendar-move-hook nil))
13976 (when cwin
13977 (select-window cwin)
13978 (calendar-goto-date (if (listp date) date
13979 (calendar-gregorian-from-absolute date)))
13980 (select-window win))))
13982 (defun org-goto-calendar (&optional arg)
13983 "Go to the Emacs calendar at the current date.
13984 If there is a time stamp in the current line, go to that date.
13985 A prefix ARG can be used to force the current date."
13986 (interactive "P")
13987 (let ((tsr org-ts-regexp) diff
13988 (calendar-move-hook nil)
13989 (calendar-view-holidays-initially-flag nil)
13990 (view-calendar-holidays-initially nil)
13991 (calendar-view-diary-initially-flag nil)
13992 (view-diary-entries-initially nil))
13993 (if (or (org-at-timestamp-p)
13994 (save-excursion
13995 (beginning-of-line 1)
13996 (looking-at (concat ".*" tsr))))
13997 (let ((d1 (time-to-days (current-time)))
13998 (d2 (time-to-days
13999 (org-time-string-to-time (match-string 1)))))
14000 (setq diff (- d2 d1))))
14001 (calendar)
14002 (calendar-goto-today)
14003 (if (and diff (not arg)) (calendar-forward-day diff))))
14005 (defun org-get-date-from-calendar ()
14006 "Return a list (month day year) of date at point in calendar."
14007 (with-current-buffer "*Calendar*"
14008 (save-match-data
14009 (calendar-cursor-to-date))))
14011 (defun org-date-from-calendar ()
14012 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14013 If there is already a time stamp at the cursor position, update it."
14014 (interactive)
14015 (if (org-at-timestamp-p t)
14016 (org-timestamp-change 0 'calendar)
14017 (let ((cal-date (org-get-date-from-calendar)))
14018 (org-insert-time-stamp
14019 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14021 (defun org-minutes-to-hh:mm-string (m)
14022 "Compute H:MM from a number of minutes."
14023 (let ((h (/ m 60)))
14024 (setq m (- m (* 60 h)))
14025 (format org-time-clocksum-format h m)))
14027 (defun org-hh:mm-string-to-minutes (s)
14028 "Convert a string H:MM to a number of minutes.
14029 If the string is just a number, interpret it as minutes.
14030 In fact, the first hh:mm or number in the string will be taken,
14031 there can be extra stuff in the string.
14032 If no number is found, the return value is 0."
14033 (cond
14034 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14035 (+ (* (string-to-number (match-string 1 s)) 60)
14036 (string-to-number (match-string 2 s))))
14037 ((string-match "\\([0-9]+\\)" s)
14038 (string-to-number (match-string 1 s)))
14039 (t 0)))
14041 ;;;; Files
14043 (defun org-save-all-org-buffers ()
14044 "Save all Org-mode buffers without user confirmation."
14045 (interactive)
14046 (message "Saving all Org-mode buffers...")
14047 (save-some-buffers t 'org-mode-p)
14048 (when (featurep 'org-id) (org-id-locations-save))
14049 (message "Saving all Org-mode buffers... done"))
14051 (defun org-revert-all-org-buffers ()
14052 "Revert all Org-mode buffers.
14053 Prompt for confirmation when there are unsaved changes.
14054 Be sure you know what you are doing before letting this function
14055 overwrite your changes.
14057 This function is useful in a setup where one tracks org files
14058 with a version control system, to revert on one machine after pulling
14059 changes from another. I believe the procedure must be like this:
14061 1. M-x org-save-all-org-buffers
14062 2. Pull changes from the other machine, resolve conflicts
14063 3. M-x org-revert-all-org-buffers"
14064 (interactive)
14065 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14066 (error "Abort"))
14067 (save-excursion
14068 (save-window-excursion
14069 (mapc
14070 (lambda (b)
14071 (when (and (with-current-buffer b (org-mode-p))
14072 (with-current-buffer b buffer-file-name))
14073 (switch-to-buffer b)
14074 (revert-buffer t 'no-confirm)))
14075 (buffer-list))
14076 (when (and (featurep 'org-id) org-id-track-globally)
14077 (org-id-locations-load)))))
14079 ;;;; Agenda files
14081 ;;;###autoload
14082 (defun org-iswitchb (&optional arg)
14083 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14084 With a prefix argument, restrict available to files.
14085 With two prefix arguments, restrict available buffers to agenda files."
14086 (interactive "P")
14087 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14088 ((equal arg '(16)) (org-buffer-list 'agenda))
14089 (t (org-buffer-list)))))
14090 (switch-to-buffer
14091 (org-icompleting-read "Org buffer: "
14092 (mapcar 'list (mapcar 'buffer-name blist))
14093 nil t))))
14095 ;;;###autoload
14096 (defalias 'org-ido-switchb 'org-iswitchb)
14098 (defun org-buffer-list (&optional predicate exclude-tmp)
14099 "Return a list of Org buffers.
14100 PREDICATE can be `export', `files' or `agenda'.
14102 export restrict the list to Export buffers.
14103 files restrict the list to buffers visiting Org files.
14104 agenda restrict the list to buffers visiting agenda files.
14106 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14107 (let* ((bfn nil)
14108 (agenda-files (and (eq predicate 'agenda)
14109 (mapcar 'file-truename (org-agenda-files t))))
14110 (filter
14111 (cond
14112 ((eq predicate 'files)
14113 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14114 ((eq predicate 'export)
14115 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14116 ((eq predicate 'agenda)
14117 (lambda (b)
14118 (with-current-buffer b
14119 (and (eq major-mode 'org-mode)
14120 (setq bfn (buffer-file-name b))
14121 (member (file-truename bfn) agenda-files)))))
14122 (t (lambda (b) (with-current-buffer b
14123 (or (eq major-mode 'org-mode)
14124 (string-match "\*Org .*Export"
14125 (buffer-name b)))))))))
14126 (delq nil
14127 (mapcar
14128 (lambda(b)
14129 (if (and (funcall filter b)
14130 (or (not exclude-tmp)
14131 (not (string-match "tmp" (buffer-name b)))))
14133 nil))
14134 (buffer-list)))))
14136 (defun org-agenda-files (&optional unrestricted archives)
14137 "Get the list of agenda files.
14138 Optional UNRESTRICTED means return the full list even if a restriction
14139 is currently in place.
14140 When ARCHIVES is t, include all archive files hat are really being
14141 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14142 `org-agenda-archives-mode' is t."
14143 (let ((files
14144 (cond
14145 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14146 ((stringp org-agenda-files) (org-read-agenda-file-list))
14147 ((listp org-agenda-files) org-agenda-files)
14148 (t (error "Invalid value of `org-agenda-files'")))))
14149 (setq files (apply 'append
14150 (mapcar (lambda (f)
14151 (if (file-directory-p f)
14152 (directory-files
14153 f t org-agenda-file-regexp)
14154 (list f)))
14155 files)))
14156 (when org-agenda-skip-unavailable-files
14157 (setq files (delq nil
14158 (mapcar (function
14159 (lambda (file)
14160 (and (file-readable-p file) file)))
14161 files))))
14162 (when (or (eq archives t)
14163 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14164 (setq files (org-add-archive-files files)))
14165 files))
14167 (defun org-edit-agenda-file-list ()
14168 "Edit the list of agenda files.
14169 Depending on setup, this either uses customize to edit the variable
14170 `org-agenda-files', or it visits the file that is holding the list. In the
14171 latter case, the buffer is set up in a way that saving it automatically kills
14172 the buffer and restores the previous window configuration."
14173 (interactive)
14174 (if (stringp org-agenda-files)
14175 (let ((cw (current-window-configuration)))
14176 (find-file org-agenda-files)
14177 (org-set-local 'org-window-configuration cw)
14178 (org-add-hook 'after-save-hook
14179 (lambda ()
14180 (set-window-configuration
14181 (prog1 org-window-configuration
14182 (kill-buffer (current-buffer))))
14183 (org-install-agenda-files-menu)
14184 (message "New agenda file list installed"))
14185 nil 'local)
14186 (message "%s" (substitute-command-keys
14187 "Edit list and finish with \\[save-buffer]")))
14188 (customize-variable 'org-agenda-files)))
14190 (defun org-store-new-agenda-file-list (list)
14191 "Set new value for the agenda file list and save it correctly."
14192 (if (stringp org-agenda-files)
14193 (let ((f org-agenda-files) b)
14194 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14195 (with-temp-file f
14196 (insert (mapconcat 'identity list "\n") "\n")))
14197 (let ((org-mode-hook nil) (org-inhibit-startup t)
14198 (org-insert-mode-line-in-empty-file nil))
14199 (setq org-agenda-files list)
14200 (customize-save-variable 'org-agenda-files org-agenda-files))))
14202 (defun org-read-agenda-file-list ()
14203 "Read the list of agenda files from a file."
14204 (when (file-directory-p org-agenda-files)
14205 (error "`org-agenda-files' cannot be a single directory"))
14206 (when (stringp org-agenda-files)
14207 (with-temp-buffer
14208 (insert-file-contents org-agenda-files)
14209 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14212 ;;;###autoload
14213 (defun org-cycle-agenda-files ()
14214 "Cycle through the files in `org-agenda-files'.
14215 If the current buffer visits an agenda file, find the next one in the list.
14216 If the current buffer does not, find the first agenda file."
14217 (interactive)
14218 (let* ((fs (org-agenda-files t))
14219 (files (append fs (list (car fs))))
14220 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14221 file)
14222 (unless files (error "No agenda files"))
14223 (catch 'exit
14224 (while (setq file (pop files))
14225 (if (equal (file-truename file) tcf)
14226 (when (car files)
14227 (find-file (car files))
14228 (throw 'exit t))))
14229 (find-file (car fs)))
14230 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14232 (defun org-agenda-file-to-front (&optional to-end)
14233 "Move/add the current file to the top of the agenda file list.
14234 If the file is not present in the list, it is added to the front. If it is
14235 present, it is moved there. With optional argument TO-END, add/move to the
14236 end of the list."
14237 (interactive "P")
14238 (let ((org-agenda-skip-unavailable-files nil)
14239 (file-alist (mapcar (lambda (x)
14240 (cons (file-truename x) x))
14241 (org-agenda-files t)))
14242 (ctf (file-truename buffer-file-name))
14243 x had)
14244 (setq x (assoc ctf file-alist) had x)
14246 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14247 (if to-end
14248 (setq file-alist (append (delq x file-alist) (list x)))
14249 (setq file-alist (cons x (delq x file-alist))))
14250 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14251 (org-install-agenda-files-menu)
14252 (message "File %s to %s of agenda file list"
14253 (if had "moved" "added") (if to-end "end" "front"))))
14255 (defun org-remove-file (&optional file)
14256 "Remove current file from the list of files in variable `org-agenda-files'.
14257 These are the files which are being checked for agenda entries.
14258 Optional argument FILE means, use this file instead of the current."
14259 (interactive)
14260 (let* ((org-agenda-skip-unavailable-files nil)
14261 (file (or file buffer-file-name))
14262 (true-file (file-truename file))
14263 (afile (abbreviate-file-name file))
14264 (files (delq nil (mapcar
14265 (lambda (x)
14266 (if (equal true-file
14267 (file-truename x))
14268 nil x))
14269 (org-agenda-files t)))))
14270 (if (not (= (length files) (length (org-agenda-files t))))
14271 (progn
14272 (org-store-new-agenda-file-list files)
14273 (org-install-agenda-files-menu)
14274 (message "Removed file: %s" afile))
14275 (message "File was not in list: %s (not removed)" afile))))
14277 (defun org-file-menu-entry (file)
14278 (vector file (list 'find-file file) t))
14280 (defun org-check-agenda-file (file)
14281 "Make sure FILE exists. If not, ask user what to do."
14282 (when (not (file-exists-p file))
14283 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14284 (abbreviate-file-name file))
14285 (let ((r (downcase (read-char-exclusive))))
14286 (cond
14287 ((equal r ?r)
14288 (org-remove-file file)
14289 (throw 'nextfile t))
14290 (t (error "Abort"))))))
14292 (defun org-get-agenda-file-buffer (file)
14293 "Get a buffer visiting FILE. If the buffer needs to be created, add
14294 it to the list of buffers which might be released later."
14295 (let ((buf (org-find-base-buffer-visiting file)))
14296 (if buf
14297 buf ; just return it
14298 ;; Make a new buffer and remember it
14299 (setq buf (find-file-noselect file))
14300 (if buf (push buf org-agenda-new-buffers))
14301 buf)))
14303 (defun org-release-buffers (blist)
14304 "Release all buffers in list, asking the user for confirmation when needed.
14305 When a buffer is unmodified, it is just killed. When modified, it is saved
14306 \(if the user agrees) and then killed."
14307 (let (buf file)
14308 (while (setq buf (pop blist))
14309 (setq file (buffer-file-name buf))
14310 (when (and (buffer-modified-p buf)
14311 file
14312 (y-or-n-p (format "Save file %s? " file)))
14313 (with-current-buffer buf (save-buffer)))
14314 (kill-buffer buf))))
14316 (defun org-prepare-agenda-buffers (files)
14317 "Create buffers for all agenda files, protect archived trees and comments."
14318 (interactive)
14319 (let ((pa '(:org-archived t))
14320 (pc '(:org-comment t))
14321 (pall '(:org-archived t :org-comment t))
14322 (inhibit-read-only t)
14323 (rea (concat ":" org-archive-tag ":"))
14324 bmp file re)
14325 (save-excursion
14326 (save-restriction
14327 (while (setq file (pop files))
14328 (catch 'nextfile
14329 (if (bufferp file)
14330 (set-buffer file)
14331 (org-check-agenda-file file)
14332 (set-buffer (org-get-agenda-file-buffer file)))
14333 (widen)
14334 (setq bmp (buffer-modified-p))
14335 (org-refresh-category-properties)
14336 (setq org-todo-keywords-for-agenda
14337 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14338 (setq org-done-keywords-for-agenda
14339 (append org-done-keywords-for-agenda org-done-keywords))
14340 (setq org-todo-keyword-alist-for-agenda
14341 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14342 (setq org-drawers-for-agenda
14343 (append org-drawers-for-agenda org-drawers))
14344 (setq org-tag-alist-for-agenda
14345 (append org-tag-alist-for-agenda org-tag-alist))
14347 (save-excursion
14348 (remove-text-properties (point-min) (point-max) pall)
14349 (when org-agenda-skip-archived-trees
14350 (goto-char (point-min))
14351 (while (re-search-forward rea nil t)
14352 (if (org-on-heading-p t)
14353 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14354 (goto-char (point-min))
14355 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14356 (while (re-search-forward re nil t)
14357 (add-text-properties
14358 (match-beginning 0) (org-end-of-subtree t) pc)))
14359 (set-buffer-modified-p bmp)))))
14360 (setq org-todo-keyword-alist-for-agenda
14361 (org-uniquify org-todo-keyword-alist-for-agenda)
14362 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14364 ;;;; Embedded LaTeX
14366 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14367 "Keymap for the minor `org-cdlatex-mode'.")
14369 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14370 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14371 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14372 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14373 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14375 (defvar org-cdlatex-texmathp-advice-is-done nil
14376 "Flag remembering if we have applied the advice to texmathp already.")
14378 (define-minor-mode org-cdlatex-mode
14379 "Toggle the minor `org-cdlatex-mode'.
14380 This mode supports entering LaTeX environment and math in LaTeX fragments
14381 in Org-mode.
14382 \\{org-cdlatex-mode-map}"
14383 nil " OCDL" nil
14384 (when org-cdlatex-mode (require 'cdlatex))
14385 (unless org-cdlatex-texmathp-advice-is-done
14386 (setq org-cdlatex-texmathp-advice-is-done t)
14387 (defadvice texmathp (around org-math-always-on activate)
14388 "Always return t in org-mode buffers.
14389 This is because we want to insert math symbols without dollars even outside
14390 the LaTeX math segments. If Orgmode thinks that point is actually inside
14391 an embedded LaTeX fragment, let texmathp do its job.
14392 \\[org-cdlatex-mode-map]"
14393 (interactive)
14394 (let (p)
14395 (cond
14396 ((not (org-mode-p)) ad-do-it)
14397 ((eq this-command 'cdlatex-math-symbol)
14398 (setq ad-return-value t
14399 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14401 (let ((p (org-inside-LaTeX-fragment-p)))
14402 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14403 (setq ad-return-value t
14404 texmathp-why '("Org-mode embedded math" . 0))
14405 (if p ad-do-it)))))))))
14407 (defun turn-on-org-cdlatex ()
14408 "Unconditionally turn on `org-cdlatex-mode'."
14409 (org-cdlatex-mode 1))
14411 (defun org-inside-LaTeX-fragment-p ()
14412 "Test if point is inside a LaTeX fragment.
14413 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14414 sequence appearing also before point.
14415 Even though the matchers for math are configurable, this function assumes
14416 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14417 delimiters are skipped when they have been removed by customization.
14418 The return value is nil, or a cons cell with the delimiter and
14419 and the position of this delimiter.
14421 This function does a reasonably good job, but can locally be fooled by
14422 for example currency specifications. For example it will assume being in
14423 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14424 fragments that are properly closed, but during editing, we have to live
14425 with the uncertainty caused by missing closing delimiters. This function
14426 looks only before point, not after."
14427 (catch 'exit
14428 (let ((pos (point))
14429 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14430 (lim (progn
14431 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14432 (point)))
14433 dd-on str (start 0) m re)
14434 (goto-char pos)
14435 (when dodollar
14436 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14437 re (nth 1 (assoc "$" org-latex-regexps)))
14438 (while (string-match re str start)
14439 (cond
14440 ((= (match-end 0) (length str))
14441 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14442 ((= (match-end 0) (- (length str) 5))
14443 (throw 'exit nil))
14444 (t (setq start (match-end 0))))))
14445 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14446 (goto-char pos)
14447 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14448 (and (match-beginning 2) (throw 'exit nil))
14449 ;; count $$
14450 (while (re-search-backward "\\$\\$" lim t)
14451 (setq dd-on (not dd-on)))
14452 (goto-char pos)
14453 (if dd-on (cons "$$" m))))))
14456 (defun org-try-cdlatex-tab ()
14457 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14458 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14459 - inside a LaTeX fragment, or
14460 - after the first word in a line, where an abbreviation expansion could
14461 insert a LaTeX environment."
14462 (when org-cdlatex-mode
14463 (cond
14464 ((save-excursion
14465 (skip-chars-backward "a-zA-Z0-9*")
14466 (skip-chars-backward " \t")
14467 (bolp))
14468 (cdlatex-tab) t)
14469 ((org-inside-LaTeX-fragment-p)
14470 (cdlatex-tab) t)
14471 (t nil))))
14473 (defun org-cdlatex-underscore-caret (&optional arg)
14474 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14475 Revert to the normal definition outside of these fragments."
14476 (interactive "P")
14477 (if (org-inside-LaTeX-fragment-p)
14478 (call-interactively 'cdlatex-sub-superscript)
14479 (let (org-cdlatex-mode)
14480 (call-interactively (key-binding (vector last-input-event))))))
14482 (defun org-cdlatex-math-modify (&optional arg)
14483 "Execute `cdlatex-math-modify' in LaTeX fragments.
14484 Revert to the normal definition outside of these fragments."
14485 (interactive "P")
14486 (if (org-inside-LaTeX-fragment-p)
14487 (call-interactively 'cdlatex-math-modify)
14488 (let (org-cdlatex-mode)
14489 (call-interactively (key-binding (vector last-input-event))))))
14491 (defvar org-latex-fragment-image-overlays nil
14492 "List of overlays carrying the images of latex fragments.")
14493 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14495 (defun org-remove-latex-fragment-image-overlays ()
14496 "Remove all overlays with LaTeX fragment images in current buffer."
14497 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14498 (setq org-latex-fragment-image-overlays nil))
14500 (defun org-preview-latex-fragment (&optional subtree)
14501 "Preview the LaTeX fragment at point, or all locally or globally.
14502 If the cursor is in a LaTeX fragment, create the image and overlay
14503 it over the source code. If there is no fragment at point, display
14504 all fragments in the current text, from one headline to the next. With
14505 prefix SUBTREE, display all fragments in the current subtree. With a
14506 double prefix `C-u C-u', or when the cursor is before the first headline,
14507 display all fragments in the buffer.
14508 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14509 (interactive "P")
14510 (org-remove-latex-fragment-image-overlays)
14511 (save-excursion
14512 (save-restriction
14513 (let (beg end at msg)
14514 (cond
14515 ((or (equal subtree '(16))
14516 (not (save-excursion
14517 (re-search-backward (concat "^" outline-regexp) nil t))))
14518 (setq beg (point-min) end (point-max)
14519 msg "Creating images for buffer...%s"))
14520 ((equal subtree '(4))
14521 (org-back-to-heading)
14522 (setq beg (point) end (org-end-of-subtree t)
14523 msg "Creating images for subtree...%s"))
14525 (if (setq at (org-inside-LaTeX-fragment-p))
14526 (goto-char (max (point-min) (- (cdr at) 2)))
14527 (org-back-to-heading))
14528 (setq beg (point) end (progn (outline-next-heading) (point))
14529 msg (if at "Creating image...%s"
14530 "Creating images for entry...%s"))))
14531 (message msg "")
14532 (narrow-to-region beg end)
14533 (goto-char beg)
14534 (org-format-latex
14535 (concat "ltxpng/" (file-name-sans-extension
14536 (file-name-nondirectory
14537 buffer-file-name)))
14538 default-directory 'overlays msg at 'forbuffer)
14539 (message msg "done. Use `C-c C-c' to remove images.")))))
14541 (defvar org-latex-regexps
14542 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14543 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14544 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14545 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14546 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14547 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14548 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14549 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14550 "Regular expressions for matching embedded LaTeX.")
14552 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14553 "Replace LaTeX fragments with links to an image, and produce images.
14554 Some of the options can be changed using the variable
14555 `org-format-latex-options'."
14556 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14557 (let* ((prefixnodir (file-name-nondirectory prefix))
14558 (absprefix (expand-file-name prefix dir))
14559 (todir (file-name-directory absprefix))
14560 (opt org-format-latex-options)
14561 (matchers (plist-get opt :matchers))
14562 (re-list org-latex-regexps)
14563 (cnt 0) txt link beg end re e checkdir
14564 executables-checked
14565 m n block linkfile movefile ov)
14566 ;; Check if there are old images files with this prefix, and remove them
14567 (when (file-directory-p todir)
14568 (mapc 'delete-file
14569 (directory-files
14570 todir 'full
14571 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14572 ;; Check the different regular expressions
14573 (while (setq e (pop re-list))
14574 (setq m (car e) re (nth 1 e) n (nth 2 e)
14575 block (if (nth 3 e) "\n\n" ""))
14576 (when (member m matchers)
14577 (goto-char (point-min))
14578 (while (re-search-forward re nil t)
14579 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14580 (not (get-text-property (match-beginning n)
14581 'org-protected))
14582 (or (not overlays)
14583 (not (eq (get-char-property (match-beginning n)
14584 'org-overlay-type)
14585 'org-latex-overlay))))
14586 (setq txt (match-string n)
14587 beg (match-beginning n) end (match-end n)
14588 cnt (1+ cnt)
14589 linkfile (format "%s_%04d.png" prefix cnt)
14590 movefile (format "%s_%04d.png" absprefix cnt)
14591 link (concat block "[[file:" linkfile "]]" block))
14592 (if msg (message msg cnt))
14593 (goto-char beg)
14594 (unless checkdir ; make sure the directory exists
14595 (setq checkdir t)
14596 (or (file-directory-p todir) (make-directory todir)))
14598 (unless executables-checked
14599 (org-check-external-command
14600 "latex" "needed to convert LaTeX fragments to images")
14601 (org-check-external-command
14602 "dvipng" "needed to convert LaTeX fragments to images")
14603 (setq executables-checked t))
14605 (org-create-formula-image
14606 txt movefile opt forbuffer)
14607 (if overlays
14608 (progn
14609 (mapc (lambda (o)
14610 (if (eq (org-overlay-get o 'org-overlay-type)
14611 'org-latex-overlay)
14612 (org-delete-overlay o)))
14613 (org-overlays-in beg end))
14614 (setq ov (org-make-overlay beg end))
14615 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14616 (if (featurep 'xemacs)
14617 (progn
14618 (org-overlay-put ov 'invisible t)
14619 (org-overlay-put
14620 ov 'end-glyph
14621 (make-glyph (vector 'png :file movefile))))
14622 (org-overlay-put
14623 ov 'display
14624 (list 'image :type 'png :file movefile :ascent 'center)))
14625 (push ov org-latex-fragment-image-overlays)
14626 (goto-char end))
14627 (delete-region beg end)
14628 (insert link))))))))
14630 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14631 ;; This function borrows from Ganesh Swami's latex2png.el
14632 (defun org-create-formula-image (string tofile options buffer)
14633 "This calls dvipng."
14634 (require 'org-latex)
14635 (let* ((tmpdir (if (featurep 'xemacs)
14636 (temp-directory)
14637 temporary-file-directory))
14638 (texfilebase (make-temp-name
14639 (expand-file-name "orgtex" tmpdir)))
14640 (texfile (concat texfilebase ".tex"))
14641 (dvifile (concat texfilebase ".dvi"))
14642 (pngfile (concat texfilebase ".png"))
14643 (fnh (if (featurep 'xemacs)
14644 (font-height (get-face-font 'default))
14645 (face-attribute 'default :height nil)))
14646 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14647 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14648 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14649 "Black"))
14650 (bg (or (plist-get options (if buffer :background :html-background))
14651 "Transparent")))
14652 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14653 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14654 (with-temp-file texfile
14655 (insert org-format-latex-header
14656 (if org-export-latex-packages-alist
14657 (concat "\n"
14658 (mapconcat (lambda(p)
14659 (if (equal "" (car p))
14660 (format "\\usepackage{%s}" (cadr p))
14661 (format "\\usepackage[%s]{%s}"
14662 (car p) (cadr p))))
14663 org-export-latex-packages-alist "\n"))
14665 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14666 (let ((dir default-directory))
14667 (condition-case nil
14668 (progn
14669 (cd tmpdir)
14670 (call-process "latex" nil nil nil texfile))
14671 (error nil))
14672 (cd dir))
14673 (if (not (file-exists-p dvifile))
14674 (progn (message "Failed to create dvi file from %s" texfile) nil)
14675 (condition-case nil
14676 (call-process "dvipng" nil nil nil
14677 "-fg" fg "-bg" bg
14678 "-D" dpi
14679 ;;"-x" scale "-y" scale
14680 "-T" "tight"
14681 "-o" pngfile
14682 dvifile)
14683 (error nil))
14684 (if (not (file-exists-p pngfile))
14685 (progn (message "Failed to create png file from %s" texfile) nil)
14686 ;; Use the requested file name and clean up
14687 (copy-file pngfile tofile 'replace)
14688 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14689 (delete-file (concat texfilebase e)))
14690 pngfile))))
14692 (defun org-dvipng-color (attr)
14693 "Return an rgb color specification for dvipng."
14694 (apply 'format "rgb %s %s %s"
14695 (mapcar 'org-normalize-color
14696 (color-values (face-attribute 'default attr nil)))))
14698 (defun org-normalize-color (value)
14699 "Return string to be used as color value for an RGB component."
14700 (format "%g" (/ value 65535.0)))
14702 ;;;; Key bindings
14704 ;; Make `C-c C-x' a prefix key
14705 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14707 ;; TAB key with modifiers
14708 (org-defkey org-mode-map "\C-i" 'org-cycle)
14709 (org-defkey org-mode-map [(tab)] 'org-cycle)
14710 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14711 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14712 (org-defkey org-mode-map "\M-\t" 'org-complete)
14713 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14714 ;; The following line is necessary under Suse GNU/Linux
14715 (unless (featurep 'xemacs)
14716 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14717 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14718 (define-key org-mode-map [backtab] 'org-shifttab)
14720 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14721 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14722 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14724 ;; Cursor keys with modifiers
14725 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14726 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14727 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14728 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14730 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14731 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14732 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14733 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14735 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14736 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14737 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14738 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14740 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14741 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14743 ;;; Extra keys for tty access.
14744 ;; We only set them when really needed because otherwise the
14745 ;; menus don't show the simple keys
14747 (when (or org-use-extra-keys
14748 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14749 (not window-system))
14750 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14751 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14752 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14753 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14754 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14755 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14756 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14757 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14758 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14759 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14760 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14761 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14762 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14763 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14764 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14765 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14766 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14767 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14768 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14769 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14770 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14771 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14772 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14773 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14774 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14775 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14776 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14777 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14779 ;; All the other keys
14781 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14782 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14783 (if (boundp 'narrow-map)
14784 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14785 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14786 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14787 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14788 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14789 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14790 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14791 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14792 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14793 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14794 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14795 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14796 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14797 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14798 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14799 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14800 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14801 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14802 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14803 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14804 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14805 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14806 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14807 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14808 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14809 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14810 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14811 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14812 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14813 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14814 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14815 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14816 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14817 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14818 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14819 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14820 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14821 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14822 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14823 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14824 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14825 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14826 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14827 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14828 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14829 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14830 (org-defkey org-mode-map "\C-c^" 'org-sort)
14831 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14832 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14833 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14834 (org-defkey org-mode-map "\C-m" 'org-return)
14835 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14836 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14837 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14838 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14839 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14840 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14841 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14842 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14843 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14844 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14845 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14846 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14847 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14848 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14849 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14850 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14851 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14852 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14853 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14854 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14855 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14857 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14858 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14859 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14860 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14862 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14863 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14864 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14865 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14866 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14867 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14868 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14869 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14870 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14871 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14872 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14873 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14874 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14875 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14876 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14878 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14879 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14880 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14881 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14883 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14885 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14887 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14888 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14890 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14893 (when (featurep 'xemacs)
14894 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14897 (defconst org-speed-commands-default
14899 ("Outline Navigation")
14900 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
14901 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
14902 ("f" . (org-speed-move-safe 'org-forward-same-level))
14903 ("b" . (org-speed-move-safe 'org-backward-same-level))
14904 ("u" . (org-speed-move-safe 'outline-up-heading))
14905 ("j" . org-goto)
14906 ("g" . (org-refile t))
14907 ("Outline Visibility")
14908 ("c" . org-cycle)
14909 ("C" . org-shifttab)
14910 (" " . org-display-outline-path)
14911 ("Outline Structure Editing")
14912 ("U" . org-shiftmetaup)
14913 ("D" . org-shiftmetadown)
14914 ("r" . org-metaright)
14915 ("l" . org-metaleft)
14916 ("R" . org-shiftmetaright)
14917 ("L" . org-shiftmetaleft)
14918 ("i" . (progn (forward-char 1) (call-interactively
14919 'org-insert-heading-respect-content)))
14920 ("^" . org-sort)
14921 ("w" . org-refile)
14922 ("a" . org-archive-subtree-default-with-confirmation)
14923 ("." . outline-mark-subtree)
14924 ("Clock Commands")
14925 ("I" . org-clock-in)
14926 ("O" . org-clock-out)
14927 ("Meta Data Editing")
14928 ("t" . org-todo)
14929 ("0" . (org-priority ?\ ))
14930 ("1" . (org-priority ?A))
14931 ("2" . (org-priority ?B))
14932 ("3" . (org-priority ?C))
14933 (";" . org-set-tags-command)
14934 ("e" . org-set-effort)
14935 ("Agenda Views etc")
14936 ("v" . org-agenda)
14937 ("/" . org-sparse-tree)
14938 ("/" . org-sparse-tree)
14939 ("Misc")
14940 ("o" . org-open-at-point)
14941 ("?" . org-speed-command-help)
14943 "The default speed commands.")
14945 (defun org-print-speed-command (e)
14946 (if (> (length (car e)) 1)
14947 (progn
14948 (princ "\n")
14949 (princ (car e))
14950 (princ "\n")
14951 (princ (make-string (length (car e)) ?-))
14952 (princ "\n"))
14953 (princ (car e))
14954 (princ " ")
14955 (if (symbolp (cdr e))
14956 (princ (symbol-name (cdr e)))
14957 (prin1 (cdr e)))
14958 (princ "\n")))
14960 (defun org-speed-command-help ()
14961 "Show the available speed commands."
14962 (interactive)
14963 (if (not org-use-speed-commands)
14964 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
14965 (with-output-to-temp-buffer "*Help*"
14966 (princ "User-defined Speed commands\n===========================\n")
14967 (mapc 'org-print-speed-command org-speed-commands-user)
14968 (princ "\n")
14969 (princ "Built-in Speed commands\n=======================\n")
14970 (mapc 'org-print-speed-command org-speed-commands-default))
14971 (with-current-buffer "*Help*"
14972 (setq truncate-lines t))))
14974 (defun org-speed-move-safe (cmd)
14975 "Execute CMD, but make sure that the cursor always ends up in a headline.
14976 If not, return to the original position and throw an error."
14977 (interactive)
14978 (let ((pos (point)))
14979 (call-interactively cmd)
14980 (unless (and (bolp) (org-on-heading-p))
14981 (goto-char pos)
14982 (error "Boundary reached while executing %s" cmd))))
14984 (defvar org-self-insert-command-undo-counter 0)
14986 (defvar org-table-auto-blank-field) ; defined in org-table.el
14987 (defvar org-speed-command nil)
14988 (defun org-self-insert-command (N)
14989 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14990 If the cursor is in a table looking at whitespace, the whitespace is
14991 overwritten, and the table is not marked as requiring realignment."
14992 (interactive "p")
14993 (cond
14994 ((and org-use-speed-commands
14995 (or (and (bolp) (looking-at outline-regexp))
14996 (and (functionp org-use-speed-commands)
14997 (funcall org-use-speed-commands)))
14998 (setq
14999 org-speed-command
15000 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15001 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15002 (cond
15003 ((commandp org-speed-command)
15004 (setq this-command org-speed-command)
15005 (call-interactively org-speed-command))
15006 ((functionp org-speed-command)
15007 (funcall org-speed-command))
15008 ((and org-speed-command (listp org-speed-command))
15009 (eval org-speed-command))
15010 (t (let (org-use-speed-commands)
15011 (call-interactively 'org-self-insert-command)))))
15012 ((and
15013 (org-table-p)
15014 (progn
15015 ;; check if we blank the field, and if that triggers align
15016 (and (featurep 'org-table) org-table-auto-blank-field
15017 (member last-command
15018 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15019 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15020 ;; got extra space, this field does not determine column width
15021 (let (org-table-may-need-update) (org-table-blank-field))
15022 ;; no extra space, this field may determine column width
15023 (org-table-blank-field)))
15025 (eq N 1)
15026 (looking-at "[^|\n]* |"))
15027 (let (org-table-may-need-update)
15028 (goto-char (1- (match-end 0)))
15029 (delete-backward-char 1)
15030 (goto-char (match-beginning 0))
15031 (self-insert-command N)))
15033 (setq org-table-may-need-update t)
15034 (self-insert-command N)
15035 (org-fix-tags-on-the-fly)
15036 (if org-self-insert-cluster-for-undo
15037 (if (not (eq last-command 'org-self-insert-command))
15038 (setq org-self-insert-command-undo-counter 1)
15039 (if (>= org-self-insert-command-undo-counter 20)
15040 (setq org-self-insert-command-undo-counter 1)
15041 (and (> org-self-insert-command-undo-counter 0)
15042 buffer-undo-list
15043 (not (cadr buffer-undo-list)) ; remove nil entry
15044 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15045 (setq org-self-insert-command-undo-counter
15046 (1+ org-self-insert-command-undo-counter))))))))
15048 (defun org-fix-tags-on-the-fly ()
15049 (when (and (equal (char-after (point-at-bol)) ?*)
15050 (org-on-heading-p))
15051 (org-align-tags-here org-tags-column)))
15053 (defun org-delete-backward-char (N)
15054 "Like `delete-backward-char', insert whitespace at field end in tables.
15055 When deleting backwards, in tables this function will insert whitespace in
15056 front of the next \"|\" separator, to keep the table aligned. The table will
15057 still be marked for re-alignment if the field did fill the entire column,
15058 because, in this case the deletion might narrow the column."
15059 (interactive "p")
15060 (if (and (org-table-p)
15061 (eq N 1)
15062 (string-match "|" (buffer-substring (point-at-bol) (point)))
15063 (looking-at ".*?|"))
15064 (let ((pos (point))
15065 (noalign (looking-at "[^|\n\r]* |"))
15066 (c org-table-may-need-update))
15067 (backward-delete-char N)
15068 (skip-chars-forward "^|")
15069 (insert " ")
15070 (goto-char (1- pos))
15071 ;; noalign: if there were two spaces at the end, this field
15072 ;; does not determine the width of the column.
15073 (if noalign (setq org-table-may-need-update c)))
15074 (backward-delete-char N)
15075 (org-fix-tags-on-the-fly)))
15077 (defun org-delete-char (N)
15078 "Like `delete-char', but insert whitespace at field end in tables.
15079 When deleting characters, in tables this function will insert whitespace in
15080 front of the next \"|\" separator, to keep the table aligned. The table will
15081 still be marked for re-alignment if the field did fill the entire column,
15082 because, in this case the deletion might narrow the column."
15083 (interactive "p")
15084 (if (and (org-table-p)
15085 (not (bolp))
15086 (not (= (char-after) ?|))
15087 (eq N 1))
15088 (if (looking-at ".*?|")
15089 (let ((pos (point))
15090 (noalign (looking-at "[^|\n\r]* |"))
15091 (c org-table-may-need-update))
15092 (replace-match (concat
15093 (substring (match-string 0) 1 -1)
15094 " |"))
15095 (goto-char pos)
15096 ;; noalign: if there were two spaces at the end, this field
15097 ;; does not determine the width of the column.
15098 (if noalign (setq org-table-may-need-update c)))
15099 (delete-char N))
15100 (delete-char N)
15101 (org-fix-tags-on-the-fly)))
15103 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15104 (put 'org-self-insert-command 'delete-selection t)
15105 (put 'orgtbl-self-insert-command 'delete-selection t)
15106 (put 'org-delete-char 'delete-selection 'supersede)
15107 (put 'org-delete-backward-char 'delete-selection 'supersede)
15108 (put 'org-yank 'delete-selection 'yank)
15110 ;; Make `flyspell-mode' delay after some commands
15111 (put 'org-self-insert-command 'flyspell-delayed t)
15112 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15113 (put 'org-delete-char 'flyspell-delayed t)
15114 (put 'org-delete-backward-char 'flyspell-delayed t)
15116 ;; Make pabbrev-mode expand after org-mode commands
15117 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15118 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15120 ;; How to do this: Measure non-white length of current string
15121 ;; If equal to column width, we should realign.
15123 (defun org-remap (map &rest commands)
15124 "In MAP, remap the functions given in COMMANDS.
15125 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15126 (let (new old)
15127 (while commands
15128 (setq old (pop commands) new (pop commands))
15129 (if (fboundp 'command-remapping)
15130 (org-defkey map (vector 'remap old) new)
15131 (substitute-key-definition old new map global-map)))))
15133 (when (eq org-enable-table-editor 'optimized)
15134 ;; If the user wants maximum table support, we need to hijack
15135 ;; some standard editing functions
15136 (org-remap org-mode-map
15137 'self-insert-command 'org-self-insert-command
15138 'delete-char 'org-delete-char
15139 'delete-backward-char 'org-delete-backward-char)
15140 (org-defkey org-mode-map "|" 'org-force-self-insert))
15142 (defvar org-ctrl-c-ctrl-c-hook nil
15143 "Hook for functions attaching themselves to `C-c C-c'.
15144 This can be used to add additional functionality to the C-c C-c key which
15145 executes context-dependent commands.
15146 Each function will be called with no arguments. The function must check
15147 if the context is appropriate for it to act. If yes, it should do its
15148 thing and then return a non-nil value. If the context is wrong,
15149 just do nothing and return nil.")
15151 (defvar org-tab-first-hook nil
15152 "Hook for functions to attach themselves to TAB.
15153 See `org-ctrl-c-ctrl-c-hook' for more information.
15154 This hook runs as the first action when TAB is pressed, even before
15155 `org-cycle' messes around with the `outline-regexp' to cater for
15156 inline tasks and plain list item folding.
15157 If any function in this hook returns t, not other actions like table
15158 field motion visibility cycling will be done.")
15160 (defvar org-tab-after-check-for-table-hook nil
15161 "Hook for functions to attach themselves to TAB.
15162 See `org-ctrl-c-ctrl-c-hook' for more information.
15163 This hook runs after it has been established that the cursor is not in a
15164 table, but before checking if the cursor is in a headline or if global cycling
15165 should be done.
15166 If any function in this hook returns t, not other actions like visibility
15167 cycling will be done.")
15169 (defvar org-tab-after-check-for-cycling-hook nil
15170 "Hook for functions to attach themselves to TAB.
15171 See `org-ctrl-c-ctrl-c-hook' for more information.
15172 This hook runs after it has been established that not table field motion and
15173 not visibility should be done because of current context. This is probably
15174 the place where a package like yasnippets can hook in.")
15176 (defvar org-tab-before-tab-emulation-hook nil
15177 "Hook for functions to attach themselves to TAB.
15178 See `org-ctrl-c-ctrl-c-hook' for more information.
15179 This hook runs after every other options for TAB have been exhausted, but
15180 before indentation and \t insertion takes place.")
15182 (defvar org-metaleft-hook nil
15183 "Hook for functions attaching themselves to `M-left'.
15184 See `org-ctrl-c-ctrl-c-hook' for more information.")
15185 (defvar org-metaright-hook nil
15186 "Hook for functions attaching themselves to `M-right'.
15187 See `org-ctrl-c-ctrl-c-hook' for more information.")
15188 (defvar org-metaup-hook nil
15189 "Hook for functions attaching themselves to `M-up'.
15190 See `org-ctrl-c-ctrl-c-hook' for more information.")
15191 (defvar org-metadown-hook nil
15192 "Hook for functions attaching themselves to `M-down'.
15193 See `org-ctrl-c-ctrl-c-hook' for more information.")
15194 (defvar org-shiftmetaleft-hook nil
15195 "Hook for functions attaching themselves to `M-S-left'.
15196 See `org-ctrl-c-ctrl-c-hook' for more information.")
15197 (defvar org-shiftmetaright-hook nil
15198 "Hook for functions attaching themselves to `M-S-right'.
15199 See `org-ctrl-c-ctrl-c-hook' for more information.")
15200 (defvar org-shiftmetaup-hook nil
15201 "Hook for functions attaching themselves to `M-S-up'.
15202 See `org-ctrl-c-ctrl-c-hook' for more information.")
15203 (defvar org-shiftmetadown-hook nil
15204 "Hook for functions attaching themselves to `M-S-down'.
15205 See `org-ctrl-c-ctrl-c-hook' for more information.")
15206 (defvar org-metareturn-hook nil
15207 "Hook for functions attaching themselves to `M-RET'.
15208 See `org-ctrl-c-ctrl-c-hook' for more information.")
15210 (defun org-modifier-cursor-error ()
15211 "Throw an error, a modified cursor command was applied in wrong context."
15212 (error "This command is active in special context like tables, headlines or items"))
15214 (defun org-shiftselect-error ()
15215 "Throw an error because Shift-Cursor command was applied in wrong context."
15216 (if (and (boundp 'shift-select-mode) shift-select-mode)
15217 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15218 (error "This command works only in special context like headlines or timestamps")))
15220 (defun org-call-for-shift-select (cmd)
15221 (let ((this-command-keys-shift-translated t))
15222 (call-interactively cmd)))
15224 (defun org-shifttab (&optional arg)
15225 "Global visibility cycling or move to previous table field.
15226 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15227 on context.
15228 See the individual commands for more information."
15229 (interactive "P")
15230 (cond
15231 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15232 ((integerp arg)
15233 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15234 (message "Content view to level: %d" arg)
15235 (org-content (prefix-numeric-value arg2))
15236 (setq org-cycle-global-status 'overview)))
15237 (t (call-interactively 'org-global-cycle))))
15239 (defun org-shiftmetaleft ()
15240 "Promote subtree or delete table column.
15241 Calls `org-promote-subtree', `org-outdent-item',
15242 or `org-table-delete-column', depending on context.
15243 See the individual commands for more information."
15244 (interactive)
15245 (cond
15246 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15247 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15248 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15249 ((org-at-item-p) (call-interactively 'org-outdent-item))
15250 (t (org-modifier-cursor-error))))
15252 (defun org-shiftmetaright ()
15253 "Demote subtree or insert table column.
15254 Calls `org-demote-subtree', `org-indent-item',
15255 or `org-table-insert-column', depending on context.
15256 See the individual commands for more information."
15257 (interactive)
15258 (cond
15259 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15260 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15261 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15262 ((org-at-item-p) (call-interactively 'org-indent-item))
15263 (t (org-modifier-cursor-error))))
15265 (defun org-shiftmetaup (&optional arg)
15266 "Move subtree up or kill table row.
15267 Calls `org-move-subtree-up' or `org-table-kill-row' or
15268 `org-move-item-up' depending on context. See the individual commands
15269 for more information."
15270 (interactive "P")
15271 (cond
15272 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15273 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15274 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15275 ((org-at-item-p) (call-interactively 'org-move-item-up))
15276 (t (org-modifier-cursor-error))))
15278 (defun org-shiftmetadown (&optional arg)
15279 "Move subtree down or insert table row.
15280 Calls `org-move-subtree-down' or `org-table-insert-row' or
15281 `org-move-item-down', depending on context. See the individual
15282 commands for more information."
15283 (interactive "P")
15284 (cond
15285 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15286 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15287 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15288 ((org-at-item-p) (call-interactively 'org-move-item-down))
15289 (t (org-modifier-cursor-error))))
15291 (defun org-metaleft (&optional arg)
15292 "Promote heading or move table column to left.
15293 Calls `org-do-promote' or `org-table-move-column', depending on context.
15294 With no specific context, calls the Emacs default `backward-word'.
15295 See the individual commands for more information."
15296 (interactive "P")
15297 (cond
15298 ((run-hook-with-args-until-success 'org-metaleft-hook))
15299 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15300 ((or (org-on-heading-p)
15301 (and (org-region-active-p)
15302 (save-excursion
15303 (goto-char (region-beginning))
15304 (org-on-heading-p))))
15305 (call-interactively 'org-do-promote))
15306 ((or (org-at-item-p)
15307 (and (org-region-active-p)
15308 (save-excursion
15309 (goto-char (region-beginning))
15310 (org-at-item-p))))
15311 (call-interactively 'org-outdent-item))
15312 (t (call-interactively 'backward-word))))
15314 (defun org-metaright (&optional arg)
15315 "Demote subtree or move table column to right.
15316 Calls `org-do-demote' or `org-table-move-column', depending on context.
15317 With no specific context, calls the Emacs default `forward-word'.
15318 See the individual commands for more information."
15319 (interactive "P")
15320 (cond
15321 ((run-hook-with-args-until-success 'org-metaright-hook))
15322 ((org-at-table-p) (call-interactively 'org-table-move-column))
15323 ((or (org-on-heading-p)
15324 (and (org-region-active-p)
15325 (save-excursion
15326 (goto-char (region-beginning))
15327 (org-on-heading-p))))
15328 (call-interactively 'org-do-demote))
15329 ((or (org-at-item-p)
15330 (and (org-region-active-p)
15331 (save-excursion
15332 (goto-char (region-beginning))
15333 (org-at-item-p))))
15334 (call-interactively 'org-indent-item))
15335 (t (call-interactively 'forward-word))))
15337 (defun org-metaup (&optional arg)
15338 "Move subtree up or move table row up.
15339 Calls `org-move-subtree-up' or `org-table-move-row' or
15340 `org-move-item-up', depending on context. See the individual commands
15341 for more information."
15342 (interactive "P")
15343 (cond
15344 ((run-hook-with-args-until-success 'org-metaup-hook))
15345 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15346 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15347 ((org-at-item-p) (call-interactively 'org-move-item-up))
15348 (t (transpose-lines 1) (beginning-of-line -1))))
15350 (defun org-metadown (&optional arg)
15351 "Move subtree down or move table row down.
15352 Calls `org-move-subtree-down' or `org-table-move-row' or
15353 `org-move-item-down', depending on context. See the individual
15354 commands for more information."
15355 (interactive "P")
15356 (cond
15357 ((run-hook-with-args-until-success 'org-metadown-hook))
15358 ((org-at-table-p) (call-interactively 'org-table-move-row))
15359 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15360 ((org-at-item-p) (call-interactively 'org-move-item-down))
15361 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15363 (defun org-shiftup (&optional arg)
15364 "Increase item in timestamp or increase priority of current headline.
15365 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15366 depending on context. See the individual commands for more information."
15367 (interactive "P")
15368 (cond
15369 ((and org-support-shift-select (org-region-active-p))
15370 (org-call-for-shift-select 'previous-line))
15371 ((org-at-timestamp-p t)
15372 (call-interactively (if org-edit-timestamp-down-means-later
15373 'org-timestamp-down 'org-timestamp-up)))
15374 ((and (not (eq org-support-shift-select 'always))
15375 org-enable-priority-commands
15376 (org-on-heading-p))
15377 (call-interactively 'org-priority-up))
15378 ((and (not org-support-shift-select) (org-at-item-p))
15379 (call-interactively 'org-previous-item))
15380 ((org-clocktable-try-shift 'up arg))
15381 (org-support-shift-select
15382 (org-call-for-shift-select 'previous-line))
15383 (t (org-shiftselect-error))))
15385 (defun org-shiftdown (&optional arg)
15386 "Decrease item in timestamp or decrease priority of current headline.
15387 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15388 depending on context. See the individual commands for more information."
15389 (interactive "P")
15390 (cond
15391 ((and org-support-shift-select (org-region-active-p))
15392 (org-call-for-shift-select 'next-line))
15393 ((org-at-timestamp-p t)
15394 (call-interactively (if org-edit-timestamp-down-means-later
15395 'org-timestamp-up 'org-timestamp-down)))
15396 ((and (not (eq org-support-shift-select 'always))
15397 org-enable-priority-commands
15398 (org-on-heading-p))
15399 (call-interactively 'org-priority-down))
15400 ((and (not org-support-shift-select) (org-at-item-p))
15401 (call-interactively 'org-next-item))
15402 ((org-clocktable-try-shift 'down arg))
15403 (org-support-shift-select
15404 (org-call-for-shift-select 'next-line))
15405 (t (org-shiftselect-error))))
15407 (defun org-shiftright (&optional arg)
15408 "Cycle the thing at point or in the current line, depending on context.
15409 Depending on context, this does one of the following:
15411 - switch a timestamp at point one day into the future
15412 - on a headline, switch to the next TODO keyword.
15413 - on an item, switch entire list to the next bullet type
15414 - on a property line, switch to the next allowed value
15415 - on a clocktable definition line, move time block into the future"
15416 (interactive "P")
15417 (cond
15418 ((and org-support-shift-select (org-region-active-p))
15419 (org-call-for-shift-select 'forward-char))
15420 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15421 ((and (not (eq org-support-shift-select 'always))
15422 (org-on-heading-p))
15423 (let ((org-inhibit-logging
15424 (not org-treat-S-cursor-todo-selection-as-state-change))
15425 (org-inhibit-blocking
15426 (not org-treat-S-cursor-todo-selection-as-state-change)))
15427 (org-call-with-arg 'org-todo 'right)))
15428 ((or (and org-support-shift-select
15429 (not (eq org-support-shift-select 'always))
15430 (org-at-item-bullet-p))
15431 (and (not org-support-shift-select) (org-at-item-p)))
15432 (org-call-with-arg 'org-cycle-list-bullet nil))
15433 ((and (not (eq org-support-shift-select 'always))
15434 (org-at-property-p))
15435 (call-interactively 'org-property-next-allowed-value))
15436 ((org-clocktable-try-shift 'right arg))
15437 (org-support-shift-select
15438 (org-call-for-shift-select 'forward-char))
15439 (t (org-shiftselect-error))))
15441 (defun org-shiftleft (&optional arg)
15442 "Cycle the thing at point or in the current line, depending on context.
15443 Depending on context, this does one of the following:
15445 - switch a timestamp at point one day into the past
15446 - on a headline, switch to the previous TODO keyword.
15447 - on an item, switch entire list to the previous bullet type
15448 - on a property line, switch to the previous allowed value
15449 - on a clocktable definition line, move time block into the past"
15450 (interactive "P")
15451 (cond
15452 ((and org-support-shift-select (org-region-active-p))
15453 (org-call-for-shift-select 'backward-char))
15454 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15455 ((and (not (eq org-support-shift-select 'always))
15456 (org-on-heading-p))
15457 (let ((org-inhibit-logging
15458 (not org-treat-S-cursor-todo-selection-as-state-change))
15459 (org-inhibit-blocking
15460 (not org-treat-S-cursor-todo-selection-as-state-change)))
15461 (org-call-with-arg 'org-todo 'left)))
15462 ((or (and org-support-shift-select
15463 (not (eq org-support-shift-select 'always))
15464 (org-at-item-bullet-p))
15465 (and (not org-support-shift-select) (org-at-item-p)))
15466 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15467 ((and (not (eq org-support-shift-select 'always))
15468 (org-at-property-p))
15469 (call-interactively 'org-property-previous-allowed-value))
15470 ((org-clocktable-try-shift 'left arg))
15471 (org-support-shift-select
15472 (org-call-for-shift-select 'backward-char))
15473 (t (org-shiftselect-error))))
15475 (defun org-shiftcontrolright ()
15476 "Switch to next TODO set."
15477 (interactive)
15478 (cond
15479 ((and org-support-shift-select (org-region-active-p))
15480 (org-call-for-shift-select 'forward-word))
15481 ((and (not (eq org-support-shift-select 'always))
15482 (org-on-heading-p))
15483 (org-call-with-arg 'org-todo 'nextset))
15484 (org-support-shift-select
15485 (org-call-for-shift-select 'forward-word))
15486 (t (org-shiftselect-error))))
15488 (defun org-shiftcontrolleft ()
15489 "Switch to previous TODO set."
15490 (interactive)
15491 (cond
15492 ((and org-support-shift-select (org-region-active-p))
15493 (org-call-for-shift-select 'backward-word))
15494 ((and (not (eq org-support-shift-select 'always))
15495 (org-on-heading-p))
15496 (org-call-with-arg 'org-todo 'previousset))
15497 (org-support-shift-select
15498 (org-call-for-shift-select 'backward-word))
15499 (t (org-shiftselect-error))))
15501 (defun org-ctrl-c-ret ()
15502 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15503 (interactive)
15504 (cond
15505 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15506 (t (call-interactively 'org-insert-heading))))
15508 (defun org-copy-special ()
15509 "Copy region in table or copy current subtree.
15510 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15511 See the individual commands for more information."
15512 (interactive)
15513 (call-interactively
15514 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15516 (defun org-cut-special ()
15517 "Cut region in table or cut current subtree.
15518 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15519 See the individual commands for more information."
15520 (interactive)
15521 (call-interactively
15522 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15524 (defun org-paste-special (arg)
15525 "Paste rectangular region into table, or past subtree relative to level.
15526 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15527 See the individual commands for more information."
15528 (interactive "P")
15529 (if (org-at-table-p)
15530 (org-table-paste-rectangle)
15531 (org-paste-subtree arg)))
15533 (defun org-edit-special ()
15534 "Call a special editor for the stuff at point.
15535 When at a table, call the formula editor with `org-table-edit-formulas'.
15536 When at the first line of an src example, call `org-edit-src-code'.
15537 When in an #+include line, visit the include file. Otherwise call
15538 `ffap' to visit the file at point."
15539 (interactive)
15540 (cond
15541 ((org-at-table-p)
15542 (call-interactively 'org-table-edit-formulas))
15543 ((save-excursion
15544 (beginning-of-line 1)
15545 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15546 (find-file (org-trim (match-string 1))))
15547 ((org-edit-src-code))
15548 ((org-edit-fixed-width-region))
15549 (t (call-interactively 'ffap))))
15552 (defun org-ctrl-c-ctrl-c (&optional arg)
15553 "Set tags in headline, or update according to changed information at point.
15555 This command does many different things, depending on context:
15557 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15558 this is what we do.
15560 - If the cursor is on a statistics cookie, update it.
15562 - If the cursor is in a headline, prompt for tags and insert them
15563 into the current line, aligned to `org-tags-column'. When called
15564 with prefix arg, realign all tags in the current buffer.
15566 - If the cursor is in one of the special #+KEYWORD lines, this
15567 triggers scanning the buffer for these lines and updating the
15568 information.
15570 - If the cursor is inside a table, realign the table. This command
15571 works even if the automatic table editor has been turned off.
15573 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15574 the entire table.
15576 - If the cursor is at a footnote reference or definition, jump to
15577 the corresponding definition or references, respectively.
15579 - If the cursor is a the beginning of a dynamic block, update it.
15581 - If the cursor is inside a table created by the table.el package,
15582 activate that table.
15584 - If the current buffer is a remember buffer, close note and file
15585 it. A prefix argument of 1 files to the default location
15586 without further interaction. A prefix argument of 2 files to
15587 the currently clocking task.
15589 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15590 links in this buffer.
15592 - If the cursor is on a numbered item in a plain list, renumber the
15593 ordered list.
15595 - If the cursor is on a checkbox, toggle it."
15596 (interactive "P")
15597 (let ((org-enable-table-editor t))
15598 (cond
15599 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15600 org-occur-highlights
15601 org-latex-fragment-image-overlays)
15602 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15603 (org-remove-occur-highlights)
15604 (org-remove-latex-fragment-image-overlays)
15605 (message "Temporary highlights/overlays removed from current buffer"))
15606 ((and (local-variable-p 'org-finish-function (current-buffer))
15607 (fboundp org-finish-function))
15608 (funcall org-finish-function))
15609 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15610 ((org-at-property-p)
15611 (call-interactively 'org-property-action))
15612 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15613 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15614 (or (org-on-heading-p) (org-at-item-p)))
15615 (call-interactively 'org-update-statistics-cookies))
15616 ((org-on-heading-p) (call-interactively 'org-set-tags))
15617 ((org-at-table.el-p)
15618 (require 'table)
15619 (beginning-of-line 1)
15620 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15621 (call-interactively 'table-recognize-table))
15622 ((org-at-table-p)
15623 (org-table-maybe-eval-formula)
15624 (if arg
15625 (call-interactively 'org-table-recalculate)
15626 (org-table-maybe-recalculate-line))
15627 (call-interactively 'org-table-align))
15628 ((or (org-footnote-at-reference-p)
15629 (org-footnote-at-definition-p))
15630 (call-interactively 'org-footnote-action))
15631 ((org-at-item-checkbox-p)
15632 (call-interactively 'org-toggle-checkbox))
15633 ((org-at-item-p)
15634 (if arg
15635 (call-interactively 'org-toggle-checkbox)
15636 (call-interactively 'org-maybe-renumber-ordered-list)))
15637 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15638 ;; Dynamic block
15639 (beginning-of-line 1)
15640 (save-excursion (org-update-dblock)))
15641 ((save-excursion
15642 (beginning-of-line 1)
15643 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15644 (cond
15645 ((equal (match-string 1) "TBLFM")
15646 ;; Recalculate the table before this line
15647 (save-excursion
15648 (beginning-of-line 1)
15649 (skip-chars-backward " \r\n\t")
15650 (if (org-at-table-p)
15651 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15653 ; (org-set-regexps-and-options)
15654 ; (org-restart-font-lock)
15655 (let ((org-inhibit-startup t)) (org-mode-restart))
15656 (message "Local setup has been refreshed"))))
15657 ((org-clock-update-time-maybe))
15658 (t (error "C-c C-c can do nothing useful at this location")))))
15660 (defun org-mode-restart ()
15661 "Restart Org-mode, to scan again for special lines.
15662 Also updates the keyword regular expressions."
15663 (interactive)
15664 (org-mode)
15665 (message "Org-mode restarted"))
15667 (defun org-kill-note-or-show-branches ()
15668 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15669 (interactive)
15670 (if (not org-finish-function)
15671 (call-interactively 'show-branches)
15672 (let ((org-note-abort t))
15673 (funcall org-finish-function))))
15675 (defun org-return (&optional indent)
15676 "Goto next table row or insert a newline.
15677 Calls `org-table-next-row' or `newline', depending on context.
15678 See the individual commands for more information."
15679 (interactive)
15680 (cond
15681 ((bobp) (if indent (newline-and-indent) (newline)))
15682 ((org-at-table-p)
15683 (org-table-justify-field-maybe)
15684 (call-interactively 'org-table-next-row))
15685 ((and org-return-follows-link
15686 (eq (get-text-property (point) 'face) 'org-link))
15687 (call-interactively 'org-open-at-point))
15688 ((and (org-at-heading-p)
15689 (looking-at
15690 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15691 (org-show-entry)
15692 (end-of-line 1)
15693 (newline))
15694 (t (if indent (newline-and-indent) (newline)))))
15696 (defun org-return-indent ()
15697 "Goto next table row or insert a newline and indent.
15698 Calls `org-table-next-row' or `newline-and-indent', depending on
15699 context. See the individual commands for more information."
15700 (interactive)
15701 (org-return t))
15703 (defun org-ctrl-c-star ()
15704 "Compute table, or change heading status of lines.
15705 Calls `org-table-recalculate' or `org-toggle-heading',
15706 depending on context."
15707 (interactive)
15708 (cond
15709 ((org-at-table-p)
15710 (call-interactively 'org-table-recalculate))
15712 ;; Convert all lines in region to list items
15713 (call-interactively 'org-toggle-heading))))
15715 (defun org-ctrl-c-minus ()
15716 "Insert separator line in table or modify bullet status of line.
15717 Also turns a plain line or a region of lines into list items.
15718 Calls `org-table-insert-hline', `org-toggle-item', or
15719 `org-cycle-list-bullet', depending on context."
15720 (interactive)
15721 (cond
15722 ((org-at-table-p)
15723 (call-interactively 'org-table-insert-hline))
15724 ((org-region-active-p)
15725 (call-interactively 'org-toggle-item))
15726 ((org-in-item-p)
15727 (call-interactively 'org-cycle-list-bullet))
15729 (call-interactively 'org-toggle-item))))
15731 (defun org-toggle-item ()
15732 "Convert headings or normal lines to items, items to normal lines.
15733 If there is no active region, only the current line is considered.
15735 If the first line in the region is a headline, convert all headlines to items.
15737 If the first line in the region is an item, convert all items to normal lines.
15739 If the first line is normal text, add an item bullet to each line."
15740 (interactive)
15741 (let (l2 l beg end)
15742 (if (org-region-active-p)
15743 (setq beg (region-beginning) end (region-end))
15744 (setq beg (point-at-bol)
15745 end (min (1+ (point-at-eol)) (point-max))))
15746 (save-excursion
15747 (goto-char end)
15748 (setq l2 (org-current-line))
15749 (goto-char beg)
15750 (beginning-of-line 1)
15751 (setq l (1- (org-current-line)))
15752 (if (org-at-item-p)
15753 ;; We already have items, de-itemize
15754 (while (< (setq l (1+ l)) l2)
15755 (when (org-at-item-p)
15756 (goto-char (match-beginning 2))
15757 (delete-region (match-beginning 2) (match-end 2))
15758 (and (looking-at "[ \t]+") (replace-match "")))
15759 (beginning-of-line 2))
15760 (if (org-on-heading-p)
15761 ;; Headings, convert to items
15762 (while (< (setq l (1+ l)) l2)
15763 (if (looking-at org-outline-regexp)
15764 (replace-match "- " t t))
15765 (beginning-of-line 2))
15766 ;; normal lines, turn them into items
15767 (while (< (setq l (1+ l)) l2)
15768 (unless (org-at-item-p)
15769 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15770 (replace-match "\\1- \\2")))
15771 (beginning-of-line 2)))))))
15773 (defun org-toggle-heading (&optional nstars)
15774 "Convert headings to normal text, or items or text to headings.
15775 If there is no active region, only the current line is considered.
15777 If the first line is a heading, remove the stars from all headlines
15778 in the region.
15780 If the first line is a plain list item, turn all plain list items
15781 into headings.
15783 If the first line is a normal line, turn each and every line in the
15784 region into a heading.
15786 When converting a line into a heading, the number of stars is chosen
15787 such that the lines become children of the current entry. However,
15788 when a prefix argument is given, its value determines the number of
15789 stars to add."
15790 (interactive "P")
15791 (let (l2 l itemp beg end)
15792 (if (org-region-active-p)
15793 (setq beg (region-beginning) end (region-end))
15794 (setq beg (point-at-bol)
15795 end (min (1+ (point-at-eol)) (point-max))))
15796 (save-excursion
15797 (goto-char end)
15798 (setq l2 (org-current-line))
15799 (goto-char beg)
15800 (beginning-of-line 1)
15801 (setq l (1- (org-current-line)))
15802 (if (org-on-heading-p)
15803 ;; We already have headlines, de-star them
15804 (while (< (setq l (1+ l)) l2)
15805 (when (org-on-heading-p t)
15806 (and (looking-at outline-regexp) (replace-match "")))
15807 (beginning-of-line 2))
15808 (setq itemp (org-at-item-p))
15809 (let* ((stars
15810 (if nstars
15811 (make-string (prefix-numeric-value current-prefix-arg)
15813 (save-excursion
15814 (if (re-search-backward org-complex-heading-regexp nil t)
15815 (match-string 1) ""))))
15816 (add-stars (cond (nstars "")
15817 ((equal stars "") "*")
15818 (org-odd-levels-only "**")
15819 (t "*")))
15820 (rpl (concat stars add-stars " ")))
15821 (while (< (setq l (1+ l)) l2)
15822 (if itemp
15823 (and (org-at-item-p) (replace-match rpl t t))
15824 (unless (org-on-heading-p)
15825 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15826 (replace-match (concat rpl (match-string 2))))))
15827 (beginning-of-line 2)))))))
15829 (defun org-meta-return (&optional arg)
15830 "Insert a new heading or wrap a region in a table.
15831 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15832 See the individual commands for more information."
15833 (interactive "P")
15834 (cond
15835 ((run-hook-with-args-until-success 'org-metareturn-hook))
15836 ((org-at-table-p)
15837 (call-interactively 'org-table-wrap-region))
15838 (t (call-interactively 'org-insert-heading))))
15840 ;;; Menu entries
15842 ;; Define the Org-mode menus
15843 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15844 '("Tbl"
15845 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15846 ["Next Field" org-cycle (org-at-table-p)]
15847 ["Previous Field" org-shifttab (org-at-table-p)]
15848 ["Next Row" org-return (org-at-table-p)]
15849 "--"
15850 ["Blank Field" org-table-blank-field (org-at-table-p)]
15851 ["Edit Field" org-table-edit-field (org-at-table-p)]
15852 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15853 "--"
15854 ("Column"
15855 ["Move Column Left" org-metaleft (org-at-table-p)]
15856 ["Move Column Right" org-metaright (org-at-table-p)]
15857 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15858 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15859 ("Row"
15860 ["Move Row Up" org-metaup (org-at-table-p)]
15861 ["Move Row Down" org-metadown (org-at-table-p)]
15862 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15863 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15864 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15865 "--"
15866 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15867 ("Rectangle"
15868 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15869 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15870 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15871 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15872 "--"
15873 ("Calculate"
15874 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15875 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15876 ["Edit Formulas" org-edit-special (org-at-table-p)]
15877 "--"
15878 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15879 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15880 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15881 "--"
15882 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15883 "--"
15884 ["Sum Column/Rectangle" org-table-sum
15885 (or (org-at-table-p) (org-region-active-p))]
15886 ["Which Column?" org-table-current-column (org-at-table-p)])
15887 ["Debug Formulas"
15888 org-table-toggle-formula-debugger
15889 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15890 ["Show Col/Row Numbers"
15891 org-table-toggle-coordinate-overlays
15892 :style toggle
15893 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15894 "--"
15895 ["Create" org-table-create (and (not (org-at-table-p))
15896 org-enable-table-editor)]
15897 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15898 ["Import from File" org-table-import (not (org-at-table-p))]
15899 ["Export to File" org-table-export (org-at-table-p)]
15900 "--"
15901 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15903 (easy-menu-define org-org-menu org-mode-map "Org menu"
15904 '("Org"
15905 ("Show/Hide"
15906 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15907 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15908 ["Sparse Tree..." org-sparse-tree t]
15909 ["Reveal Context" org-reveal t]
15910 ["Show All" show-all t]
15911 "--"
15912 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15913 "--"
15914 ["New Heading" org-insert-heading t]
15915 ("Navigate Headings"
15916 ["Up" outline-up-heading t]
15917 ["Next" outline-next-visible-heading t]
15918 ["Previous" outline-previous-visible-heading t]
15919 ["Next Same Level" outline-forward-same-level t]
15920 ["Previous Same Level" outline-backward-same-level t]
15921 "--"
15922 ["Jump" org-goto t])
15923 ("Edit Structure"
15924 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15925 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15926 "--"
15927 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15928 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15929 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15930 "--"
15931 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15932 "--"
15933 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15934 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15935 ["Demote Heading" org-metaright (not (org-at-table-p))]
15936 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15937 "--"
15938 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15939 "--"
15940 ["Convert to odd levels" org-convert-to-odd-levels t]
15941 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15942 ("Editing"
15943 ["Emphasis..." org-emphasize t]
15944 ["Edit Source Example" org-edit-special t]
15945 "--"
15946 ["Footnote new/jump" org-footnote-action t]
15947 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15948 ("Archive"
15949 ["Archive (default method)" org-archive-subtree-default t]
15950 "--"
15951 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
15952 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15953 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
15955 "--"
15956 ("Hyperlinks"
15957 ["Store Link (Global)" org-store-link t]
15958 ["Find existing link to here" org-occur-link-in-agenda-files t]
15959 ["Insert Link" org-insert-link t]
15960 ["Follow Link" org-open-at-point t]
15961 "--"
15962 ["Next link" org-next-link t]
15963 ["Previous link" org-previous-link t]
15964 "--"
15965 ["Descriptive Links"
15966 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15967 :style radio
15968 :selected (member '(org-link) buffer-invisibility-spec)]
15969 ["Literal Links"
15970 (progn
15971 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15972 :style radio
15973 :selected (not (member '(org-link) buffer-invisibility-spec))])
15974 "--"
15975 ("TODO Lists"
15976 ["TODO/DONE/-" org-todo t]
15977 ("Select keyword"
15978 ["Next keyword" org-shiftright (org-on-heading-p)]
15979 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15980 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15981 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15982 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15983 ["Show TODO Tree" org-show-todo-tree t]
15984 ["Global TODO list" org-todo-list t]
15985 "--"
15986 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15987 :selected org-enforce-todo-dependencies :style toggle :active t]
15988 "Settings for tree at point"
15989 ["Do Children sequentially" org-toggle-ordered-property :style radio
15990 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15991 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15992 ["Do Children parallel" org-toggle-ordered-property :style radio
15993 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15994 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15995 "--"
15996 ["Set Priority" org-priority t]
15997 ["Priority Up" org-shiftup t]
15998 ["Priority Down" org-shiftdown t]
15999 "--"
16000 ["Get news from all feeds" org-feed-update-all t]
16001 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16002 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16003 ("TAGS and Properties"
16004 ["Set Tags" org-set-tags-command t]
16005 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16006 "--"
16007 ["Set property" org-set-property t]
16008 ["Column view of properties" org-columns t]
16009 ["Insert Column View DBlock" org-insert-columns-dblock t])
16010 ("Dates and Scheduling"
16011 ["Timestamp" org-time-stamp t]
16012 ["Timestamp (inactive)" org-time-stamp-inactive t]
16013 ("Change Date"
16014 ["1 Day Later" org-shiftright t]
16015 ["1 Day Earlier" org-shiftleft t]
16016 ["1 ... Later" org-shiftup t]
16017 ["1 ... Earlier" org-shiftdown t])
16018 ["Compute Time Range" org-evaluate-time-range t]
16019 ["Schedule Item" org-schedule t]
16020 ["Deadline" org-deadline t]
16021 "--"
16022 ["Custom time format" org-toggle-time-stamp-overlays
16023 :style radio :selected org-display-custom-times]
16024 "--"
16025 ["Goto Calendar" org-goto-calendar t]
16026 ["Date from Calendar" org-date-from-calendar t]
16027 "--"
16028 ["Start/Restart Timer" org-timer-start t]
16029 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16030 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16031 ["Insert Timer String" org-timer t]
16032 ["Insert Timer Item" org-timer-item t])
16033 ("Logging work"
16034 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16035 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16036 ["Clock out" org-clock-out t]
16037 ["Clock cancel" org-clock-cancel t]
16038 "--"
16039 ["Mark as default task" org-clock-mark-default-task t]
16040 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16041 ["Goto running clock" org-clock-goto t]
16042 "--"
16043 ["Display times" org-clock-display t]
16044 ["Create clock table" org-clock-report t]
16045 "--"
16046 ["Record DONE time"
16047 (progn (setq org-log-done (not org-log-done))
16048 (message "Switching to %s will %s record a timestamp"
16049 (car org-done-keywords)
16050 (if org-log-done "automatically" "not")))
16051 :style toggle :selected org-log-done])
16052 "--"
16053 ["Agenda Command..." org-agenda t]
16054 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16055 ("File List for Agenda")
16056 ("Special views current file"
16057 ["TODO Tree" org-show-todo-tree t]
16058 ["Check Deadlines" org-check-deadlines t]
16059 ["Timeline" org-timeline t]
16060 ["Tags/Property tree" org-match-sparse-tree t])
16061 "--"
16062 ["Export/Publish..." org-export t]
16063 ("LaTeX"
16064 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16065 :selected org-cdlatex-mode]
16066 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16067 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16068 ["Modify math symbol" org-cdlatex-math-modify
16069 (org-inside-LaTeX-fragment-p)]
16070 ["Insert citation" org-reftex-citation t]
16071 "--"
16072 ["Export LaTeX fragments as images"
16073 (if (featurep 'org-exp)
16074 (setq org-export-with-LaTeX-fragments
16075 (not org-export-with-LaTeX-fragments))
16076 (require 'org-exp))
16077 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16078 org-export-with-LaTeX-fragments)])
16079 "--"
16080 ("MobileOrg"
16081 ["Push Files and Views" org-mobile-push t]
16082 ["Get Captured and Flagged" org-mobile-pull t]
16083 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16084 "--"
16085 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16086 "--"
16087 ("Documentation"
16088 ["Show Version" org-version t]
16089 ["Info Documentation" org-info t])
16090 ("Customize"
16091 ["Browse Org Group" org-customize t]
16092 "--"
16093 ["Expand This Menu" org-create-customize-menu
16094 (fboundp 'customize-menu-create)])
16095 ["Send bug report" org-submit-bug-report t]
16096 "--"
16097 ("Refresh/Reload"
16098 ["Refresh setup current buffer" org-mode-restart t]
16099 ["Reload Org (after update)" org-reload t]
16100 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16103 (defun org-info (&optional node)
16104 "Read documentation for Org-mode in the info system.
16105 With optional NODE, go directly to that node."
16106 (interactive)
16107 (info (format "(org)%s" (or node ""))))
16109 ;;;###autoload
16110 (defun org-submit-bug-report ()
16111 "Submit a bug report on Org-mode via mail.
16113 Don't hesitate to report any problems or inaccurate documentation.
16115 If you don't have setup sending mail from (X)Emacs, please copy the
16116 output buffer into your mail program, as it gives us important
16117 information about your Org-mode version and configuration."
16118 (interactive)
16119 (require 'reporter)
16120 (org-load-modules-maybe)
16121 (org-require-autoloaded-modules)
16122 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16123 (reporter-submit-bug-report
16124 "emacs-orgmode@gnu.org"
16125 (org-version)
16126 (let (list)
16127 (save-window-excursion
16128 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16129 (delete-other-windows)
16130 (erase-buffer)
16131 (insert "You are about to submit a bug report to the Org-mode mailing list.
16133 We would like to add your full Org-mode and Outline configuration to the
16134 bug report. This greatly simplifies the work of the maintainer and
16135 other experts on the mailing list.
16137 HOWEVER, some variables you have customized may contain private
16138 information. The names of customers, colleagues, or friends, might
16139 appear in the form of file names, tags, todo states, or search strings.
16140 If you answer yes to the prompt, you might want to check and remove
16141 such private information before sending the email.")
16142 (add-text-properties (point-min) (point-max) '(face org-warning))
16143 (when (yes-or-no-p "Include your Org-mode configuration ")
16144 (mapatoms
16145 (lambda (v)
16146 (and (boundp v)
16147 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16148 (or (and (symbol-value v)
16149 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16150 (and
16151 (get v 'custom-type) (get v 'standard-value)
16152 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16153 (push v list)))))
16154 (kill-buffer (get-buffer "*Warn about privacy*"))
16155 list))
16156 nil nil
16157 "Remember to cover the basics, that is, what you expected to happen and
16158 what in fact did happen. You don't know how to make a good report? See
16160 http://orgmode.org/manual/Feedback.html#Feedback
16162 Your bug report will be posted to the Org-mode mailing list.
16163 ------------------------------------------------------------------------")
16164 (save-excursion
16165 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16166 (replace-match "\\1Bug: \\3 [\\2]")))))
16169 (defun org-install-agenda-files-menu ()
16170 (let ((bl (buffer-list)))
16171 (save-excursion
16172 (while bl
16173 (set-buffer (pop bl))
16174 (if (org-mode-p) (setq bl nil)))
16175 (when (org-mode-p)
16176 (easy-menu-change
16177 '("Org") "File List for Agenda"
16178 (append
16179 (list
16180 ["Edit File List" (org-edit-agenda-file-list) t]
16181 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16182 ["Remove Current File from List" org-remove-file t]
16183 ["Cycle through agenda files" org-cycle-agenda-files t]
16184 ["Occur in all agenda files" org-occur-in-agenda-files t]
16185 "--")
16186 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16188 ;;;; Documentation
16190 ;;;###autoload
16191 (defun org-require-autoloaded-modules ()
16192 (interactive)
16193 (mapc 'require
16194 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16195 org-docbook org-exp org-html org-icalendar
16196 org-id org-latex
16197 org-publish org-remember org-table
16198 org-timer org-xoxo)))
16200 ;;;###autoload
16201 (defun org-reload (&optional uncompiled)
16202 "Reload all org lisp files.
16203 With prefix arg UNCOMPILED, load the uncompiled versions."
16204 (interactive "P")
16205 (require 'find-func)
16206 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16207 (dir-org (file-name-directory (org-find-library-name "org")))
16208 (dir-org-contrib (ignore-errors
16209 (file-name-directory
16210 (org-find-library-name "org-contribdir"))))
16211 (files
16212 (append (directory-files dir-org t file-re)
16213 (and dir-org-contrib
16214 (directory-files dir-org-contrib t file-re))))
16215 (remove-re (concat (if (featurep 'xemacs)
16216 "org-colview" "org-colview-xemacs")
16217 "\\'")))
16218 (setq files (mapcar 'file-name-sans-extension files))
16219 (setq files (mapcar
16220 (lambda (x) (if (string-match remove-re x) nil x))
16221 files))
16222 (setq files (delq nil files))
16223 (mapc
16224 (lambda (f)
16225 (when (featurep (intern (file-name-nondirectory f)))
16226 (if (and (not uncompiled)
16227 (file-exists-p (concat f ".elc")))
16228 (load (concat f ".elc") nil nil t)
16229 (load (concat f ".el") nil nil t))))
16230 files))
16231 (org-version))
16233 ;;;###autoload
16234 (defun org-customize ()
16235 "Call the customize function with org as argument."
16236 (interactive)
16237 (org-load-modules-maybe)
16238 (org-require-autoloaded-modules)
16239 (customize-browse 'org))
16241 (defun org-create-customize-menu ()
16242 "Create a full customization menu for Org-mode, insert it into the menu."
16243 (interactive)
16244 (org-load-modules-maybe)
16245 (org-require-autoloaded-modules)
16246 (if (fboundp 'customize-menu-create)
16247 (progn
16248 (easy-menu-change
16249 '("Org") "Customize"
16250 `(["Browse Org group" org-customize t]
16251 "--"
16252 ,(customize-menu-create 'org)
16253 ["Set" Custom-set t]
16254 ["Save" Custom-save t]
16255 ["Reset to Current" Custom-reset-current t]
16256 ["Reset to Saved" Custom-reset-saved t]
16257 ["Reset to Standard Settings" Custom-reset-standard t]))
16258 (message "\"Org\"-menu now contains full customization menu"))
16259 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16261 ;;;; Miscellaneous stuff
16263 ;;; Generally useful functions
16265 (defun org-get-at-bol (property)
16266 "Get text property PROPERTY at beginning of line."
16267 (get-text-property (point-at-bol) property))
16269 (defun org-find-text-property-in-string (prop s)
16270 "Return the first non-nil value of property PROP in string S."
16271 (or (get-text-property 0 prop s)
16272 (get-text-property (or (next-single-property-change 0 prop s) 0)
16273 prop s)))
16275 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16276 "Display the given MESSAGE as a warning."
16277 (if (fboundp 'display-warning)
16278 (display-warning 'org message
16279 (if (featurep 'xemacs)
16280 'warning
16281 :warning))
16282 (let ((buf (get-buffer-create "*Org warnings*")))
16283 (with-current-buffer buf
16284 (goto-char (point-max))
16285 (insert "Warning (Org): " message)
16286 (unless (bolp)
16287 (newline)))
16288 (display-buffer buf)
16289 (sit-for 0))))
16291 (defun org-in-commented-line ()
16292 "Is point in a line starting with `#'?"
16293 (equal (char-after (point-at-bol)) ?#))
16295 (defun org-in-verbatim-emphasis ()
16296 (save-match-data
16297 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16299 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16300 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16301 (if (and marker (marker-buffer marker)
16302 (buffer-live-p (marker-buffer marker)))
16303 (progn
16304 (switch-to-buffer (marker-buffer marker))
16305 (if (or (> marker (point-max)) (< marker (point-min)))
16306 (widen))
16307 (goto-char marker)
16308 (org-show-context 'org-goto))
16309 (if bookmark
16310 (bookmark-jump bookmark)
16311 (error "Cannot find location"))))
16313 (defun org-quote-csv-field (s)
16314 "Quote field for inclusion in CSV material."
16315 (if (string-match "[\",]" s)
16316 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16319 (defun org-plist-delete (plist property)
16320 "Delete PROPERTY from PLIST.
16321 This is in contrast to merely setting it to 0."
16322 (let (p)
16323 (while plist
16324 (if (not (eq property (car plist)))
16325 (setq p (plist-put p (car plist) (nth 1 plist))))
16326 (setq plist (cddr plist)))
16329 (defun org-force-self-insert (N)
16330 "Needed to enforce self-insert under remapping."
16331 (interactive "p")
16332 (self-insert-command N))
16334 (defun org-string-width (s)
16335 "Compute width of string, ignoring invisible characters.
16336 This ignores character with invisibility property `org-link', and also
16337 characters with property `org-cwidth', because these will become invisible
16338 upon the next fontification round."
16339 (let (b l)
16340 (when (or (eq t buffer-invisibility-spec)
16341 (assq 'org-link buffer-invisibility-spec))
16342 (while (setq b (text-property-any 0 (length s)
16343 'invisible 'org-link s))
16344 (setq s (concat (substring s 0 b)
16345 (substring s (or (next-single-property-change
16346 b 'invisible s) (length s)))))))
16347 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16348 (setq s (concat (substring s 0 b)
16349 (substring s (or (next-single-property-change
16350 b 'org-cwidth s) (length s))))))
16351 (setq l (string-width s) b -1)
16352 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16353 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16356 (defun org-get-indentation (&optional line)
16357 "Get the indentation of the current line, interpreting tabs.
16358 When LINE is given, assume it represents a line and compute its indentation."
16359 (if line
16360 (if (string-match "^ *" (org-remove-tabs line))
16361 (match-end 0))
16362 (save-excursion
16363 (beginning-of-line 1)
16364 (skip-chars-forward " \t")
16365 (current-column))))
16367 (defun org-remove-tabs (s &optional width)
16368 "Replace tabulators in S with spaces.
16369 Assumes that s is a single line, starting in column 0."
16370 (setq width (or width tab-width))
16371 (while (string-match "\t" s)
16372 (setq s (replace-match
16373 (make-string
16374 (- (* width (/ (+ (match-beginning 0) width) width))
16375 (match-beginning 0)) ?\ )
16376 t t s)))
16379 (defun org-fix-indentation (line ind)
16380 "Fix indentation in LINE.
16381 IND is a cons cell with target and minimum indentation.
16382 If the current indentation in LINE is smaller than the minimum,
16383 leave it alone. If it is larger than ind, set it to the target."
16384 (let* ((l (org-remove-tabs line))
16385 (i (org-get-indentation l))
16386 (i1 (car ind)) (i2 (cdr ind)))
16387 (if (>= i i2) (setq l (substring line i2)))
16388 (if (> i1 0)
16389 (concat (make-string i1 ?\ ) l)
16390 l)))
16392 (defun org-remove-indentation (code &optional n)
16393 "Remove the maximum common indentation from the lines in CODE.
16394 N may optionally be the number of spaces to remove."
16395 (with-temp-buffer
16396 (insert code)
16397 (org-do-remove-indentation n)
16398 (buffer-string)))
16400 (defun org-do-remove-indentation (&optional n)
16401 "Remove the maximum common indentation from the buffer."
16402 (untabify (point-min) (point-max))
16403 (let ((min 10000) re)
16404 (if n
16405 (setq min n)
16406 (goto-char (point-min))
16407 (while (re-search-forward "^ *[^ \n]" nil t)
16408 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16409 (unless (or (= min 0) (= min 10000))
16410 (setq re (format "^ \\{%d\\}" min))
16411 (goto-char (point-min))
16412 (while (re-search-forward re nil t)
16413 (replace-match "")
16414 (end-of-line 1))
16415 min)))
16417 (defun org-fill-template (template alist)
16418 "Find each %key of ALIST in TEMPLATE and replace it."
16419 (let (entry key value)
16420 (setq alist (sort (copy-sequence alist)
16421 (lambda (a b) (< (length (car a)) (length (car b))))))
16422 (while (setq entry (pop alist))
16423 (setq template
16424 (replace-regexp-in-string
16425 (concat "%" (regexp-quote (car entry)))
16426 (cdr entry) template t t)))
16427 template))
16429 (defun org-base-buffer (buffer)
16430 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16431 (if (not buffer)
16432 buffer
16433 (or (buffer-base-buffer buffer)
16434 buffer)))
16436 (defun org-trim (s)
16437 "Remove whitespace at beginning and end of string."
16438 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16439 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16442 (defun org-wrap (string &optional width lines)
16443 "Wrap string to either a number of lines, or a width in characters.
16444 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16445 that costs. If there is a word longer than WIDTH, the text is actually
16446 wrapped to the length of that word.
16447 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16448 many lines, whatever width that takes.
16449 The return value is a list of lines, without newlines at the end."
16450 (let* ((words (org-split-string string "[ \t\n]+"))
16451 (maxword (apply 'max (mapcar 'org-string-width words)))
16452 w ll)
16453 (cond (width
16454 (org-do-wrap words (max maxword width)))
16455 (lines
16456 (setq w maxword)
16457 (setq ll (org-do-wrap words maxword))
16458 (if (<= (length ll) lines)
16460 (setq ll words)
16461 (while (> (length ll) lines)
16462 (setq w (1+ w))
16463 (setq ll (org-do-wrap words w)))
16464 ll))
16465 (t (error "Cannot wrap this")))))
16467 (defun org-do-wrap (words width)
16468 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16469 (let (lines line)
16470 (while words
16471 (setq line (pop words))
16472 (while (and words (< (+ (length line) (length (car words))) width))
16473 (setq line (concat line " " (pop words))))
16474 (setq lines (push line lines)))
16475 (nreverse lines)))
16477 (defun org-split-string (string &optional separators)
16478 "Splits STRING into substrings at SEPARATORS.
16479 No empty strings are returned if there are matches at the beginning
16480 and end of string."
16481 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16482 (start 0)
16483 notfirst
16484 (list nil))
16485 (while (and (string-match rexp string
16486 (if (and notfirst
16487 (= start (match-beginning 0))
16488 (< start (length string)))
16489 (1+ start) start))
16490 (< (match-beginning 0) (length string)))
16491 (setq notfirst t)
16492 (or (eq (match-beginning 0) 0)
16493 (and (eq (match-beginning 0) (match-end 0))
16494 (eq (match-beginning 0) start))
16495 (setq list
16496 (cons (substring string start (match-beginning 0))
16497 list)))
16498 (setq start (match-end 0)))
16499 (or (eq start (length string))
16500 (setq list
16501 (cons (substring string start)
16502 list)))
16503 (nreverse list)))
16505 (defun org-quote-vert (s)
16506 "Replace \"|\" with \"\\vert\"."
16507 (while (string-match "|" s)
16508 (setq s (replace-match "\\vert" t t s)))
16511 (defun org-uuidgen-p (s)
16512 "Is S an ID created by UUIDGEN?"
16513 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16515 (defun org-context ()
16516 "Return a list of contexts of the current cursor position.
16517 If several contexts apply, all are returned.
16518 Each context entry is a list with a symbol naming the context, and
16519 two positions indicating start and end of the context. Possible
16520 contexts are:
16522 :headline anywhere in a headline
16523 :headline-stars on the leading stars in a headline
16524 :todo-keyword on a TODO keyword (including DONE) in a headline
16525 :tags on the TAGS in a headline
16526 :priority on the priority cookie in a headline
16527 :item on the first line of a plain list item
16528 :item-bullet on the bullet/number of a plain list item
16529 :checkbox on the checkbox in a plain list item
16530 :table in an org-mode table
16531 :table-special on a special filed in a table
16532 :table-table in a table.el table
16533 :link on a hyperlink
16534 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16535 :target on a <<target>>
16536 :radio-target on a <<<radio-target>>>
16537 :latex-fragment on a LaTeX fragment
16538 :latex-preview on a LaTeX fragment with overlayed preview image
16540 This function expects the position to be visible because it uses font-lock
16541 faces as a help to recognize the following contexts: :table-special, :link,
16542 and :keyword."
16543 (let* ((f (get-text-property (point) 'face))
16544 (faces (if (listp f) f (list f)))
16545 (p (point)) clist o)
16546 ;; First the large context
16547 (cond
16548 ((org-on-heading-p t)
16549 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16550 (when (progn
16551 (beginning-of-line 1)
16552 (looking-at org-todo-line-tags-regexp))
16553 (push (org-point-in-group p 1 :headline-stars) clist)
16554 (push (org-point-in-group p 2 :todo-keyword) clist)
16555 (push (org-point-in-group p 4 :tags) clist))
16556 (goto-char p)
16557 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16558 (if (looking-at "\\[#[A-Z0-9]\\]")
16559 (push (org-point-in-group p 0 :priority) clist)))
16561 ((org-at-item-p)
16562 (push (org-point-in-group p 2 :item-bullet) clist)
16563 (push (list :item (point-at-bol)
16564 (save-excursion (org-end-of-item) (point)))
16565 clist)
16566 (and (org-at-item-checkbox-p)
16567 (push (org-point-in-group p 0 :checkbox) clist)))
16569 ((org-at-table-p)
16570 (push (list :table (org-table-begin) (org-table-end)) clist)
16571 (if (memq 'org-formula faces)
16572 (push (list :table-special
16573 (previous-single-property-change p 'face)
16574 (next-single-property-change p 'face)) clist)))
16575 ((org-at-table-p 'any)
16576 (push (list :table-table) clist)))
16577 (goto-char p)
16579 ;; Now the small context
16580 (cond
16581 ((org-at-timestamp-p)
16582 (push (org-point-in-group p 0 :timestamp) clist))
16583 ((memq 'org-link faces)
16584 (push (list :link
16585 (previous-single-property-change p 'face)
16586 (next-single-property-change p 'face)) clist))
16587 ((memq 'org-special-keyword faces)
16588 (push (list :keyword
16589 (previous-single-property-change p 'face)
16590 (next-single-property-change p 'face)) clist))
16591 ((org-on-target-p)
16592 (push (org-point-in-group p 0 :target) clist)
16593 (goto-char (1- (match-beginning 0)))
16594 (if (looking-at org-radio-target-regexp)
16595 (push (org-point-in-group p 0 :radio-target) clist))
16596 (goto-char p))
16597 ((setq o (car (delq nil
16598 (mapcar
16599 (lambda (x)
16600 (if (memq x org-latex-fragment-image-overlays) x))
16601 (org-overlays-at (point))))))
16602 (push (list :latex-fragment
16603 (org-overlay-start o) (org-overlay-end o)) clist)
16604 (push (list :latex-preview
16605 (org-overlay-start o) (org-overlay-end o)) clist))
16606 ((org-inside-LaTeX-fragment-p)
16607 ;; FIXME: positions wrong.
16608 (push (list :latex-fragment (point) (point)) clist)))
16610 (setq clist (nreverse (delq nil clist)))
16611 clist))
16613 ;; FIXME: Compare with at-regexp-p Do we need both?
16614 (defun org-in-regexp (re &optional nlines visually)
16615 "Check if point is inside a match of regexp.
16616 Normally only the current line is checked, but you can include NLINES extra
16617 lines both before and after point into the search.
16618 If VISUALLY is set, require that the cursor is not after the match but
16619 really on, so that the block visually is on the match."
16620 (catch 'exit
16621 (let ((pos (point))
16622 (eol (point-at-eol (+ 1 (or nlines 0))))
16623 (inc (if visually 1 0)))
16624 (save-excursion
16625 (beginning-of-line (- 1 (or nlines 0)))
16626 (while (re-search-forward re eol t)
16627 (if (and (<= (match-beginning 0) pos)
16628 (>= (+ inc (match-end 0)) pos))
16629 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16631 (defun org-at-regexp-p (regexp)
16632 "Is point inside a match of REGEXP in the current line?"
16633 (catch 'exit
16634 (save-excursion
16635 (let ((pos (point)) (end (point-at-eol)))
16636 (beginning-of-line 1)
16637 (while (re-search-forward regexp end t)
16638 (if (and (<= (match-beginning 0) pos)
16639 (>= (match-end 0) pos))
16640 (throw 'exit t)))
16641 nil))))
16643 (defun org-occur-in-agenda-files (regexp &optional nlines)
16644 "Call `multi-occur' with buffers for all agenda files."
16645 (interactive "sOrg-files matching: \np")
16646 (let* ((files (org-agenda-files))
16647 (tnames (mapcar 'file-truename files))
16648 (extra org-agenda-text-search-extra-files)
16650 (when (eq (car extra) 'agenda-archives)
16651 (setq extra (cdr extra))
16652 (setq files (org-add-archive-files files)))
16653 (while (setq f (pop extra))
16654 (unless (member (file-truename f) tnames)
16655 (add-to-list 'files f 'append)
16656 (add-to-list 'tnames (file-truename f) 'append)))
16657 (multi-occur
16658 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16659 regexp)))
16661 (if (boundp 'occur-mode-find-occurrence-hook)
16662 ;; Emacs 23
16663 (add-hook 'occur-mode-find-occurrence-hook
16664 (lambda ()
16665 (when (org-mode-p)
16666 (org-reveal))))
16667 ;; Emacs 22
16668 (defadvice occur-mode-goto-occurrence
16669 (after org-occur-reveal activate)
16670 (and (org-mode-p) (org-reveal)))
16671 (defadvice occur-mode-goto-occurrence-other-window
16672 (after org-occur-reveal activate)
16673 (and (org-mode-p) (org-reveal)))
16674 (defadvice occur-mode-display-occurrence
16675 (after org-occur-reveal activate)
16676 (when (org-mode-p)
16677 (let ((pos (occur-mode-find-occurrence)))
16678 (with-current-buffer (marker-buffer pos)
16679 (save-excursion
16680 (goto-char pos)
16681 (org-reveal)))))))
16683 (defun org-occur-link-in-agenda-files ()
16684 "Create a link and search for it in the agendas.
16685 The link is not stored in `org-stored-links', it is just created
16686 for the search purpose."
16687 (interactive)
16688 (let ((link (condition-case nil
16689 (org-store-link nil)
16690 (error "Unable to create a link to here"))))
16691 (org-occur-in-agenda-files (regexp-quote link))))
16693 (defun org-uniquify (list)
16694 "Remove duplicate elements from LIST."
16695 (let (res)
16696 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16697 res))
16699 (defun org-delete-all (elts list)
16700 "Remove all elements in ELTS from LIST."
16701 (while elts
16702 (setq list (delete (pop elts) list)))
16703 list)
16705 (defun org-back-over-empty-lines ()
16706 "Move backwards over whitespace, to the beginning of the first empty line.
16707 Returns the number of empty lines passed."
16708 (let ((pos (point)))
16709 (skip-chars-backward " \t\n\r")
16710 (beginning-of-line 2)
16711 (goto-char (min (point) pos))
16712 (count-lines (point) pos)))
16714 (defun org-skip-whitespace ()
16715 (skip-chars-forward " \t\n\r"))
16717 (defun org-point-in-group (point group &optional context)
16718 "Check if POINT is in match-group GROUP.
16719 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16720 match. If the match group does ot exist or point is not inside it,
16721 return nil."
16722 (and (match-beginning group)
16723 (>= point (match-beginning group))
16724 (<= point (match-end group))
16725 (if context
16726 (list context (match-beginning group) (match-end group))
16727 t)))
16729 (defun org-switch-to-buffer-other-window (&rest args)
16730 "Switch to buffer in a second window on the current frame.
16731 In particular, do not allow pop-up frames."
16732 (let (pop-up-frames special-display-buffer-names special-display-regexps
16733 special-display-function)
16734 (apply 'switch-to-buffer-other-window args)))
16736 (defun org-combine-plists (&rest plists)
16737 "Create a single property list from all plists in PLISTS.
16738 The process starts by copying the first list, and then setting properties
16739 from the other lists. Settings in the last list are the most significant
16740 ones and overrule settings in the other lists."
16741 (let ((rtn (copy-sequence (pop plists)))
16742 p v ls)
16743 (while plists
16744 (setq ls (pop plists))
16745 (while ls
16746 (setq p (pop ls) v (pop ls))
16747 (setq rtn (plist-put rtn p v))))
16748 rtn))
16750 (defun org-move-line-down (arg)
16751 "Move the current line down. With prefix argument, move it past ARG lines."
16752 (interactive "p")
16753 (let ((col (current-column))
16754 beg end pos)
16755 (beginning-of-line 1) (setq beg (point))
16756 (beginning-of-line 2) (setq end (point))
16757 (beginning-of-line (+ 1 arg))
16758 (setq pos (move-marker (make-marker) (point)))
16759 (insert (delete-and-extract-region beg end))
16760 (goto-char pos)
16761 (org-move-to-column col)))
16763 (defun org-move-line-up (arg)
16764 "Move the current line up. With prefix argument, move it past ARG lines."
16765 (interactive "p")
16766 (let ((col (current-column))
16767 beg end pos)
16768 (beginning-of-line 1) (setq beg (point))
16769 (beginning-of-line 2) (setq end (point))
16770 (beginning-of-line (- arg))
16771 (setq pos (move-marker (make-marker) (point)))
16772 (insert (delete-and-extract-region beg end))
16773 (goto-char pos)
16774 (org-move-to-column col)))
16776 (defun org-replace-escapes (string table)
16777 "Replace %-escapes in STRING with values in TABLE.
16778 TABLE is an association list with keys like \"%a\" and string values.
16779 The sequences in STRING may contain normal field width and padding information,
16780 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16781 so values can contain further %-escapes if they are define later in TABLE."
16782 (let ((case-fold-search nil)
16783 e re rpl)
16784 (while (setq e (pop table))
16785 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16786 (while (string-match re string)
16787 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16788 (cdr e)))
16789 (setq string (replace-match rpl t t string))))
16790 string))
16793 (defun org-sublist (list start end)
16794 "Return a section of LIST, from START to END.
16795 Counting starts at 1."
16796 (let (rtn (c start))
16797 (setq list (nthcdr (1- start) list))
16798 (while (and list (<= c end))
16799 (push (pop list) rtn)
16800 (setq c (1+ c)))
16801 (nreverse rtn)))
16803 (defun org-find-base-buffer-visiting (file)
16804 "Like `find-buffer-visiting' but always return the base buffer and
16805 not an indirect buffer."
16806 (let ((buf (or (get-file-buffer file)
16807 (find-buffer-visiting file))))
16808 (if buf
16809 (or (buffer-base-buffer buf) buf)
16810 nil)))
16812 (defun org-image-file-name-regexp (&optional extensions)
16813 "Return regexp matching the file names of images.
16814 If EXTENSIONS is given, only match these."
16815 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16816 (image-file-name-regexp)
16817 (let ((image-file-name-extensions
16818 (or extensions
16819 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16820 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16821 (concat "\\."
16822 (regexp-opt (nconc (mapcar 'upcase
16823 image-file-name-extensions)
16824 image-file-name-extensions)
16826 "\\'"))))
16828 (defun org-file-image-p (file &optional extensions)
16829 "Return non-nil if FILE is an image."
16830 (save-match-data
16831 (string-match (org-image-file-name-regexp extensions) file)))
16833 (defun org-get-cursor-date ()
16834 "Return the date at cursor in as a time.
16835 This works in the calendar and in the agenda, anywhere else it just
16836 returns the current time."
16837 (let (date day defd)
16838 (cond
16839 ((eq major-mode 'calendar-mode)
16840 (setq date (calendar-cursor-to-date)
16841 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16842 ((eq major-mode 'org-agenda-mode)
16843 (setq day (get-text-property (point) 'day))
16844 (if day
16845 (setq date (calendar-gregorian-from-absolute day)
16846 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16847 (nth 2 date))))))
16848 (or defd (current-time))))
16850 (defvar org-agenda-action-marker (make-marker)
16851 "Marker pointing to the entry for the next agenda action.")
16853 (defun org-mark-entry-for-agenda-action ()
16854 "Mark the current entry as target of an agenda action.
16855 Agenda actions are actions executed from the agenda with the key `k',
16856 which make use of the date at the cursor."
16857 (interactive)
16858 (move-marker org-agenda-action-marker
16859 (save-excursion (org-back-to-heading t) (point))
16860 (current-buffer))
16861 (message
16862 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16864 ;;; Paragraph filling stuff.
16865 ;; We want this to be just right, so use the full arsenal.
16867 (defun org-indent-line-function ()
16868 "Indent line like previous, but further if previous was headline or item."
16869 (interactive)
16870 (let* ((pos (point))
16871 (itemp (org-at-item-p))
16872 (case-fold-search t)
16873 (org-drawer-regexp (or org-drawer-regexp "\000"))
16874 column bpos bcol tpos tcol bullet btype bullet-type)
16875 ;; Find the previous relevant line
16876 (beginning-of-line 1)
16877 (cond
16878 ((looking-at "#") (setq column 0))
16879 ((looking-at "\\*+ ") (setq column 0))
16880 ((and (looking-at "[ \t]*:END:")
16881 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16882 (save-excursion
16883 (goto-char (1- (match-beginning 1)))
16884 (setq column (current-column))))
16885 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16886 (save-excursion
16887 (re-search-backward
16888 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16889 (setq column (org-get-indentation (match-string 0))))
16891 (beginning-of-line 0)
16892 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16893 (not (looking-at "[ \t]*:END:"))
16894 (not (looking-at org-drawer-regexp)))
16895 (beginning-of-line 0))
16896 (cond
16897 ((looking-at "\\*+[ \t]+")
16898 (if (not org-adapt-indentation)
16899 (setq column 0)
16900 (goto-char (match-end 0))
16901 (setq column (current-column))))
16902 ((looking-at org-drawer-regexp)
16903 (goto-char (1- (match-beginning 1)))
16904 (setq column (current-column)))
16905 ((looking-at "\\([ \t]*\\):END:")
16906 (goto-char (match-end 1))
16907 (setq column (current-column)))
16908 ((org-in-item-p)
16909 (org-beginning-of-item)
16910 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16911 (setq bpos (match-beginning 1) tpos (match-end 0)
16912 bcol (progn (goto-char bpos) (current-column))
16913 tcol (progn (goto-char tpos) (current-column))
16914 bullet (match-string 1)
16915 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16916 (if (> tcol (+ bcol org-description-max-indent))
16917 (setq tcol (+ bcol 5)))
16918 (if (not itemp)
16919 (setq column tcol)
16920 (goto-char pos)
16921 (beginning-of-line 1)
16922 (if (looking-at "\\S-")
16923 (progn
16924 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16925 (setq bullet (match-string 1)
16926 btype (if (string-match "[0-9]" bullet) "n" bullet))
16927 (setq column (if (equal btype bullet-type) bcol tcol)))
16928 (setq column (org-get-indentation)))))
16929 (t (setq column (org-get-indentation))))))
16930 (goto-char pos)
16931 (if (<= (current-column) (current-indentation))
16932 (org-indent-line-to column)
16933 (save-excursion (org-indent-line-to column)))
16934 (setq column (current-column))
16935 (beginning-of-line 1)
16936 (if (looking-at
16937 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16938 (replace-match (concat (match-string 1)
16939 (format org-property-format
16940 (match-string 2) (match-string 3)))
16941 t t))
16942 (org-move-to-column column)))
16944 (defun org-set-autofill-regexps ()
16945 (interactive)
16946 ;; In the paragraph separator we include headlines, because filling
16947 ;; text in a line directly attached to a headline would otherwise
16948 ;; fill the headline as well.
16949 (org-set-local 'comment-start-skip "^#+[ \t]*")
16950 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16951 ;; The paragraph starter includes hand-formatted lists.
16952 (org-set-local
16953 'paragraph-start
16954 (concat
16955 "\f" "\\|"
16956 "[ ]*$" "\\|"
16957 "\\*+ " "\\|"
16958 "[ \t]*#" "\\|"
16959 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16960 "[ \t]*[:|]" "\\|"
16961 "\\$\\$" "\\|"
16962 "\\\\\\(begin\\|end\\|[][]\\)"))
16963 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16964 ;; But only if the user has not turned off tables or fixed-width regions
16965 (org-set-local
16966 'auto-fill-inhibit-regexp
16967 (concat "\\*+ \\|#\\+"
16968 "\\|[ \t]*" org-keyword-time-regexp
16969 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16970 (concat
16971 "\\|[ \t]*["
16972 (if org-enable-table-editor "|" "")
16973 (if org-enable-fixed-width-editor ":" "")
16974 "]"))))
16975 ;; We use our own fill-paragraph function, to make sure that tables
16976 ;; and fixed-width regions are not wrapped. That function will pass
16977 ;; through to `fill-paragraph' when appropriate.
16978 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16979 ; Adaptive filling: To get full control, first make sure that
16980 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16981 (org-set-local 'adaptive-fill-regexp "\000")
16982 (org-set-local 'adaptive-fill-function
16983 'org-adaptive-fill-function)
16984 (org-set-local
16985 'align-mode-rules-list
16986 '((org-in-buffer-settings
16987 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16988 (modes . '(org-mode))))))
16990 (defun org-fill-paragraph (&optional justify)
16991 "Re-align a table, pass through to fill-paragraph if no table."
16992 (let ((table-p (org-at-table-p))
16993 (table.el-p (org-at-table.el-p)))
16994 (cond ((and (equal (char-after (point-at-bol)) ?*)
16995 (save-excursion (goto-char (point-at-bol))
16996 (looking-at outline-regexp)))
16997 t) ; skip headlines
16998 (table.el-p t) ; skip table.el tables
16999 (table-p (org-table-align) t) ; align org-mode tables
17000 (t nil)))) ; call paragraph-fill
17002 ;; For reference, this is the default value of adaptive-fill-regexp
17003 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17005 (defun org-adaptive-fill-function ()
17006 "Return a fill prefix for org-mode files.
17007 In particular, this makes sure hanging paragraphs for hand-formatted lists
17008 work correctly."
17009 (cond ((looking-at "#[ \t]+")
17010 (match-string 0))
17011 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17012 (save-excursion
17013 (if (> (match-end 1) (+ (match-beginning 1)
17014 org-description-max-indent))
17015 (goto-char (+ (match-beginning 1) 5))
17016 (goto-char (match-end 0)))
17017 (make-string (current-column) ?\ )))
17018 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17019 (save-excursion
17020 (goto-char (match-end 0))
17021 (make-string (current-column) ?\ )))
17022 (t nil)))
17024 ;;; Other stuff.
17026 (defun org-toggle-fixed-width-section (arg)
17027 "Toggle the fixed-width export.
17028 If there is no active region, the QUOTE keyword at the current headline is
17029 inserted or removed. When present, it causes the text between this headline
17030 and the next to be exported as fixed-width text, and unmodified.
17031 If there is an active region, this command adds or removes a colon as the
17032 first character of this line. If the first character of a line is a colon,
17033 this line is also exported in fixed-width font."
17034 (interactive "P")
17035 (let* ((cc 0)
17036 (regionp (org-region-active-p))
17037 (beg (if regionp (region-beginning) (point)))
17038 (end (if regionp (region-end)))
17039 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17040 (case-fold-search nil)
17041 (re "[ \t]*\\(: \\)")
17042 off)
17043 (if regionp
17044 (save-excursion
17045 (goto-char beg)
17046 (setq cc (current-column))
17047 (beginning-of-line 1)
17048 (setq off (looking-at re))
17049 (while (> nlines 0)
17050 (setq nlines (1- nlines))
17051 (beginning-of-line 1)
17052 (cond
17053 (arg
17054 (org-move-to-column cc t)
17055 (insert ": \n")
17056 (forward-line -1))
17057 ((and off (looking-at re))
17058 (replace-match "" t t nil 1))
17059 ((not off) (org-move-to-column cc t) (insert ": ")))
17060 (forward-line 1)))
17061 (save-excursion
17062 (org-back-to-heading)
17063 (if (looking-at (concat outline-regexp
17064 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17065 (replace-match "" t t nil 1)
17066 (if (looking-at outline-regexp)
17067 (progn
17068 (goto-char (match-end 0))
17069 (insert org-quote-string " "))))))))
17071 (defun org-reftex-citation ()
17072 "Use reftex-citation to insert a citation into the buffer.
17073 This looks for a line like
17075 #+BIBLIOGRAPHY: foo plain option:-d
17077 and derives from it that foo.bib is the bibliography file relevant
17078 for this document. It then installs the necessary environment for RefTeX
17079 to work in this buffer and calls `reftex-citation' to insert a citation
17080 into the buffer.
17082 Export of such citations to both LaTeX and HTML is handled by the contributed
17083 package org-exp-bibtex by Taru Karttunen."
17084 (interactive)
17085 (let ((reftex-docstruct-symbol 'rds)
17086 (reftex-cite-format "\\cite{%l}")
17087 rds bib)
17088 (save-excursion
17089 (save-restriction
17090 (widen)
17091 (let ((case-fold-search t)
17092 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17093 (if (not (save-excursion
17094 (or (re-search-forward re nil t)
17095 (re-search-backward re nil t))))
17096 (error "No bibliography defined in file")
17097 (setq bib (concat (match-string 1) ".bib")
17098 rds (list (list 'bib bib)))))))
17099 (call-interactively 'reftex-citation)))
17101 ;;;; Functions extending outline functionality
17103 (defun org-beginning-of-line (&optional arg)
17104 "Go to the beginning of the current line. If that is invisible, continue
17105 to a visible line beginning. This makes the function of C-a more intuitive.
17106 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17107 first attempt, and only move to after the tags when the cursor is already
17108 beyond the end of the headline."
17109 (interactive "P")
17110 (let ((pos (point))
17111 (special (if (consp org-special-ctrl-a/e)
17112 (car org-special-ctrl-a/e)
17113 org-special-ctrl-a/e))
17114 refpos)
17115 (if (org-bound-and-true-p line-move-visual)
17116 (beginning-of-visual-line 1)
17117 (beginning-of-line 1))
17118 (if (and arg (fboundp 'move-beginning-of-line))
17119 (call-interactively 'move-beginning-of-line)
17120 (if (bobp)
17122 (backward-char 1)
17123 (if (org-invisible-p)
17124 (while (and (not (bobp)) (org-invisible-p))
17125 (backward-char 1)
17126 (beginning-of-line 1))
17127 (forward-char 1))))
17128 (when special
17129 (cond
17130 ((and (looking-at org-complex-heading-regexp)
17131 (= (char-after (match-end 1)) ?\ ))
17132 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17133 (point-at-eol)))
17134 (goto-char
17135 (if (eq special t)
17136 (cond ((> pos refpos) refpos)
17137 ((= pos (point)) refpos)
17138 (t (point)))
17139 (cond ((> pos (point)) (point))
17140 ((not (eq last-command this-command)) (point))
17141 (t refpos)))))
17142 ((org-at-item-p)
17143 (goto-char
17144 (if (eq special t)
17145 (cond ((> pos (match-end 4)) (match-end 4))
17146 ((= pos (point)) (match-end 4))
17147 (t (point)))
17148 (cond ((> pos (point)) (point))
17149 ((not (eq last-command this-command)) (point))
17150 (t (match-end 4))))))))
17151 (org-no-warnings
17152 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17154 (defun org-end-of-line (&optional arg)
17155 "Go to the end of the line.
17156 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17157 first attempt, and only move to after the tags when the cursor is already
17158 beyond the end of the headline."
17159 (interactive "P")
17160 (let ((special (if (consp org-special-ctrl-a/e)
17161 (cdr org-special-ctrl-a/e)
17162 org-special-ctrl-a/e)))
17163 (if (or (not special)
17164 (not (org-on-heading-p))
17165 arg)
17166 (call-interactively
17167 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17168 ((fboundp 'move-end-of-line) 'move-end-of-line)
17169 (t 'end-of-line)))
17170 (let ((pos (point)))
17171 (beginning-of-line 1)
17172 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17173 (if (eq special t)
17174 (if (or (< pos (match-beginning 1))
17175 (= pos (match-end 0)))
17176 (goto-char (match-beginning 1))
17177 (goto-char (match-end 0)))
17178 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17179 (goto-char (match-end 0))
17180 (goto-char (match-beginning 1))))
17181 (call-interactively (if (fboundp 'move-end-of-line)
17182 'move-end-of-line
17183 'end-of-line)))))
17184 (org-no-warnings
17185 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17187 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17188 (define-key org-mode-map "\C-e" 'org-end-of-line)
17189 (define-key org-mode-map [home] 'org-beginning-of-line)
17190 (define-key org-mode-map [end] 'org-end-of-line)
17192 (defun org-backward-sentence (&optional arg)
17193 "Go to beginning of sentence, or beginning of table field.
17194 This will call `backward-sentence' or `org-table-beginning-of-field',
17195 depending on context."
17196 (interactive "P")
17197 (cond
17198 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17199 (t (call-interactively 'backward-sentence))))
17201 (defun org-forward-sentence (&optional arg)
17202 "Go to end of sentence, or end of table field.
17203 This will call `forward-sentence' or `org-table-end-of-field',
17204 depending on context."
17205 (interactive "P")
17206 (cond
17207 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17208 (t (call-interactively 'forward-sentence))))
17210 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17211 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17213 (defun org-kill-line (&optional arg)
17214 "Kill line, to tags or end of line."
17215 (interactive "P")
17216 (cond
17217 ((or (not org-special-ctrl-k)
17218 (bolp)
17219 (not (org-on-heading-p)))
17220 (call-interactively 'kill-line))
17221 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17222 (kill-region (point) (match-beginning 1))
17223 (org-set-tags nil t))
17224 (t (kill-region (point) (point-at-eol)))))
17226 (define-key org-mode-map "\C-k" 'org-kill-line)
17228 (defun org-yank (&optional arg)
17229 "Yank. If the kill is a subtree, treat it specially.
17230 This command will look at the current kill and check if is a single
17231 subtree, or a series of subtrees[1]. If it passes the test, and if the
17232 cursor is at the beginning of a line or after the stars of a currently
17233 empty headline, then the yank is handled specially. How exactly depends
17234 on the value of the following variables, both set by default.
17236 org-yank-folded-subtrees
17237 When set, the subtree(s) will be folded after insertion, but only
17238 if doing so would now swallow text after the yanked text.
17240 org-yank-adjusted-subtrees
17241 When set, the subtree will be promoted or demoted in order to
17242 fit into the local outline tree structure, which means that the level
17243 will be adjusted so that it becomes the smaller one of the two
17244 *visible* surrounding headings.
17246 Any prefix to this command will cause `yank' to be called directly with
17247 no special treatment. In particular, a simple `C-u' prefix will just
17248 plainly yank the text as it is.
17250 \[1] The test checks if the first non-white line is a heading
17251 and if there are no other headings with fewer stars."
17252 (interactive "P")
17253 (org-yank-generic 'yank arg))
17255 (defun org-yank-generic (command arg)
17256 "Perform some yank-like command.
17258 This function implements the behavior described in the `org-yank'
17259 documentation. However, it has been generalized to work for any
17260 interactive command with similar behavior."
17262 ;; pretend to be command COMMAND
17263 (setq this-command command)
17265 (if arg
17266 (call-interactively command)
17268 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17269 (and (org-kill-is-subtree-p)
17270 (or (bolp)
17271 (and (looking-at "[ \t]*$")
17272 (string-match
17273 "\\`\\*+\\'"
17274 (buffer-substring (point-at-bol) (point)))))))
17275 swallowp)
17276 (cond
17277 ((and subtreep org-yank-folded-subtrees)
17278 (let ((beg (point))
17279 end)
17280 (if (and subtreep org-yank-adjusted-subtrees)
17281 (org-paste-subtree nil nil 'for-yank)
17282 (call-interactively command))
17284 (setq end (point))
17285 (goto-char beg)
17286 (when (and (bolp) subtreep
17287 (not (setq swallowp
17288 (org-yank-folding-would-swallow-text beg end))))
17289 (or (looking-at outline-regexp)
17290 (re-search-forward (concat "^" outline-regexp) end t))
17291 (while (and (< (point) end) (looking-at outline-regexp))
17292 (hide-subtree)
17293 (org-cycle-show-empty-lines 'folded)
17294 (condition-case nil
17295 (outline-forward-same-level 1)
17296 (error (goto-char end)))))
17297 (when swallowp
17298 (message
17299 "Inserted text not folded because that would swallow text"))
17301 (goto-char end)
17302 (skip-chars-forward " \t\n\r")
17303 (beginning-of-line 1)
17304 (push-mark beg 'nomsg)))
17305 ((and subtreep org-yank-adjusted-subtrees)
17306 (let ((beg (point-at-bol)))
17307 (org-paste-subtree nil nil 'for-yank)
17308 (push-mark beg 'nomsg)))
17310 (call-interactively command))))))
17312 (defun org-yank-folding-would-swallow-text (beg end)
17313 "Would hide-subtree at BEG swallow any text after END?"
17314 (let (level)
17315 (save-excursion
17316 (goto-char beg)
17317 (when (or (looking-at outline-regexp)
17318 (re-search-forward (concat "^" outline-regexp) end t))
17319 (setq level (org-outline-level)))
17320 (goto-char end)
17321 (skip-chars-forward " \t\r\n\v\f")
17322 (if (or (eobp)
17323 (and (bolp) (looking-at org-outline-regexp)
17324 (<= (org-outline-level) level)))
17325 nil ; Nothing would be swallowed
17326 t)))) ; something would swallow
17328 (define-key org-mode-map "\C-y" 'org-yank)
17330 (defun org-invisible-p ()
17331 "Check if point is at a character currently not visible."
17332 ;; Early versions of noutline don't have `outline-invisible-p'.
17333 (if (fboundp 'outline-invisible-p)
17334 (outline-invisible-p)
17335 (get-char-property (point) 'invisible)))
17337 (defun org-invisible-p2 ()
17338 "Check if point is at a character currently not visible."
17339 (save-excursion
17340 (if (and (eolp) (not (bobp))) (backward-char 1))
17341 ;; Early versions of noutline don't have `outline-invisible-p'.
17342 (if (fboundp 'outline-invisible-p)
17343 (outline-invisible-p)
17344 (get-char-property (point) 'invisible))))
17346 (defun org-back-to-heading (&optional invisible-ok)
17347 "Call `outline-back-to-heading', but provide a better error message."
17348 (condition-case nil
17349 (outline-back-to-heading invisible-ok)
17350 (error (error "Before first headline at position %d in buffer %s"
17351 (point) (current-buffer)))))
17353 (defun org-before-first-heading-p ()
17354 "Before first heading?"
17355 (save-excursion
17356 (null (re-search-backward "^\\*+ " nil t))))
17358 (defun org-on-heading-p (&optional ignored)
17359 (outline-on-heading-p t))
17360 (defun org-at-heading-p (&optional ignored)
17361 (outline-on-heading-p t))
17363 (defun org-at-heading-or-item-p ()
17364 (or (org-on-heading-p) (org-at-item-p)))
17366 (defun org-on-target-p ()
17367 (or (org-in-regexp org-radio-target-regexp)
17368 (org-in-regexp org-target-regexp)))
17370 (defun org-up-heading-all (arg)
17371 "Move to the heading line of which the present line is a subheading.
17372 This function considers both visible and invisible heading lines.
17373 With argument, move up ARG levels."
17374 (if (fboundp 'outline-up-heading-all)
17375 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17376 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17378 (defun org-up-heading-safe ()
17379 "Move to the heading line of which the present line is a subheading.
17380 This version will not throw an error. It will return the level of the
17381 headline found, or nil if no higher level is found.
17383 Also, this function will be a lot faster than `outline-up-heading',
17384 because it relies on stars being the outline starters. This can really
17385 make a significant difference in outlines with very many siblings."
17386 (let (start-level re)
17387 (org-back-to-heading t)
17388 (setq start-level (funcall outline-level))
17389 (if (equal start-level 1)
17391 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17392 (if (re-search-backward re nil t)
17393 (funcall outline-level)))))
17395 (defun org-first-sibling-p ()
17396 "Is this heading the first child of its parents?"
17397 (interactive)
17398 (let ((re (concat "^" outline-regexp))
17399 level l)
17400 (unless (org-at-heading-p t)
17401 (error "Not at a heading"))
17402 (setq level (funcall outline-level))
17403 (save-excursion
17404 (if (not (re-search-backward re nil t))
17406 (setq l (funcall outline-level))
17407 (< l level)))))
17409 (defun org-goto-sibling (&optional previous)
17410 "Goto the next sibling, even if it is invisible.
17411 When PREVIOUS is set, go to the previous sibling instead. Returns t
17412 when a sibling was found. When none is found, return nil and don't
17413 move point."
17414 (let ((fun (if previous 're-search-backward 're-search-forward))
17415 (pos (point))
17416 (re (concat "^" outline-regexp))
17417 level l)
17418 (when (condition-case nil (org-back-to-heading t) (error nil))
17419 (setq level (funcall outline-level))
17420 (catch 'exit
17421 (or previous (forward-char 1))
17422 (while (funcall fun re nil t)
17423 (setq l (funcall outline-level))
17424 (when (< l level) (goto-char pos) (throw 'exit nil))
17425 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17426 (goto-char pos)
17427 nil))))
17429 (defun org-show-siblings ()
17430 "Show all siblings of the current headline."
17431 (save-excursion
17432 (while (org-goto-sibling) (org-flag-heading nil)))
17433 (save-excursion
17434 (while (org-goto-sibling 'previous)
17435 (org-flag-heading nil))))
17437 (defun org-show-hidden-entry ()
17438 "Show an entry where even the heading is hidden."
17439 (save-excursion
17440 (org-show-entry)))
17442 (defun org-flag-heading (flag &optional entry)
17443 "Flag the current heading. FLAG non-nil means make invisible.
17444 When ENTRY is non-nil, show the entire entry."
17445 (save-excursion
17446 (org-back-to-heading t)
17447 ;; Check if we should show the entire entry
17448 (if entry
17449 (progn
17450 (org-show-entry)
17451 (save-excursion
17452 (and (outline-next-heading)
17453 (org-flag-heading nil))))
17454 (outline-flag-region (max (point-min) (1- (point)))
17455 (save-excursion (outline-end-of-heading) (point))
17456 flag))))
17458 (defun org-get-next-sibling ()
17459 "Move to next heading of the same level, and return point.
17460 If there is no such heading, return nil.
17461 This is like outline-next-sibling, but invisible headings are ok."
17462 (let ((level (funcall outline-level)))
17463 (outline-next-heading)
17464 (while (and (not (eobp)) (> (funcall outline-level) level))
17465 (outline-next-heading))
17466 (if (or (eobp) (< (funcall outline-level) level))
17468 (point))))
17470 (defun org-get-last-sibling ()
17471 "Move to previous heading of the same level, and return point.
17472 If there is no such heading, return nil."
17473 (let ((opoint (point))
17474 (level (funcall outline-level)))
17475 (outline-previous-heading)
17476 (when (and (/= (point) opoint) (outline-on-heading-p t))
17477 (while (and (> (funcall outline-level) level)
17478 (not (bobp)))
17479 (outline-previous-heading))
17480 (if (< (funcall outline-level) level)
17482 (point)))))
17484 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17485 ;; This contains an exact copy of the original function, but it uses
17486 ;; `org-back-to-heading', to make it work also in invisible
17487 ;; trees. And is uses an invisible-OK argument.
17488 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17489 ;; Furthermore, when used inside Org, finding the end of a large subtree
17490 ;; with many children and grandchildren etc, this can be much faster
17491 ;; than the outline version.
17492 (org-back-to-heading invisible-OK)
17493 (let ((first t)
17494 (level (funcall outline-level)))
17495 (if (and (org-mode-p) (< level 1000))
17496 ;; A true heading (not a plain list item), in Org-mode
17497 ;; This means we can easily find the end by looking
17498 ;; only for the right number of stars. Using a regexp to do
17499 ;; this is so much faster than using a Lisp loop.
17500 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17501 (forward-char 1)
17502 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17503 ;; something else, do it the slow way
17504 (while (and (not (eobp))
17505 (or first (> (funcall outline-level) level)))
17506 (setq first nil)
17507 (outline-next-heading)))
17508 (unless to-heading
17509 (if (memq (preceding-char) '(?\n ?\^M))
17510 (progn
17511 ;; Go to end of line before heading
17512 (forward-char -1)
17513 (if (memq (preceding-char) '(?\n ?\^M))
17514 ;; leave blank line before heading
17515 (forward-char -1))))))
17516 (point))
17518 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17519 "Use Org version in org-mode, for dramatic speed-up."
17520 (if (eq major-mode 'org-mode)
17521 (progn
17522 (org-end-of-subtree nil t)
17523 (unless (eobp) (backward-char 1)))
17524 ad-do-it))
17526 (defun org-forward-same-level (arg &optional invisible-ok)
17527 "Move forward to the arg'th subheading at same level as this one.
17528 Stop at the first and last subheadings of a superior heading."
17529 (interactive "p")
17530 (org-back-to-heading invisible-ok)
17531 (org-on-heading-p)
17532 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17533 (re (format "^\\*\\{1,%d\\} " level))
17535 (forward-char 1)
17536 (while (> arg 0)
17537 (while (and (re-search-forward re nil 'move)
17538 (setq l (- (match-end 0) (match-beginning 0) 1))
17539 (= l level)
17540 (not invisible-ok)
17541 (org-invisible-p))
17542 (if (< l level) (setq arg 1)))
17543 (setq arg (1- arg)))
17544 (beginning-of-line 1)))
17546 (defun org-backward-same-level (arg &optional invisible-ok)
17547 "Move backward to the arg'th subheading at same level as this one.
17548 Stop at the first and last subheadings of a superior heading."
17549 (interactive "p")
17550 (org-back-to-heading)
17551 (org-on-heading-p)
17552 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17553 (re (format "^\\*\\{1,%d\\} " level))
17555 (while (> arg 0)
17556 (while (and (re-search-backward re nil 'move)
17557 (setq l (- (match-end 0) (match-beginning 0) 1))
17558 (= l level)
17559 (not invisible-ok)
17560 (org-invisible-p))
17561 (if (< l level) (setq arg 1)))
17562 (setq arg (1- arg)))))
17564 (defun org-show-subtree ()
17565 "Show everything after this heading at deeper levels."
17566 (outline-flag-region
17567 (point)
17568 (save-excursion
17569 (org-end-of-subtree t t))
17570 nil))
17572 (defun org-show-entry ()
17573 "Show the body directly following this heading.
17574 Show the heading too, if it is currently invisible."
17575 (interactive)
17576 (save-excursion
17577 (condition-case nil
17578 (progn
17579 (org-back-to-heading t)
17580 (outline-flag-region
17581 (max (point-min) (1- (point)))
17582 (save-excursion
17583 (if (re-search-forward
17584 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17585 (match-beginning 1)
17586 (point-max)))
17587 nil)
17588 (org-cycle-hide-drawers 'children))
17589 (error nil))))
17591 (defun org-make-options-regexp (kwds &optional extra)
17592 "Make a regular expression for keyword lines."
17593 (concat
17595 "#?[ \t]*\\+\\("
17596 (mapconcat 'regexp-quote kwds "\\|")
17597 (if extra (concat "\\|" extra))
17598 "\\):[ \t]*"
17599 "\\(.*\\)"))
17601 ;; Make isearch reveal the necessary context
17602 (defun org-isearch-end ()
17603 "Reveal context after isearch exits."
17604 (when isearch-success ; only if search was successful
17605 (if (featurep 'xemacs)
17606 ;; Under XEmacs, the hook is run in the correct place,
17607 ;; we directly show the context.
17608 (org-show-context 'isearch)
17609 ;; In Emacs the hook runs *before* restoring the overlays.
17610 ;; So we have to use a one-time post-command-hook to do this.
17611 ;; (Emacs 22 has a special variable, see function `org-mode')
17612 (unless (and (boundp 'isearch-mode-end-hook-quit)
17613 isearch-mode-end-hook-quit)
17614 ;; Only when the isearch was not quitted.
17615 (org-add-hook 'post-command-hook 'org-isearch-post-command
17616 'append 'local)))))
17618 (defun org-isearch-post-command ()
17619 "Remove self from hook, and show context."
17620 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17621 (org-show-context 'isearch))
17624 ;;;; Integration with and fixes for other packages
17626 ;;; Imenu support
17628 (defvar org-imenu-markers nil
17629 "All markers currently used by Imenu.")
17630 (make-variable-buffer-local 'org-imenu-markers)
17632 (defun org-imenu-new-marker (&optional pos)
17633 "Return a new marker for use by Imenu, and remember the marker."
17634 (let ((m (make-marker)))
17635 (move-marker m (or pos (point)))
17636 (push m org-imenu-markers)
17639 (defun org-imenu-get-tree ()
17640 "Produce the index for Imenu."
17641 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17642 (setq org-imenu-markers nil)
17643 (let* ((n org-imenu-depth)
17644 (re (concat "^" outline-regexp))
17645 (subs (make-vector (1+ n) nil))
17646 (last-level 0)
17647 m level head)
17648 (save-excursion
17649 (save-restriction
17650 (widen)
17651 (goto-char (point-max))
17652 (while (re-search-backward re nil t)
17653 (setq level (org-reduced-level (funcall outline-level)))
17654 (when (<= level n)
17655 (looking-at org-complex-heading-regexp)
17656 (setq head (org-link-display-format
17657 (org-match-string-no-properties 4))
17658 m (org-imenu-new-marker))
17659 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17660 (if (>= level last-level)
17661 (push (cons head m) (aref subs level))
17662 (push (cons head (aref subs (1+ level))) (aref subs level))
17663 (loop for i from (1+ level) to n do (aset subs i nil)))
17664 (setq last-level level)))))
17665 (aref subs 1)))
17667 (eval-after-load "imenu"
17668 '(progn
17669 (add-hook 'imenu-after-jump-hook
17670 (lambda ()
17671 (if (eq major-mode 'org-mode)
17672 (org-show-context 'org-goto))))))
17674 (defun org-link-display-format (link)
17675 "Replace a link with either the description, or the link target
17676 if no description is present"
17677 (save-match-data
17678 (if (string-match org-bracket-link-analytic-regexp link)
17679 (replace-match (if (match-end 5)
17680 (match-string 5 link)
17681 (concat (match-string 1 link)
17682 (match-string 3 link)))
17683 nil t link)
17684 link)))
17686 ;; Speedbar support
17688 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17689 "Overlay marking the agenda restriction line in speedbar.")
17690 (org-overlay-put org-speedbar-restriction-lock-overlay
17691 'face 'org-agenda-restriction-lock)
17692 (org-overlay-put org-speedbar-restriction-lock-overlay
17693 'help-echo "Agendas are currently limited to this item.")
17694 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17696 (defun org-speedbar-set-agenda-restriction ()
17697 "Restrict future agenda commands to the location at point in speedbar.
17698 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17699 (interactive)
17700 (require 'org-agenda)
17701 (let (p m tp np dir txt)
17702 (cond
17703 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17704 'org-imenu t))
17705 (setq m (get-text-property p 'org-imenu-marker))
17706 (with-current-buffer (marker-buffer m)
17707 (goto-char m)
17708 (org-agenda-set-restriction-lock 'subtree)))
17709 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17710 'speedbar-function 'speedbar-find-file))
17711 (setq tp (previous-single-property-change
17712 (1+ p) 'speedbar-function)
17713 np (next-single-property-change
17714 tp 'speedbar-function)
17715 dir (speedbar-line-directory)
17716 txt (buffer-substring-no-properties (or tp (point-min))
17717 (or np (point-max))))
17718 (with-current-buffer (find-file-noselect
17719 (let ((default-directory dir))
17720 (expand-file-name txt)))
17721 (unless (org-mode-p)
17722 (error "Cannot restrict to non-Org-mode file"))
17723 (org-agenda-set-restriction-lock 'file)))
17724 (t (error "Don't know how to restrict Org-mode's agenda")))
17725 (org-move-overlay org-speedbar-restriction-lock-overlay
17726 (point-at-bol) (point-at-eol))
17727 (setq current-prefix-arg nil)
17728 (org-agenda-maybe-redo)))
17730 (eval-after-load "speedbar"
17731 '(progn
17732 (speedbar-add-supported-extension ".org")
17733 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17734 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17735 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17736 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17737 (add-hook 'speedbar-visiting-tag-hook
17738 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17741 ;;; Fixes and Hacks for problems with other packages
17743 ;; Make flyspell not check words in links, to not mess up our keymap
17744 (defun org-mode-flyspell-verify ()
17745 "Don't let flyspell put overlays at active buttons."
17746 (and (not (get-text-property (point) 'keymap))
17747 (not (get-text-property (point) 'org-no-flyspell))))
17749 (defun org-remove-flyspell-overlays-in (beg end)
17750 "Remove flyspell overlays in region."
17751 (and (org-bound-and-true-p flyspell-mode)
17752 (fboundp 'flyspell-delete-region-overlays)
17753 (flyspell-delete-region-overlays beg end))
17754 (add-text-properties beg end '(org-no-flyspell t)))
17756 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17757 (eval-after-load "bookmark"
17758 '(if (boundp 'bookmark-after-jump-hook)
17759 ;; We can use the hook
17760 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17761 ;; Hook not available, use advice
17762 (defadvice bookmark-jump (after org-make-visible activate)
17763 "Make the position visible."
17764 (org-bookmark-jump-unhide))))
17766 ;; Make sure saveplace shows the location if it was hidden
17767 (eval-after-load "saveplace"
17768 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17769 "Make the position visible."
17770 (org-bookmark-jump-unhide)))
17772 ;; Make sure ecb shows the location if it was hidden
17773 (eval-after-load "ecb"
17774 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17775 "Make hierarchy visible when jumping into location from ECB tree buffer."
17776 (if (eq major-mode 'org-mode)
17777 (org-show-context))))
17779 (defun org-bookmark-jump-unhide ()
17780 "Unhide the current position, to show the bookmark location."
17781 (and (org-mode-p)
17782 (or (org-invisible-p)
17783 (save-excursion (goto-char (max (point-min) (1- (point))))
17784 (org-invisible-p)))
17785 (org-show-context 'bookmark-jump)))
17787 ;; Make session.el ignore our circular variable
17788 (eval-after-load "session"
17789 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17791 ;;;; Experimental code
17793 (defun org-closed-in-range ()
17794 "Sparse tree of items closed in a certain time range.
17795 Still experimental, may disappear in the future."
17796 (interactive)
17797 ;; Get the time interval from the user.
17798 (let* ((time1 (org-float-time
17799 (org-read-date nil 'to-time nil "Starting date: ")))
17800 (time2 (org-float-time
17801 (org-read-date nil 'to-time nil "End date:")))
17802 ;; callback function
17803 (callback (lambda ()
17804 (let ((time
17805 (org-float-time
17806 (apply 'encode-time
17807 (org-parse-time-string
17808 (match-string 1))))))
17809 ;; check if time in interval
17810 (and (>= time time1) (<= time time2))))))
17811 ;; make tree, check each match with the callback
17812 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17814 ;;;; Finish up
17816 (provide 'org)
17818 (run-hooks 'org-load-hook)
17820 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17822 ;;; org.el ends here