Merge commit 'bernt/typos'
[org-mode/org-tableheadings.git] / lisp / org.el
blobed32b94b096651877ac79ac5c8130e8ea29b1182
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.32trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.32trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let* ((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 :group 'org-structure
599 :type 'boolean)
601 (defcustom org-speed-commands-user nil
602 "Alist of additional speed commands.
603 This list will be checked before `org-speed-commands-default'
604 when the variable `org-use-speed-commands' is non-nil
605 and when the cursor is at the beginning of a headline.
606 The car if each entry is a string with a single letter, which must
607 be assigned to `self-insert-command' in the global map.
608 The cdr is either a command to be called interactively, a function
609 to be called, or a form to be evaluated."
610 :group 'org-structure
611 :type '(repeat
612 (cons
613 (string "Command letter")
614 (choice
615 (function)
616 (sexp)))))
618 (defgroup org-cycle nil
619 "Options concerning visibility cycling in Org-mode."
620 :tag "Org Cycle"
621 :group 'org-structure)
623 (defcustom org-cycle-skip-children-state-if-no-children t
624 "Non-nil means, skip CHILDREN state in entries that don't have any."
625 :group 'org-cycle
626 :type 'boolean)
628 (defcustom org-cycle-max-level nil
629 "Maximum level which should still be subject to visibility cycling.
630 Levels higher than this will, for cycling, be treated as text, not a headline.
631 When `org-odd-levels-only' is set, a value of N in this variable actually
632 means 2N-1 stars as the limiting headline.
633 When nil, cycle all levels.
634 Note that the limiting level of cycling is also influenced by
635 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
636 `org-inlinetask-min-level' is, cycling will be limited to levels one less
637 than its value."
638 :group 'org-cycle
639 :type '(choice
640 (const :tag "No limit" nil)
641 (integer :tag "Maximum level")))
643 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
644 "Names of drawers. Drawers are not opened by cycling on the headline above.
645 Drawers only open with a TAB on the drawer line itself. A drawer looks like
646 this:
647 :DRAWERNAME:
648 .....
649 :END:
650 The drawer \"PROPERTIES\" is special for capturing properties through
651 the property API.
653 Drawers can be defined on the per-file basis with a line like:
655 #+DRAWERS: HIDDEN STATE PROPERTIES"
656 :group 'org-structure
657 :group 'org-cycle
658 :type '(repeat (string :tag "Drawer Name")))
660 (defcustom org-hide-block-startup nil
661 "Non-nil means, , entering Org-mode will fold all blocks.
662 This can also be set in on a per-file basis with
664 #+STARTUP: hideblocks
665 #+STARTUP: showblocks"
666 :group 'org-startup
667 :group 'org-cycle
668 :type 'boolean)
670 (defcustom org-cycle-global-at-bob nil
671 "Cycle globally if cursor is at beginning of buffer and not at a headline.
672 This makes it possible to do global cycling without having to use S-TAB or
673 C-u TAB. For this special case to work, the first line of the buffer
674 must not be a headline - it may be empty or some other text. When used in
675 this way, `org-cycle-hook' is disables temporarily, to make sure the
676 cursor stays at the beginning of the buffer.
677 When this option is nil, don't do anything special at the beginning
678 of the buffer."
679 :group 'org-cycle
680 :type 'boolean)
682 (defcustom org-cycle-level-after-item/entry-creation t
683 "Non-nil means, cycle entry level or item indentation in new empty entries.
685 When the cursor is at the end of an empty headline, i.e with only stars
686 and maybe a TODO keyword, TAB will then switch the entry to become a child,
687 and then all possible anchestor states, before returning to the original state.
688 This makes data entry extremely fast: M-RET to create a new hedline,
689 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
691 When the cursor is at the end of an empty plain list item, one TAB will
692 make it a subitem, two or more tabs will back up to make this an item
693 higher up in the item hierarchy."
694 :group 'org-cycle
695 :type 'boolean)
697 (defcustom org-cycle-emulate-tab t
698 "Where should `org-cycle' emulate TAB.
699 nil Never
700 white Only in completely white lines
701 whitestart Only at the beginning of lines, before the first non-white char
702 t Everywhere except in headlines
703 exc-hl-bol Everywhere except at the start of a headline
704 If TAB is used in a place where it does not emulate TAB, the current subtree
705 visibility is cycled."
706 :group 'org-cycle
707 :type '(choice (const :tag "Never" nil)
708 (const :tag "Only in completely white lines" white)
709 (const :tag "Before first char in a line" whitestart)
710 (const :tag "Everywhere except in headlines" t)
711 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
714 (defcustom org-cycle-separator-lines 2
715 "Number of empty lines needed to keep an empty line between collapsed trees.
716 If you leave an empty line between the end of a subtree and the following
717 headline, this empty line is hidden when the subtree is folded.
718 Org-mode will leave (exactly) one empty line visible if the number of
719 empty lines is equal or larger to the number given in this variable.
720 So the default 2 means, at least 2 empty lines after the end of a subtree
721 are needed to produce free space between a collapsed subtree and the
722 following headline.
724 If the number is negative, and the number of empty lines is at least -N,
725 all empty lines are shown.
727 Special case: when 0, never leave empty lines in collapsed view."
728 :group 'org-cycle
729 :type 'integer)
730 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
732 (defcustom org-pre-cycle-hook nil
733 "Hook that is run before visibility cycling is happening.
734 The function(s) in this hook must accept a single argument which indicates
735 the new state that will be set right after running this hook. The
736 argument is a symbol. Before a global state change, it can have the values
737 `overview', `content', or `all'. Before a local state change, it can have
738 the values `folded', `children', or `subtree'."
739 :group 'org-cycle
740 :type 'hook)
742 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
743 org-cycle-hide-drawers
744 org-cycle-show-empty-lines
745 org-optimize-window-after-visibility-change)
746 "Hook that is run after `org-cycle' has changed the buffer visibility.
747 The function(s) in this hook must accept a single argument which indicates
748 the new state that was set by the most recent `org-cycle' command. The
749 argument is a symbol. After a global state change, it can have the values
750 `overview', `content', or `all'. After a local state change, it can have
751 the values `folded', `children', or `subtree'."
752 :group 'org-cycle
753 :type 'hook)
755 (defgroup org-edit-structure nil
756 "Options concerning structure editing in Org-mode."
757 :tag "Org Edit Structure"
758 :group 'org-structure)
760 (defcustom org-odd-levels-only nil
761 "Non-nil means, skip even levels and only use odd levels for the outline.
762 This has the effect that two stars are being added/taken away in
763 promotion/demotion commands. It also influences how levels are
764 handled by the exporters.
765 Changing it requires restart of `font-lock-mode' to become effective
766 for fontification also in regions already fontified.
767 You may also set this on a per-file basis by adding one of the following
768 lines to the buffer:
770 #+STARTUP: odd
771 #+STARTUP: oddeven"
772 :group 'org-edit-structure
773 :group 'org-font-lock
774 :type 'boolean)
776 (defcustom org-adapt-indentation t
777 "Non-nil means, adapt indentation to outline node level.
779 When this variable is set, Org assumes that you write outlines by
780 indenting text in each node to align with the headline (after the stars).
781 The following issues are influenced by this variable:
783 - When this is set and the *entire* text in an entry is indented, the
784 indentation is increased by one space in a demotion command, and
785 decreased by one in a promotion command. If any line in the entry
786 body starts with text at column 0, indentation is not changed at all.
788 - Property drawers and planning information is inserted indented when
789 this variable s set. When nil, they will not be indented.
791 - TAB indents a line relative to context. The lines below a headline
792 will be indented when this variable is set.
794 Note that this is all about true indentation, by adding and removing
795 space characters. See also `org-indent.el' which does level-dependent
796 indentation in a virtual way, i.e. at display time in Emacs."
797 :group 'org-edit-structure
798 :type 'boolean)
800 (defcustom org-special-ctrl-a/e nil
801 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
803 When t, `C-a' will bring back the cursor to the beginning of the
804 headline text, i.e. after the stars and after a possible TODO keyword.
805 In an item, this will be the position after the bullet.
806 When the cursor is already at that position, another `C-a' will bring
807 it to the beginning of the line.
809 `C-e' will jump to the end of the headline, ignoring the presence of tags
810 in the headline. A second `C-e' will then jump to the true end of the
811 line, after any tags. This also means that, when this variable is
812 non-nil, `C-e' also will never jump beyond the end of the heading of a
813 folded section, i.e. not after the ellipses.
815 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
816 going to the true line boundary first. Only a directly following, identical
817 keypress will bring the cursor to the special positions.
819 This may also be a cons cell where the behavior for `C-a' and `C-e' is
820 set separately."
821 :group 'org-edit-structure
822 :type '(choice
823 (const :tag "off" nil)
824 (const :tag "on: after stars/bullet and before tags first" t)
825 (const :tag "reversed: true line boundary first" reversed)
826 (cons :tag "Set C-a and C-e separately"
827 (choice :tag "Special C-a"
828 (const :tag "off" nil)
829 (const :tag "on: after stars/bullet first" t)
830 (const :tag "reversed: before stars/bullet first" reversed))
831 (choice :tag "Special C-e"
832 (const :tag "off" nil)
833 (const :tag "on: before tags first" t)
834 (const :tag "reversed: after tags first" reversed)))))
835 (if (fboundp 'defvaralias)
836 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
838 (defcustom org-special-ctrl-k nil
839 "Non-nil means `C-k' will behave specially in headlines.
840 When nil, `C-k' will call the default `kill-line' command.
841 When t, the following will happen while the cursor is in the headline:
843 - When the cursor is at the beginning of a headline, kill the entire
844 line and possible the folded subtree below the line.
845 - When in the middle of the headline text, kill the headline up to the tags.
846 - When after the headline text, kill the tags."
847 :group 'org-edit-structure
848 :type 'boolean)
850 (defcustom org-yank-folded-subtrees t
851 "Non-nil means, when yanking subtrees, fold them.
852 If the kill is a single subtree, or a sequence of subtrees, i.e. if
853 it starts with a heading and all other headings in it are either children
854 or siblings, then fold all the subtrees. However, do this only if no
855 text after the yank would be swallowed into a folded tree by this action."
856 :group 'org-edit-structure
857 :type 'boolean)
859 (defcustom org-yank-adjusted-subtrees nil
860 "Non-nil means, when yanking subtrees, adjust the level.
861 With this setting, `org-paste-subtree' is used to insert the subtree, see
862 this function for details."
863 :group 'org-edit-structure
864 :type 'boolean)
866 (defcustom org-M-RET-may-split-line '((default . t))
867 "Non-nil means, M-RET will split the line at the cursor position.
868 When nil, it will go to the end of the line before making a
869 new line.
870 You may also set this option in a different way for different
871 contexts. Valid contexts are:
873 headline when creating a new headline
874 item when creating a new item
875 table in a table field
876 default the value to be used for all contexts not explicitly
877 customized"
878 :group 'org-structure
879 :group 'org-table
880 :type '(choice
881 (const :tag "Always" t)
882 (const :tag "Never" nil)
883 (repeat :greedy t :tag "Individual contexts"
884 (cons
885 (choice :tag "Context"
886 (const headline)
887 (const item)
888 (const table)
889 (const default))
890 (boolean)))))
893 (defcustom org-insert-heading-respect-content nil
894 "Non-nil means, insert new headings after the current subtree.
895 When nil, the new heading is created directly after the current line.
896 The commands \\[org-insert-heading-respect-content] and
897 \\[org-insert-todo-heading-respect-content] turn this variable on
898 for the duration of the command."
899 :group 'org-structure
900 :type 'boolean)
902 (defcustom org-blank-before-new-entry '((heading . auto)
903 (plain-list-item . auto))
904 "Should `org-insert-heading' leave a blank line before new heading/item?
905 The value is an alist, with `heading' and `plain-list-item' as car,
906 and a boolean flag as cdr. For plain lists, if the variable
907 `org-empty-line-terminates-plain-lists' is set, the setting here
908 is ignored and no empty line is inserted, to keep the list in tact."
909 :group 'org-edit-structure
910 :type '(list
911 (cons (const heading)
912 (choice (const :tag "Never" nil)
913 (const :tag "Always" t)
914 (const :tag "Auto" auto)))
915 (cons (const plain-list-item)
916 (choice (const :tag "Never" nil)
917 (const :tag "Always" t)
918 (const :tag "Auto" auto)))))
920 (defcustom org-insert-heading-hook nil
921 "Hook being run after inserting a new heading."
922 :group 'org-edit-structure
923 :type 'hook)
925 (defcustom org-enable-fixed-width-editor t
926 "Non-nil means, lines starting with \":\" are treated as fixed-width.
927 This currently only means, they are never auto-wrapped.
928 When nil, such lines will be treated like ordinary lines.
929 See also the QUOTE keyword."
930 :group 'org-edit-structure
931 :type 'boolean)
934 (defcustom org-goto-auto-isearch t
935 "Non-nil means, typing characters in org-goto starts incremental search."
936 :group 'org-edit-structure
937 :type 'boolean)
939 (defgroup org-sparse-trees nil
940 "Options concerning sparse trees in Org-mode."
941 :tag "Org Sparse Trees"
942 :group 'org-structure)
944 (defcustom org-highlight-sparse-tree-matches t
945 "Non-nil means, highlight all matches that define a sparse tree.
946 The highlights will automatically disappear the next time the buffer is
947 changed by an edit command."
948 :group 'org-sparse-trees
949 :type 'boolean)
951 (defcustom org-remove-highlights-with-change t
952 "Non-nil means, any change to the buffer will remove temporary highlights.
953 Such highlights are created by `org-occur' and `org-clock-display'.
954 When nil, `C-c C-c needs to be used to get rid of the highlights.
955 The highlights created by `org-preview-latex-fragment' always need
956 `C-c C-c' to be removed."
957 :group 'org-sparse-trees
958 :group 'org-time
959 :type 'boolean)
962 (defcustom org-occur-hook '(org-first-headline-recenter)
963 "Hook that is run after `org-occur' has constructed a sparse tree.
964 This can be used to recenter the window to show as much of the structure
965 as possible."
966 :group 'org-sparse-trees
967 :type 'hook)
969 (defgroup org-imenu-and-speedbar nil
970 "Options concerning imenu and speedbar in Org-mode."
971 :tag "Org Imenu and Speedbar"
972 :group 'org-structure)
974 (defcustom org-imenu-depth 2
975 "The maximum level for Imenu access to Org-mode headlines.
976 This also applied for speedbar access."
977 :group 'org-imenu-and-speedbar
978 :type 'integer)
980 (defgroup org-table nil
981 "Options concerning tables in Org-mode."
982 :tag "Org Table"
983 :group 'org)
985 (defcustom org-enable-table-editor 'optimized
986 "Non-nil means, lines starting with \"|\" are handled by the table editor.
987 When nil, such lines will be treated like ordinary lines.
989 When equal to the symbol `optimized', the table editor will be optimized to
990 do the following:
991 - Automatic overwrite mode in front of whitespace in table fields.
992 This makes the structure of the table stay in tact as long as the edited
993 field does not exceed the column width.
994 - Minimize the number of realigns. Normally, the table is aligned each time
995 TAB or RET are pressed to move to another field. With optimization this
996 happens only if changes to a field might have changed the column width.
997 Optimization requires replacing the functions `self-insert-command',
998 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
999 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1000 very good at guessing when a re-align will be necessary, but you can always
1001 force one with \\[org-ctrl-c-ctrl-c].
1003 If you would like to use the optimized version in Org-mode, but the
1004 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1006 This variable can be used to turn on and off the table editor during a session,
1007 but in order to toggle optimization, a restart is required.
1009 See also the variable `org-table-auto-blank-field'."
1010 :group 'org-table
1011 :type '(choice
1012 (const :tag "off" nil)
1013 (const :tag "on" t)
1014 (const :tag "on, optimized" optimized)))
1016 (defcustom org-self-insert-cluster-for-undo t
1017 "Non-nil means cluster self-insert commands for undo when possible.
1018 If this is set, then, like in the Emacs command loop, 20 consequtive
1019 characters will be undone together.
1020 This is configurable, because there is some impact on typing performance."
1021 :group 'org-table
1022 :type 'boolean)
1024 (defcustom org-table-tab-recognizes-table.el t
1025 "Non-nil means, TAB will automatically notice a table.el table.
1026 When it sees such a table, it moves point into it and - if necessary -
1027 calls `table-recognize-table'."
1028 :group 'org-table-editing
1029 :type 'boolean)
1031 (defgroup org-link nil
1032 "Options concerning links in Org-mode."
1033 :tag "Org Link"
1034 :group 'org)
1036 (defvar org-link-abbrev-alist-local nil
1037 "Buffer-local version of `org-link-abbrev-alist', which see.
1038 The value of this is taken from the #+LINK lines.")
1039 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1041 (defcustom org-link-abbrev-alist nil
1042 "Alist of link abbreviations.
1043 The car of each element is a string, to be replaced at the start of a link.
1044 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1045 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1047 [[linkkey:tag][description]]
1049 The 'linkkey' must be a word word, starting with a letter, followed
1050 by letters, numbers, '-' or '_'.
1052 If REPLACE is a string, the tag will simply be appended to create the link.
1053 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1054 the placeholder \"%h\" will cause a url-encoded version of the tag to
1055 be inserted at that point (see the function `url-hexify-string').
1057 REPLACE may also be a function that will be called with the tag as the
1058 only argument to create the link, which should be returned as a string.
1060 See the manual for examples."
1061 :group 'org-link
1062 :type '(repeat
1063 (cons
1064 (string :tag "Protocol")
1065 (choice
1066 (string :tag "Format")
1067 (function)))))
1069 (defcustom org-descriptive-links t
1070 "Non-nil means, hide link part and only show description of bracket links.
1071 Bracket links are like [[link][description]]. This variable sets the initial
1072 state in new org-mode buffers. The setting can then be toggled on a
1073 per-buffer basis from the Org->Hyperlinks menu."
1074 :group 'org-link
1075 :type 'boolean)
1077 (defcustom org-link-file-path-type 'adaptive
1078 "How the path name in file links should be stored.
1079 Valid values are:
1081 relative Relative to the current directory, i.e. the directory of the file
1082 into which the link is being inserted.
1083 absolute Absolute path, if possible with ~ for home directory.
1084 noabbrev Absolute path, no abbreviation of home directory.
1085 adaptive Use relative path for files in the current directory and sub-
1086 directories of it. For other files, use an absolute path."
1087 :group 'org-link
1088 :type '(choice
1089 (const relative)
1090 (const absolute)
1091 (const noabbrev)
1092 (const adaptive)))
1094 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1095 "Types of links that should be activated in Org-mode files.
1096 This is a list of symbols, each leading to the activation of a certain link
1097 type. In principle, it does not hurt to turn on most link types - there may
1098 be a small gain when turning off unused link types. The types are:
1100 bracket The recommended [[link][description]] or [[link]] links with hiding.
1101 angular Links in angular brackets that may contain whitespace like
1102 <bbdb:Carsten Dominik>.
1103 plain Plain links in normal text, no whitespace, like http://google.com.
1104 radio Text that is matched by a radio target, see manual for details.
1105 tag Tag settings in a headline (link to tag search).
1106 date Time stamps (link to calendar).
1107 footnote Footnote labels.
1109 Changing this variable requires a restart of Emacs to become effective."
1110 :group 'org-link
1111 :type '(set :greedy t
1112 (const :tag "Double bracket links (new style)" bracket)
1113 (const :tag "Angular bracket links (old style)" angular)
1114 (const :tag "Plain text links" plain)
1115 (const :tag "Radio target matches" radio)
1116 (const :tag "Tags" tag)
1117 (const :tag "Timestamps" date)
1118 (const :tag "Footnotes" footnote)))
1120 (defcustom org-make-link-description-function nil
1121 "Function to use to generate link descriptions from links. If
1122 nil the link location will be used. This function must take two
1123 parameters; the first is the link and the second the description
1124 org-insert-link has generated, and should return the description
1125 to use."
1126 :group 'org-link
1127 :type 'function)
1129 (defgroup org-link-store nil
1130 "Options concerning storing links in Org-mode."
1131 :tag "Org Store Link"
1132 :group 'org-link)
1134 (defcustom org-email-link-description-format "Email %c: %.30s"
1135 "Format of the description part of a link to an email or usenet message.
1136 The following %-escapes will be replaced by corresponding information:
1138 %F full \"From\" field
1139 %f name, taken from \"From\" field, address if no name
1140 %T full \"To\" field
1141 %t first name in \"To\" field, address if no name
1142 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1143 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1144 %s subject
1145 %m message-id.
1147 You may use normal field width specification between the % and the letter.
1148 This is for example useful to limit the length of the subject.
1150 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1151 :group 'org-link-store
1152 :type 'string)
1154 (defcustom org-from-is-user-regexp
1155 (let (r1 r2)
1156 (when (and user-mail-address (not (string= user-mail-address "")))
1157 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1158 (when (and user-full-name (not (string= user-full-name "")))
1159 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1160 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1161 "Regexp matched against the \"From:\" header of an email or usenet message.
1162 It should match if the message is from the user him/herself."
1163 :group 'org-link-store
1164 :type 'regexp)
1166 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1167 "Non-nil means, storing a link to an Org file will use entry IDs.
1169 Note that before this variable is even considered, org-id must be loaded,
1170 so please customize `org-modules' and turn it on.
1172 The variable can have the following values:
1174 t Create an ID if needed to make a link to the current entry.
1176 create-if-interactive
1177 If `org-store-link' is called directly (interactively, as a user
1178 command), do create an ID to support the link. But when doing the
1179 job for remember, only use the ID if it already exists. The
1180 purpose of this setting is to avoid proliferation of unwanted
1181 IDs, just because you happen to be in an Org file when you
1182 call `org-remember' that automatically and preemptively
1183 creates a link. If you do want to get an ID link in a remember
1184 template to an entry not having an ID, create it first by
1185 explicitly creating a link to it, using `C-c C-l' first.
1187 create-if-interactive-and-no-custom-id
1188 Like create-if-interactive, but do not create an ID if there is
1189 a CUSTOM_ID property defined in the entry. This is the default.
1191 use-existing
1192 Use existing ID, do not create one.
1194 nil Never use an ID to make a link, instead link using a text search for
1195 the headline text."
1196 :group 'org-link-store
1197 :type '(choice
1198 (const :tag "Create ID to make link" t)
1199 (const :tag "Create if storing link interactively"
1200 create-if-interactive)
1201 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1202 create-if-interactive-and-no-custom-id)
1203 (const :tag "Only use existing" use-existing)
1204 (const :tag "Do not use ID to create link" nil)))
1206 (defcustom org-context-in-file-links t
1207 "Non-nil means, file links from `org-store-link' contain context.
1208 A search string will be added to the file name with :: as separator and
1209 used to find the context when the link is activated by the command
1210 `org-open-at-point'.
1211 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1212 negates this setting for the duration of the command."
1213 :group 'org-link-store
1214 :type 'boolean)
1216 (defcustom org-keep-stored-link-after-insertion nil
1217 "Non-nil means, keep link in list for entire session.
1219 The command `org-store-link' adds a link pointing to the current
1220 location to an internal list. These links accumulate during a session.
1221 The command `org-insert-link' can be used to insert links into any
1222 Org-mode file (offering completion for all stored links). When this
1223 option is nil, every link which has been inserted once using \\[org-insert-link]
1224 will be removed from the list, to make completing the unused links
1225 more efficient."
1226 :group 'org-link-store
1227 :type 'boolean)
1229 (defgroup org-link-follow nil
1230 "Options concerning following links in Org-mode."
1231 :tag "Org Follow Link"
1232 :group 'org-link)
1234 (defcustom org-link-translation-function nil
1235 "Function to translate links with different syntax to Org syntax.
1236 This can be used to translate links created for example by the Planner
1237 or emacs-wiki packages to Org syntax.
1238 The function must accept two parameters, a TYPE containing the link
1239 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1240 which is everything after the link protocol. It should return a cons
1241 with possibly modified values of type and path.
1242 Org contains a function for this, so if you set this variable to
1243 `org-translate-link-from-planner', you should be able follow many
1244 links created by planner."
1245 :group 'org-link-follow
1246 :type 'function)
1248 (defcustom org-follow-link-hook nil
1249 "Hook that is run after a link has been followed."
1250 :group 'org-link-follow
1251 :type 'hook)
1253 (defcustom org-tab-follows-link nil
1254 "Non-nil means, on links TAB will follow the link.
1255 Needs to be set before org.el is loaded.
1256 This really should not be used, it does not make sense, and the
1257 implementation is bad."
1258 :group 'org-link-follow
1259 :type 'boolean)
1261 (defcustom org-return-follows-link nil
1262 "Non-nil means, on links RET will follow the link.
1263 Needs to be set before org.el is loaded."
1264 :group 'org-link-follow
1265 :type 'boolean)
1267 (defcustom org-mouse-1-follows-link
1268 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1269 "Non-nil means, mouse-1 on a link will follow the link.
1270 A longer mouse click will still set point. Does not work on XEmacs.
1271 Needs to be set before org.el is loaded."
1272 :group 'org-link-follow
1273 :type 'boolean)
1275 (defcustom org-mark-ring-length 4
1276 "Number of different positions to be recorded in the ring
1277 Changing this requires a restart of Emacs to work correctly."
1278 :group 'org-link-follow
1279 :type 'integer)
1281 (defcustom org-link-frame-setup
1282 '((vm . vm-visit-folder-other-frame)
1283 (gnus . gnus-other-frame)
1284 (file . find-file-other-window))
1285 "Setup the frame configuration for following links.
1286 When following a link with Emacs, it may often be useful to display
1287 this link in another window or frame. This variable can be used to
1288 set this up for the different types of links.
1289 For VM, use any of
1290 `vm-visit-folder'
1291 `vm-visit-folder-other-frame'
1292 For Gnus, use any of
1293 `gnus'
1294 `gnus-other-frame'
1295 `org-gnus-no-new-news'
1296 For FILE, use any of
1297 `find-file'
1298 `find-file-other-window'
1299 `find-file-other-frame'
1300 For the calendar, use the variable `calendar-setup'.
1301 For BBDB, it is currently only possible to display the matches in
1302 another window."
1303 :group 'org-link-follow
1304 :type '(list
1305 (cons (const vm)
1306 (choice
1307 (const vm-visit-folder)
1308 (const vm-visit-folder-other-window)
1309 (const vm-visit-folder-other-frame)))
1310 (cons (const gnus)
1311 (choice
1312 (const gnus)
1313 (const gnus-other-frame)
1314 (const org-gnus-no-new-news)))
1315 (cons (const file)
1316 (choice
1317 (const find-file)
1318 (const find-file-other-window)
1319 (const find-file-other-frame)))))
1321 (defcustom org-display-internal-link-with-indirect-buffer nil
1322 "Non-nil means, use indirect buffer to display infile links.
1323 Activating internal links (from one location in a file to another location
1324 in the same file) normally just jumps to the location. When the link is
1325 activated with a C-u prefix (or with mouse-3), the link is displayed in
1326 another window. When this option is set, the other window actually displays
1327 an indirect buffer clone of the current buffer, to avoid any visibility
1328 changes to the current buffer."
1329 :group 'org-link-follow
1330 :type 'boolean)
1332 (defcustom org-open-non-existing-files nil
1333 "Non-nil means, `org-open-file' will open non-existing files.
1334 When nil, an error will be generated.
1335 This variable applies only to external applications because they
1336 might choke on non-existing files. If the link is to a file that
1337 will be openend in Emacs, the variable is ignored."
1338 :group 'org-link-follow
1339 :type 'boolean)
1341 (defcustom org-open-directory-means-index-dot-org nil
1342 "Non-nil means, a link to a directory really means to index.org.
1343 When nil, following a directory link will run dired or open a finder/explorer
1344 window on that directory."
1345 :group 'org-link-follow
1346 :type 'boolean)
1348 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1349 "Function and arguments to call for following mailto links.
1350 This is a list with the first element being a lisp function, and the
1351 remaining elements being arguments to the function. In string arguments,
1352 %a will be replaced by the address, and %s will be replaced by the subject
1353 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1354 :group 'org-link-follow
1355 :type '(choice
1356 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1357 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1358 (const :tag "message-mail" (message-mail "%a" "%s"))
1359 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1361 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1362 "Non-nil means, ask for confirmation before executing shell links.
1363 Shell links can be dangerous: just think about a link
1365 [[shell:rm -rf ~/*][Google Search]]
1367 This link would show up in your Org-mode document as \"Google Search\",
1368 but really it would remove your entire home directory.
1369 Therefore we advise against setting this variable to nil.
1370 Just change it to `y-or-n-p' if you want to confirm with a
1371 single keystroke rather than having to type \"yes\"."
1372 :group 'org-link-follow
1373 :type '(choice
1374 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1375 (const :tag "with y-or-n (faster)" y-or-n-p)
1376 (const :tag "no confirmation (dangerous)" nil)))
1378 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1379 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1380 Elisp links can be dangerous: just think about a link
1382 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1384 This link would show up in your Org-mode document as \"Google Search\",
1385 but really it would remove your entire home directory.
1386 Therefore we advise against setting this variable to nil.
1387 Just change it to `y-or-n-p' if you want to confirm with a
1388 single keystroke rather than having to type \"yes\"."
1389 :group 'org-link-follow
1390 :type '(choice
1391 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1392 (const :tag "with y-or-n (faster)" y-or-n-p)
1393 (const :tag "no confirmation (dangerous)" nil)))
1395 (defconst org-file-apps-defaults-gnu
1396 '((remote . emacs)
1397 (system . mailcap)
1398 (t . mailcap))
1399 "Default file applications on a UNIX or GNU/Linux system.
1400 See `org-file-apps'.")
1402 (defconst org-file-apps-defaults-macosx
1403 '((remote . emacs)
1404 (t . "open %s")
1405 (system . "open %s")
1406 ("ps.gz" . "gv %s")
1407 ("eps.gz" . "gv %s")
1408 ("dvi" . "xdvi %s")
1409 ("fig" . "xfig %s"))
1410 "Default file applications on a MacOS X system.
1411 The system \"open\" is known as a default, but we use X11 applications
1412 for some files for which the OS does not have a good default.
1413 See `org-file-apps'.")
1415 (defconst org-file-apps-defaults-windowsnt
1416 (list
1417 '(remote . emacs)
1418 (cons t
1419 (list (if (featurep 'xemacs)
1420 'mswindows-shell-execute
1421 'w32-shell-execute)
1422 "open" 'file))
1423 (cons 'system
1424 (list (if (featurep 'xemacs)
1425 'mswindows-shell-execute
1426 'w32-shell-execute)
1427 "open" 'file)))
1428 "Default file applications on a Windows NT system.
1429 The system \"open\" is used for most files.
1430 See `org-file-apps'.")
1432 (defcustom org-file-apps
1434 (auto-mode . emacs)
1435 ("\\.mm\\'" . default)
1436 ("\\.x?html?\\'" . default)
1437 ("\\.pdf\\'" . default)
1439 "External applications for opening `file:path' items in a document.
1440 Org-mode uses system defaults for different file types, but
1441 you can use this variable to set the application for a given file
1442 extension. The entries in this list are cons cells where the car identifies
1443 files and the cdr the corresponding command. Possible values for the
1444 file identifier are
1445 \"regex\" Regular expression matched against the file name. For backward
1446 compatibility, this can also be a string with only alphanumeric
1447 characters, which is then interpreted as an extension.
1448 `directory' Matches a directory
1449 `remote' Matches a remote file, accessible through tramp or efs.
1450 Remote files most likely should be visited through Emacs
1451 because external applications cannot handle such paths.
1452 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1453 so all files Emacs knows how to handle. Using this with
1454 command `emacs' will open most files in Emacs. Beware that this
1455 will also open html files inside Emacs, unless you add
1456 (\"html\" . default) to the list as well.
1457 t Default for files not matched by any of the other options.
1458 `system' The system command to open files, like `open' on Windows
1459 and Mac OS X, and mailcap under GNU/Linux. This is the command
1460 that will be selected if you call `C-c C-o' with a double
1461 `C-u C-u' prefix.
1463 Possible values for the command are:
1464 `emacs' The file will be visited by the current Emacs process.
1465 `default' Use the default application for this file type, which is the
1466 association for t in the list, most likely in the system-specific
1467 part.
1468 This can be used to overrule an unwanted setting in the
1469 system-specific variable.
1470 `system' Use the system command for opening files, like \"open\".
1471 This command is specified by the entry whose car is `system'.
1472 Most likely, the system-specific version of this variable
1473 does define this command, but you can overrule/replace it
1474 here.
1475 string A command to be executed by a shell; %s will be replaced
1476 by the path to the file.
1477 sexp A Lisp form which will be evaluated. The file path will
1478 be available in the Lisp variable `file'.
1479 For more examples, see the system specific constants
1480 `org-file-apps-defaults-macosx'
1481 `org-file-apps-defaults-windowsnt'
1482 `org-file-apps-defaults-gnu'."
1483 :group 'org-link-follow
1484 :type '(repeat
1485 (cons (choice :value ""
1486 (string :tag "Extension")
1487 (const :tag "System command to open files" system)
1488 (const :tag "Default for unrecognized files" t)
1489 (const :tag "Remote file" remote)
1490 (const :tag "Links to a directory" directory)
1491 (const :tag "Any files that have Emacs modes"
1492 auto-mode))
1493 (choice :value ""
1494 (const :tag "Visit with Emacs" emacs)
1495 (const :tag "Use default" default)
1496 (const :tag "Use the system command" system)
1497 (string :tag "Command")
1498 (sexp :tag "Lisp form")))))
1500 (defgroup org-refile nil
1501 "Options concerning refiling entries in Org-mode."
1502 :tag "Org Refile"
1503 :group 'org)
1505 (defcustom org-directory "~/org"
1506 "Directory with org files.
1507 This is just a default location to look for Org files. There is no need
1508 at all to put your files into this directory. It is only used in the
1509 following situations:
1511 1. When a remember template specifies a target file that is not an
1512 absolute path. The path will then be interpreted relative to
1513 `org-directory'
1514 2. When a remember note is filed away in an interactive way (when exiting the
1515 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1516 with `org-directory' as the default path."
1517 :group 'org-refile
1518 :group 'org-remember
1519 :type 'directory)
1521 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1522 "Default target for storing notes.
1523 Used by the hooks for remember.el. This can be a string, or nil to mean
1524 the value of `remember-data-file'.
1525 You can set this on a per-template basis with the variable
1526 `org-remember-templates'."
1527 :group 'org-refile
1528 :group 'org-remember
1529 :type '(choice
1530 (const :tag "Default from remember-data-file" nil)
1531 file))
1533 (defcustom org-goto-interface 'outline
1534 "The default interface to be used for `org-goto'.
1535 Allowed values are:
1536 outline The interface shows an outline of the relevant file
1537 and the correct heading is found by moving through
1538 the outline or by searching with incremental search.
1539 outline-path-completion Headlines in the current buffer are offered via
1540 completion. This is the interface also used by
1541 the refile command."
1542 :group 'org-refile
1543 :type '(choice
1544 (const :tag "Outline" outline)
1545 (const :tag "Outline-path-completion" outline-path-completion)))
1547 (defcustom org-goto-max-level 5
1548 "Maximum level to be considered when running org-goto with refile interface."
1549 :group 'org-refile
1550 :type 'integer)
1552 (defcustom org-reverse-note-order nil
1553 "Non-nil means, store new notes at the beginning of a file or entry.
1554 When nil, new notes will be filed to the end of a file or entry.
1555 This can also be a list with cons cells of regular expressions that
1556 are matched against file names, and values."
1557 :group 'org-remember
1558 :group 'org-refile
1559 :type '(choice
1560 (const :tag "Reverse always" t)
1561 (const :tag "Reverse never" nil)
1562 (repeat :tag "By file name regexp"
1563 (cons regexp boolean))))
1565 (defcustom org-refile-targets nil
1566 "Targets for refiling entries with \\[org-refile].
1567 This is list of cons cells. Each cell contains:
1568 - a specification of the files to be considered, either a list of files,
1569 or a symbol whose function or variable value will be used to retrieve
1570 a file name or a list of file names. If you use `org-agenda-files' for
1571 that, all agenda files will be scanned for targets. Nil means, consider
1572 headings in the current buffer.
1573 - A specification of how to find candidate refile targets. This may be
1574 any of:
1575 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1576 This tag has to be present in all target headlines, inheritance will
1577 not be considered.
1578 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1579 todo keyword.
1580 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1581 headlines that are refiling targets.
1582 - a cons cell (:level . N). Any headline of level N is considered a target.
1583 Note that, when `org-odd-levels-only' is set, level corresponds to
1584 order in hierarchy, not to the number of stars.
1585 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1586 Note that, when `org-odd-levels-only' is set, level corresponds to
1587 order in hierarchy, not to the number of stars.
1589 You can set the variable `org-refile-target-verify-function' to a function
1590 to verify each headline found by the simple critery above.
1592 When this variable is nil, all top-level headlines in the current buffer
1593 are used, equivalent to the value `((nil . (:level . 1))'."
1594 :group 'org-refile
1595 :type '(repeat
1596 (cons
1597 (choice :value org-agenda-files
1598 (const :tag "All agenda files" org-agenda-files)
1599 (const :tag "Current buffer" nil)
1600 (function) (variable) (file))
1601 (choice :tag "Identify target headline by"
1602 (cons :tag "Specific tag" (const :value :tag) (string))
1603 (cons :tag "TODO keyword" (const :value :todo) (string))
1604 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1605 (cons :tag "Level number" (const :value :level) (integer))
1606 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1608 (defcustom org-refile-target-verify-function nil
1609 "Function to verify if the headline at point should be a refile target.
1610 The function will be called without arguments, with point at the
1611 beginning of the headline. It should return t and leave point
1612 where it is if the headline is a valid target for refiling.
1614 If the target should not be selected, the function must return nil.
1615 In addition to this, it may move point to a place from where the search
1616 should be continued. For example, the function may decide that the entire
1617 subtree of the current entry should be excluded and move point to the end
1618 of the subtree."
1619 :group 'org-refile
1620 :type 'function)
1622 (defcustom org-refile-use-outline-path nil
1623 "Non-nil means, provide refile targets as paths.
1624 So a level 3 headline will be available as level1/level2/level3.
1626 When the value is `file', also include the file name (without directory)
1627 into the path. In this case, you can also stop the completion after
1628 the file name, to get entries inserted as top level in the file.
1630 When `full-file-path', include the full file path."
1631 :group 'org-refile
1632 :type '(choice
1633 (const :tag "Not" nil)
1634 (const :tag "Yes" t)
1635 (const :tag "Start with file name" file)
1636 (const :tag "Start with full file path" full-file-path)))
1638 (defcustom org-outline-path-complete-in-steps t
1639 "Non-nil means, complete the outline path in hierarchical steps.
1640 When Org-mode uses the refile interface to select an outline path
1641 \(see variable `org-refile-use-outline-path'), the completion of
1642 the path can be done is a single go, or if can be done in steps down
1643 the headline hierarchy. Going in steps is probably the best if you
1644 do not use a special completion package like `ido' or `icicles'.
1645 However, when using these packages, going in one step can be very
1646 fast, while still showing the whole path to the entry."
1647 :group 'org-refile
1648 :type 'boolean)
1650 (defcustom org-refile-allow-creating-parent-nodes nil
1651 "Non-nil means, allow to create new nodes as refile targets.
1652 New nodes are then created by adding \"/new node name\" to the completion
1653 of an existing node. When the value of this variable is `confirm',
1654 new node creation must be confirmed by the user (recommended)
1655 When nil, the completion must match an existing entry.
1657 Note that, if the new heading is not seen by the criteria
1658 listed in `org-refile-targets', multiple instances of the same
1659 heading would be created by trying again to file under the new
1660 heading."
1661 :group 'org-refile
1662 :type '(choice
1663 (const :tag "Never" nil)
1664 (const :tag "Always" t)
1665 (const :tag "Prompt for confirmation" confirm)))
1667 (defgroup org-todo nil
1668 "Options concerning TODO items in Org-mode."
1669 :tag "Org TODO"
1670 :group 'org)
1672 (defgroup org-progress nil
1673 "Options concerning Progress logging in Org-mode."
1674 :tag "Org Progress"
1675 :group 'org-time)
1677 (defvar org-todo-interpretation-widgets
1679 (:tag "Sequence (cycling hits every state)" sequence)
1680 (:tag "Type (cycling directly to DONE)" type))
1681 "The available interpretation symbols for customizing
1682 `org-todo-keywords'.
1683 Interested libraries should add to this list.")
1685 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1686 "List of TODO entry keyword sequences and their interpretation.
1687 \\<org-mode-map>This is a list of sequences.
1689 Each sequence starts with a symbol, either `sequence' or `type',
1690 indicating if the keywords should be interpreted as a sequence of
1691 action steps, or as different types of TODO items. The first
1692 keywords are states requiring action - these states will select a headline
1693 for inclusion into the global TODO list Org-mode produces. If one of
1694 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1695 signify that no further action is necessary. If \"|\" is not found,
1696 the last keyword is treated as the only DONE state of the sequence.
1698 The command \\[org-todo] cycles an entry through these states, and one
1699 additional state where no keyword is present. For details about this
1700 cycling, see the manual.
1702 TODO keywords and interpretation can also be set on a per-file basis with
1703 the special #+SEQ_TODO and #+TYP_TODO lines.
1705 Each keyword can optionally specify a character for fast state selection
1706 \(in combination with the variable `org-use-fast-todo-selection')
1707 and specifiers for state change logging, using the same syntax
1708 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1709 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1710 indicates to record a time stamp each time this state is selected.
1712 Each keyword may also specify if a timestamp or a note should be
1713 recorded when entering or leaving the state, by adding additional
1714 characters in the parenthesis after the keyword. This looks like this:
1715 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1716 record only the time of the state change. With X and Y being either
1717 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1718 Y when leaving the state if and only if the *target* state does not
1719 define X. You may omit any of the fast-selection key or X or /Y,
1720 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1722 For backward compatibility, this variable may also be just a list
1723 of keywords - in this case the interpretation (sequence or type) will be
1724 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1725 :group 'org-todo
1726 :group 'org-keywords
1727 :type '(choice
1728 (repeat :tag "Old syntax, just keywords"
1729 (string :tag "Keyword"))
1730 (repeat :tag "New syntax"
1731 (cons
1732 (choice
1733 :tag "Interpretation"
1734 ;;Quick and dirty way to see
1735 ;;`org-todo-interpretations'. This takes the
1736 ;;place of item arguments
1737 :convert-widget
1738 (lambda (widget)
1739 (widget-put widget
1740 :args (mapcar
1741 #'(lambda (x)
1742 (widget-convert
1743 (cons 'const x)))
1744 org-todo-interpretation-widgets))
1745 widget))
1746 (repeat
1747 (string :tag "Keyword"))))))
1749 (defvar org-todo-keywords-1 nil
1750 "All TODO and DONE keywords active in a buffer.")
1751 (make-variable-buffer-local 'org-todo-keywords-1)
1752 (defvar org-todo-keywords-for-agenda nil)
1753 (defvar org-done-keywords-for-agenda nil)
1754 (defvar org-drawers-for-agenda nil)
1755 (defvar org-todo-keyword-alist-for-agenda nil)
1756 (defvar org-tag-alist-for-agenda nil)
1757 (defvar org-agenda-contributing-files nil)
1758 (defvar org-not-done-keywords nil)
1759 (make-variable-buffer-local 'org-not-done-keywords)
1760 (defvar org-done-keywords nil)
1761 (make-variable-buffer-local 'org-done-keywords)
1762 (defvar org-todo-heads nil)
1763 (make-variable-buffer-local 'org-todo-heads)
1764 (defvar org-todo-sets nil)
1765 (make-variable-buffer-local 'org-todo-sets)
1766 (defvar org-todo-log-states nil)
1767 (make-variable-buffer-local 'org-todo-log-states)
1768 (defvar org-todo-kwd-alist nil)
1769 (make-variable-buffer-local 'org-todo-kwd-alist)
1770 (defvar org-todo-key-alist nil)
1771 (make-variable-buffer-local 'org-todo-key-alist)
1772 (defvar org-todo-key-trigger nil)
1773 (make-variable-buffer-local 'org-todo-key-trigger)
1775 (defcustom org-todo-interpretation 'sequence
1776 "Controls how TODO keywords are interpreted.
1777 This variable is in principle obsolete and is only used for
1778 backward compatibility, if the interpretation of todo keywords is
1779 not given already in `org-todo-keywords'. See that variable for
1780 more information."
1781 :group 'org-todo
1782 :group 'org-keywords
1783 :type '(choice (const sequence)
1784 (const type)))
1786 (defcustom org-use-fast-todo-selection t
1787 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1788 This variable describes if and under what circumstances the cycling
1789 mechanism for TODO keywords will be replaced by a single-key, direct
1790 selection scheme.
1792 When nil, fast selection is never used.
1794 When the symbol `prefix', it will be used when `org-todo' is called with
1795 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1796 in an agenda buffer.
1798 When t, fast selection is used by default. In this case, the prefix
1799 argument forces cycling instead.
1801 In all cases, the special interface is only used if access keys have actually
1802 been assigned by the user, i.e. if keywords in the configuration are followed
1803 by a letter in parenthesis, like TODO(t)."
1804 :group 'org-todo
1805 :type '(choice
1806 (const :tag "Never" nil)
1807 (const :tag "By default" t)
1808 (const :tag "Only with C-u C-c C-t" prefix)))
1810 (defcustom org-provide-todo-statistics t
1811 "Non-nil means, update todo statistics after insert and toggle.
1812 ALL-HEADLINES means update todo statistics by including headlines
1813 with no TODO keyword as well, counting them as not done.
1814 A list of TODO keywords means the same, but skip keywords that are
1815 not in this list.
1817 When this is set, todo statistics is updated in the parent of the
1818 current entry each time a todo state is changed."
1819 :group 'org-todo
1820 :type '(choice
1821 (const :tag "Yes, only for TODO entries" t)
1822 (const :tag "Yes, including all entries" 'all-headlines)
1823 (repeat :tag "Yes, for TODOs in this list"
1824 (string :tag "TODO keyword"))
1825 (other :tag "No TODO statistics" nil)))
1827 (defcustom org-hierarchical-todo-statistics t
1828 "Non-nil means, TODO statistics covers just direct children.
1829 When nil, all entries in the subtree are considered.
1830 This has only an effect if `org-provide-todo-statistics' is set.
1831 To set this to nil for only a single subtree, use a COOKIE_DATA
1832 property and include the word \"recursive\" into the value."
1833 :group 'org-todo
1834 :type 'boolean)
1836 (defcustom org-after-todo-state-change-hook nil
1837 "Hook which is run after the state of a TODO item was changed.
1838 The new state (a string with a TODO keyword, or nil) is available in the
1839 Lisp variable `state'."
1840 :group 'org-todo
1841 :type 'hook)
1843 (defvar org-blocker-hook nil
1844 "Hook for functions that are allowed to block a state change.
1846 Each function gets as its single argument a property list, see
1847 `org-trigger-hook' for more information about this list.
1849 If any of the functions in this hook returns nil, the state change
1850 is blocked.")
1852 (defvar org-trigger-hook nil
1853 "Hook for functions that are triggered by a state change.
1855 Each function gets as its single argument a property list with at least
1856 the following elements:
1858 (:type type-of-change :position pos-at-entry-start
1859 :from old-state :to new-state)
1861 Depending on the type, more properties may be present.
1863 This mechanism is currently implemented for:
1865 TODO state changes
1866 ------------------
1867 :type todo-state-change
1868 :from previous state (keyword as a string), or nil, or a symbol
1869 'todo' or 'done', to indicate the general type of state.
1870 :to new state, like in :from")
1872 (defcustom org-enforce-todo-dependencies nil
1873 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1874 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1875 be blocked if any prior sibling is not yet done.
1876 Finally, if the parent is blocked because of ordered siblings of its own,
1877 the child will also be blocked.
1878 This variable needs to be set before org.el is loaded, and you need to
1879 restart Emacs after a change to make the change effective. The only way
1880 to change is while Emacs is running is through the customize interface."
1881 :set (lambda (var val)
1882 (set var val)
1883 (if val
1884 (add-hook 'org-blocker-hook
1885 'org-block-todo-from-children-or-siblings-or-parent)
1886 (remove-hook 'org-blocker-hook
1887 'org-block-todo-from-children-or-siblings-or-parent)))
1888 :group 'org-todo
1889 :type 'boolean)
1891 (defcustom org-enforce-todo-checkbox-dependencies nil
1892 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1893 When this is nil, checkboxes have no influence on switching TODO states.
1894 When non-nil, you first need to check off all check boxes before the TODO
1895 entry can be switched to DONE.
1896 This variable needs to be set before org.el is loaded, and you need to
1897 restart Emacs after a change to make the change effective. The only way
1898 to change is while Emacs is running is through the customize interface."
1899 :set (lambda (var val)
1900 (set var val)
1901 (if val
1902 (add-hook 'org-blocker-hook
1903 'org-block-todo-from-checkboxes)
1904 (remove-hook 'org-blocker-hook
1905 'org-block-todo-from-checkboxes)))
1906 :group 'org-todo
1907 :type 'boolean)
1909 (defcustom org-treat-insert-todo-heading-as-state-change nil
1910 "Non-nil means, inserting a TODO heading is treated as state change.
1911 So when the command \\[org-insert-todo-heading] is used, state change
1912 logging will apply if appropriate. When nil, the new TODO item will
1913 be inserted directly, and no logging will take place."
1914 :group 'org-todo
1915 :type 'boolean)
1917 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1918 "Non-nil means, switching TODO states with S-cursor counts as state change.
1919 This is the default behavior. However, setting this to nil allows a
1920 convenient way to select a TODO state and bypass any logging associated
1921 with that."
1922 :group 'org-todo
1923 :type 'boolean)
1925 (defcustom org-todo-state-tags-triggers nil
1926 "Tag changes that should be triggered by TODO state changes.
1927 This is a list. Each entry is
1929 (state-change (tag . flag) .......)
1931 State-change can be a string with a state, and empty string to indicate the
1932 state that has no TODO keyword, or it can be one of the symbols `todo'
1933 or `done', meaning any not-done or done state, respectively."
1934 :group 'org-todo
1935 :group 'org-tags
1936 :type '(repeat
1937 (cons (choice :tag "When changing to"
1938 (const :tag "Not-done state" todo)
1939 (const :tag "Done state" done)
1940 (string :tag "State"))
1941 (repeat
1942 (cons :tag "Tag action"
1943 (string :tag "Tag")
1944 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1946 (defcustom org-log-done nil
1947 "Information to record when a task moves to the DONE state.
1949 Possible values are:
1951 nil Don't add anything, just change the keyword
1952 time Add a time stamp to the task
1953 note Prompt for a note and add it with template `org-log-note-headings'
1955 This option can also be set with on a per-file-basis with
1957 #+STARTUP: nologdone
1958 #+STARTUP: logdone
1959 #+STARTUP: lognotedone
1961 You can have local logging settings for a subtree by setting the LOGGING
1962 property to one or more of these keywords."
1963 :group 'org-todo
1964 :group 'org-progress
1965 :type '(choice
1966 (const :tag "No logging" nil)
1967 (const :tag "Record CLOSED timestamp" time)
1968 (const :tag "Record CLOSED timestamp with note." note)))
1970 ;; Normalize old uses of org-log-done.
1971 (cond
1972 ((eq org-log-done t) (setq org-log-done 'time))
1973 ((and (listp org-log-done) (memq 'done org-log-done))
1974 (setq org-log-done 'note)))
1976 (defcustom org-log-reschedule nil
1977 "Information to record when the scheduling date of a tasks is modified.
1979 Possible values are:
1981 nil Don't add anything, just change the date
1982 time Add a time stamp to the task
1983 note Prompt for a note and add it with template `org-log-note-headings'
1985 This option can also be set with on a per-file-basis with
1987 #+STARTUP: nologreschedule
1988 #+STARTUP: logreschedule
1989 #+STARTUP: lognotereschedule"
1990 :group 'org-todo
1991 :group 'org-progress
1992 :type '(choice
1993 (const :tag "No logging" nil)
1994 (const :tag "Record timestamp" time)
1995 (const :tag "Record timestamp with note." note)))
1997 (defcustom org-log-redeadline nil
1998 "Information to record when the deadline date of a tasks is modified.
2000 Possible values are:
2002 nil Don't add anything, just change the date
2003 time Add a time stamp to the task
2004 note Prompt for a note and add it with template `org-log-note-headings'
2006 This option can also be set with on a per-file-basis with
2008 #+STARTUP: nologredeadline
2009 #+STARTUP: logredeadline
2010 #+STARTUP: lognoteredeadline
2012 You can have local logging settings for a subtree by setting the LOGGING
2013 property to one or more of these keywords."
2014 :group 'org-todo
2015 :group 'org-progress
2016 :type '(choice
2017 (const :tag "No logging" nil)
2018 (const :tag "Record timestamp" time)
2019 (const :tag "Record timestamp with note." note)))
2021 (defcustom org-log-note-clock-out nil
2022 "Non-nil means, record a note when clocking out of an item.
2023 This can also be configured on a per-file basis by adding one of
2024 the following lines anywhere in the buffer:
2026 #+STARTUP: lognoteclock-out
2027 #+STARTUP: nolognoteclock-out"
2028 :group 'org-todo
2029 :group 'org-progress
2030 :type 'boolean)
2032 (defcustom org-log-done-with-time t
2033 "Non-nil means, the CLOSED time stamp will contain date and time.
2034 When nil, only the date will be recorded."
2035 :group 'org-progress
2036 :type 'boolean)
2038 (defcustom org-log-note-headings
2039 '((done . "CLOSING NOTE %t")
2040 (state . "State %-12s from %-12S %t")
2041 (note . "Note taken on %t")
2042 (reschedule . "Rescheduled from %S on %t")
2043 (redeadline . "New deadline from %S on %t")
2044 (clock-out . ""))
2045 "Headings for notes added to entries.
2046 The value is an alist, with the car being a symbol indicating the note
2047 context, and the cdr is the heading to be used. The heading may also be the
2048 empty string.
2049 %t in the heading will be replaced by a time stamp.
2050 %s will be replaced by the new TODO state, in double quotes.
2051 %S will be replaced by the old TODO state, in double quotes.
2052 %u will be replaced by the user name.
2053 %U will be replaced by the full user name."
2054 :group 'org-todo
2055 :group 'org-progress
2056 :type '(list :greedy t
2057 (cons (const :tag "Heading when closing an item" done) string)
2058 (cons (const :tag
2059 "Heading when changing todo state (todo sequence only)"
2060 state) string)
2061 (cons (const :tag "Heading when just taking a note" note) string)
2062 (cons (const :tag "Heading when clocking out" clock-out) string)
2063 (cons (const :tag "Heading when rescheduling" reschedule) string)
2064 (cons (const :tag "Heading when changing deadline" redeadline) string)))
2066 (unless (assq 'note org-log-note-headings)
2067 (push '(note . "%t") org-log-note-headings))
2069 (defcustom org-log-into-drawer nil
2070 "Non-nil means, insert state change notes and time stamps into a drawer.
2071 When nil, state changes notes will be inserted after the headline and
2072 any scheduling and clock lines, but not inside a drawer.
2074 The value of this variable should be the name of the drawer to use.
2075 LOGBOOK is proposed at the default drawer for this purpose, you can
2076 also set this to a string to define the drawer of your choice.
2078 A value of t is also allowed, representing \"LOGBOOK\".
2080 If this variable is set, `org-log-state-notes-insert-after-drawers'
2081 will be ignored.
2083 You can set the property LOG_INTO_DRAWER to overrule this setting for
2084 a subtree."
2085 :group 'org-todo
2086 :group 'org-progress
2087 :type '(choice
2088 (const :tag "Not into a drawer" nil)
2089 (const :tag "LOGBOOK" t)
2090 (string :tag "Other")))
2092 (if (fboundp 'defvaralias)
2093 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2095 (defun org-log-into-drawer ()
2096 "Return the value of `org-log-into-drawer', but let properties overrule.
2097 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2098 used instead of the default value."
2099 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2100 (cond
2101 ((or (not p) (equal p "nil")) org-log-into-drawer)
2102 ((equal p "t") "LOGBOOK")
2103 (t p))))
2105 (defcustom org-log-state-notes-insert-after-drawers nil
2106 "Non-nil means, insert state change notes after any drawers in entry.
2107 Only the drawers that *immediately* follow the headline and the
2108 deadline/scheduled line are skipped.
2109 When nil, insert notes right after the heading and perhaps the line
2110 with deadline/scheduling if present.
2112 This variable will have no effect if `org-log-into-drawer' is
2113 set."
2114 :group 'org-todo
2115 :group 'org-progress
2116 :type 'boolean)
2118 (defcustom org-log-states-order-reversed t
2119 "Non-nil means, the latest state change note will be directly after heading.
2120 When nil, the notes will be orderer according to time."
2121 :group 'org-todo
2122 :group 'org-progress
2123 :type 'boolean)
2125 (defcustom org-log-repeat 'time
2126 "Non-nil means, record moving through the DONE state when triggering repeat.
2127 An auto-repeating task is immediately switched back to TODO when
2128 marked DONE. If you are not logging state changes (by adding \"@\"
2129 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2130 record a closing note, there will be no record of the task moving
2131 through DONE. This variable forces taking a note anyway.
2133 nil Don't force a record
2134 time Record a time stamp
2135 note Record a note
2137 This option can also be set with on a per-file-basis with
2139 #+STARTUP: logrepeat
2140 #+STARTUP: lognoterepeat
2141 #+STARTUP: nologrepeat
2143 You can have local logging settings for a subtree by setting the LOGGING
2144 property to one or more of these keywords."
2145 :group 'org-todo
2146 :group 'org-progress
2147 :type '(choice
2148 (const :tag "Don't force a record" nil)
2149 (const :tag "Force recording the DONE state" time)
2150 (const :tag "Force recording a note with the DONE state" note)))
2153 (defgroup org-priorities nil
2154 "Priorities in Org-mode."
2155 :tag "Org Priorities"
2156 :group 'org-todo)
2158 (defcustom org-enable-priority-commands t
2159 "Non-nil means, priority commands are active.
2160 When nil, these commands will be disabled, so that you never accidentally
2161 set a priority."
2162 :group 'org-priorities
2163 :type 'boolean)
2165 (defcustom org-highest-priority ?A
2166 "The highest priority of TODO items. A character like ?A, ?B etc.
2167 Must have a smaller ASCII number than `org-lowest-priority'."
2168 :group 'org-priorities
2169 :type 'character)
2171 (defcustom org-lowest-priority ?C
2172 "The lowest priority of TODO items. A character like ?A, ?B etc.
2173 Must have a larger ASCII number than `org-highest-priority'."
2174 :group 'org-priorities
2175 :type 'character)
2177 (defcustom org-default-priority ?B
2178 "The default priority of TODO items.
2179 This is the priority an item get if no explicit priority is given."
2180 :group 'org-priorities
2181 :type 'character)
2183 (defcustom org-priority-start-cycle-with-default t
2184 "Non-nil means, start with default priority when starting to cycle.
2185 When this is nil, the first step in the cycle will be (depending on the
2186 command used) one higher or lower that the default priority."
2187 :group 'org-priorities
2188 :type 'boolean)
2190 (defgroup org-time nil
2191 "Options concerning time stamps and deadlines in Org-mode."
2192 :tag "Org Time"
2193 :group 'org)
2195 (defcustom org-insert-labeled-timestamps-at-point nil
2196 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2197 When nil, these labeled time stamps are forces into the second line of an
2198 entry, just after the headline. When scheduling from the global TODO list,
2199 the time stamp will always be forced into the second line."
2200 :group 'org-time
2201 :type 'boolean)
2203 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2204 "Formats for `format-time-string' which are used for time stamps.
2205 It is not recommended to change this constant.")
2207 (defcustom org-time-stamp-rounding-minutes '(0 5)
2208 "Number of minutes to round time stamps to.
2209 These are two values, the first applies when first creating a time stamp.
2210 The second applies when changing it with the commands `S-up' and `S-down'.
2211 When changing the time stamp, this means that it will change in steps
2212 of N minutes, as given by the second value.
2214 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2215 numbers should be factors of 60, so for example 5, 10, 15.
2217 When this is larger than 1, you can still force an exact time-stamp by using
2218 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2219 and by using a prefix arg to `S-up/down' to specify the exact number
2220 of minutes to shift."
2221 :group 'org-time
2222 :get '(lambda (var) ; Make sure all entries have 5 elements
2223 (if (integerp (default-value var))
2224 (list (default-value var) 5)
2225 (default-value var)))
2226 :type '(list
2227 (integer :tag "when inserting times")
2228 (integer :tag "when modifying times")))
2230 ;; Normalize old customizations of this variable.
2231 (when (integerp org-time-stamp-rounding-minutes)
2232 (setq org-time-stamp-rounding-minutes
2233 (list org-time-stamp-rounding-minutes
2234 org-time-stamp-rounding-minutes)))
2236 (defcustom org-display-custom-times nil
2237 "Non-nil means, overlay custom formats over all time stamps.
2238 The formats are defined through the variable `org-time-stamp-custom-formats'.
2239 To turn this on on a per-file basis, insert anywhere in the file:
2240 #+STARTUP: customtime"
2241 :group 'org-time
2242 :set 'set-default
2243 :type 'sexp)
2244 (make-variable-buffer-local 'org-display-custom-times)
2246 (defcustom org-time-stamp-custom-formats
2247 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2248 "Custom formats for time stamps. See `format-time-string' for the syntax.
2249 These are overlayed over the default ISO format if the variable
2250 `org-display-custom-times' is set. Time like %H:%M should be at the
2251 end of the second format. The custom formats are also honored by export
2252 commands, if custom time display is turned on at the time of export."
2253 :group 'org-time
2254 :type 'sexp)
2256 (defun org-time-stamp-format (&optional long inactive)
2257 "Get the right format for a time string."
2258 (let ((f (if long (cdr org-time-stamp-formats)
2259 (car org-time-stamp-formats))))
2260 (if inactive
2261 (concat "[" (substring f 1 -1) "]")
2262 f)))
2264 (defcustom org-time-clocksum-format "%d:%02d"
2265 "The format string used when creating CLOCKSUM lines, or when
2266 org-mode generates a time duration."
2267 :group 'org-time
2268 :type 'string)
2270 (defcustom org-time-clocksum-use-fractional nil
2271 "If non-nil, \\[org-clock-display] uses fractional times.
2272 org-mode generates a time duration."
2273 :group 'org-time
2274 :type 'boolean)
2276 (defcustom org-time-clocksum-fractional-format "%.2f"
2277 "The format string used when creating CLOCKSUM lines, or when
2278 org-mode generates a time duration."
2279 :group 'org-time
2280 :type 'string)
2282 (defcustom org-deadline-warning-days 14
2283 "No. of days before expiration during which a deadline becomes active.
2284 This variable governs the display in sparse trees and in the agenda.
2285 When 0 or negative, it means use this number (the absolute value of it)
2286 even if a deadline has a different individual lead time specified.
2288 Custom commands can set this variable in the options section."
2289 :group 'org-time
2290 :group 'org-agenda-daily/weekly
2291 :type 'integer)
2293 (defcustom org-read-date-prefer-future t
2294 "Non-nil means, assume future for incomplete date input from user.
2295 This affects the following situations:
2296 1. The user gives a month but not a year.
2297 For example, if it is april and you enter \"feb 2\", this will be read
2298 as feb 2, *next* year. \"May 5\", however, will be this year.
2299 2. The user gives a day, but no month.
2300 For example, if today is the 15th, and you enter \"3\", Org-mode will
2301 read this as the third of *next* month. However, if you enter \"17\",
2302 it will be considered as *this* month.
2304 If you set this variable to the symbol `time', then also the following
2305 will work:
2307 3. If the user gives a time, but no day. If the time is before now,
2308 to will be interpreted as tomorrow.
2310 Currently none of this works for ISO week specifications.
2312 When this option is nil, the current day, month and year will always be
2313 used as defaults."
2314 :group 'org-time
2315 :type '(choice
2316 (const :tag "Never" nil)
2317 (const :tag "Check month and day" t)
2318 (const :tag "Check month, day, and time" time)))
2320 (defcustom org-read-date-display-live t
2321 "Non-nil means, display current interpretation of date prompt live.
2322 This display will be in an overlay, in the minibuffer."
2323 :group 'org-time
2324 :type 'boolean)
2326 (defcustom org-read-date-popup-calendar t
2327 "Non-nil means, pop up a calendar when prompting for a date.
2328 In the calendar, the date can be selected with mouse-1. However, the
2329 minibuffer will also be active, and you can simply enter the date as well.
2330 When nil, only the minibuffer will be available."
2331 :group 'org-time
2332 :type 'boolean)
2333 (if (fboundp 'defvaralias)
2334 (defvaralias 'org-popup-calendar-for-date-prompt
2335 'org-read-date-popup-calendar))
2337 (defcustom org-read-date-minibuffer-setup-hook nil
2338 "Hook to be used to set up keys for the date/time interface.
2339 Add key definitions to `minibuffer-local-map', which will be a temporary
2340 copy."
2341 :group 'org-time
2342 :type 'hook)
2344 (defcustom org-extend-today-until 0
2345 "The hour when your day really ends. Must be an integer.
2346 This has influence for the following applications:
2347 - When switching the agenda to \"today\". It it is still earlier than
2348 the time given here, the day recognized as TODAY is actually yesterday.
2349 - When a date is read from the user and it is still before the time given
2350 here, the current date and time will be assumed to be yesterday, 23:59.
2351 Also, timestamps inserted in remember templates follow this rule.
2353 IMPORTANT: This is a feature whose implementation is and likely will
2354 remain incomplete. Really, it is only here because past midnight seems to
2355 be the favorite working time of John Wiegley :-)"
2356 :group 'org-time
2357 :type 'integer)
2359 (defcustom org-edit-timestamp-down-means-later nil
2360 "Non-nil means, S-down will increase the time in a time stamp.
2361 When nil, S-up will increase."
2362 :group 'org-time
2363 :type 'boolean)
2365 (defcustom org-calendar-follow-timestamp-change t
2366 "Non-nil means, make the calendar window follow timestamp changes.
2367 When a timestamp is modified and the calendar window is visible, it will be
2368 moved to the new date."
2369 :group 'org-time
2370 :type 'boolean)
2372 (defgroup org-tags nil
2373 "Options concerning tags in Org-mode."
2374 :tag "Org Tags"
2375 :group 'org)
2377 (defcustom org-tag-alist nil
2378 "List of tags allowed in Org-mode files.
2379 When this list is nil, Org-mode will base TAG input on what is already in the
2380 buffer.
2381 The value of this variable is an alist, the car of each entry must be a
2382 keyword as a string, the cdr may be a character that is used to select
2383 that tag through the fast-tag-selection interface.
2384 See the manual for details."
2385 :group 'org-tags
2386 :type '(repeat
2387 (choice
2388 (cons (string :tag "Tag name")
2389 (character :tag "Access char"))
2390 (list :tag "Start radio group"
2391 (const :startgroup)
2392 (option (string :tag "Group description")))
2393 (list :tag "End radio group"
2394 (const :endgroup)
2395 (option (string :tag "Group description")))
2396 (const :tag "New line" (:newline)))))
2398 (defcustom org-tag-persistent-alist nil
2399 "List of tags that will always appear in all Org-mode files.
2400 This is in addition to any in buffer settings or customizations
2401 of `org-tag-alist'.
2402 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2403 The value of this variable is an alist, the car of each entry must be a
2404 keyword as a string, the cdr may be a character that is used to select
2405 that tag through the fast-tag-selection interface.
2406 See the manual for details.
2407 To disable these tags on a per-file basis, insert anywhere in the file:
2408 #+STARTUP: noptag"
2409 :group 'org-tags
2410 :type '(repeat
2411 (choice
2412 (cons (string :tag "Tag name")
2413 (character :tag "Access char"))
2414 (const :tag "Start radio group" (:startgroup))
2415 (const :tag "End radio group" (:endgroup))
2416 (const :tag "New line" (:newline)))))
2418 (defvar org-file-tags nil
2419 "List of tags that can be inherited by all entries in the file.
2420 The tags will be inherited if the variable `org-use-tag-inheritance'
2421 says they should be.
2422 This variable is populated from #+FILETAGS lines.")
2424 (defcustom org-use-fast-tag-selection 'auto
2425 "Non-nil means, use fast tag selection scheme.
2426 This is a special interface to select and deselect tags with single keys.
2427 When nil, fast selection is never used.
2428 When the symbol `auto', fast selection is used if and only if selection
2429 characters for tags have been configured, either through the variable
2430 `org-tag-alist' or through a #+TAGS line in the buffer.
2431 When t, fast selection is always used and selection keys are assigned
2432 automatically if necessary."
2433 :group 'org-tags
2434 :type '(choice
2435 (const :tag "Always" t)
2436 (const :tag "Never" nil)
2437 (const :tag "When selection characters are configured" 'auto)))
2439 (defcustom org-fast-tag-selection-single-key nil
2440 "Non-nil means, fast tag selection exits after first change.
2441 When nil, you have to press RET to exit it.
2442 During fast tag selection, you can toggle this flag with `C-c'.
2443 This variable can also have the value `expert'. In this case, the window
2444 displaying the tags menu is not even shown, until you press C-c again."
2445 :group 'org-tags
2446 :type '(choice
2447 (const :tag "No" nil)
2448 (const :tag "Yes" t)
2449 (const :tag "Expert" expert)))
2451 (defvar org-fast-tag-selection-include-todo nil
2452 "Non-nil means, fast tags selection interface will also offer TODO states.
2453 This is an undocumented feature, you should not rely on it.")
2455 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2456 "The column to which tags should be indented in a headline.
2457 If this number is positive, it specifies the column. If it is negative,
2458 it means that the tags should be flushright to that column. For example,
2459 -80 works well for a normal 80 character screen."
2460 :group 'org-tags
2461 :type 'integer)
2463 (defcustom org-auto-align-tags t
2464 "Non-nil means, realign tags after pro/demotion of TODO state change.
2465 These operations change the length of a headline and therefore shift
2466 the tags around. With this options turned on, after each such operation
2467 the tags are again aligned to `org-tags-column'."
2468 :group 'org-tags
2469 :type 'boolean)
2471 (defcustom org-use-tag-inheritance t
2472 "Non-nil means, tags in levels apply also for sublevels.
2473 When nil, only the tags directly given in a specific line apply there.
2474 This may also be a list of tags that should be inherited, or a regexp that
2475 matches tags that should be inherited. Additional control is possible
2476 with the variable `org-tags-exclude-from-inheritance' which gives an
2477 explicit list of tags to be excluded from inheritance., even if the value of
2478 `org-use-tag-inheritance' would select it for inheritance.
2480 If this option is t, a match early-on in a tree can lead to a large
2481 number of matches in the subtree when constructing the agenda or creating
2482 a sparse tree. If you only want to see the first match in a tree during
2483 a search, check out the variable `org-tags-match-list-sublevels'."
2484 :group 'org-tags
2485 :type '(choice
2486 (const :tag "Not" nil)
2487 (const :tag "Always" t)
2488 (repeat :tag "Specific tags" (string :tag "Tag"))
2489 (regexp :tag "Tags matched by regexp")))
2491 (defcustom org-tags-exclude-from-inheritance nil
2492 "List of tags that should never be inherited.
2493 This is a way to exclude a few tags from inheritance. For way to do
2494 the opposite, to actively allow inheritance for selected tags,
2495 see the variable `org-use-tag-inheritance'."
2496 :group 'org-tags
2497 :type '(repeat (string :tag "Tag")))
2499 (defun org-tag-inherit-p (tag)
2500 "Check if TAG is one that should be inherited."
2501 (cond
2502 ((member tag org-tags-exclude-from-inheritance) nil)
2503 ((eq org-use-tag-inheritance t) t)
2504 ((not org-use-tag-inheritance) nil)
2505 ((stringp org-use-tag-inheritance)
2506 (string-match org-use-tag-inheritance tag))
2507 ((listp org-use-tag-inheritance)
2508 (member tag org-use-tag-inheritance))
2509 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2511 (defcustom org-tags-match-list-sublevels t
2512 "Non-nil means list also sublevels of headlines matching a search.
2513 This variable applies to tags/property searches, and also to stuck
2514 projects because this search is based on a tags match as well.
2516 When set to the symbol `indented', sublevels are indented with
2517 leading dots.
2519 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2520 the sublevels of a headline matching a tag search often also match
2521 the same search. Listing all of them can create very long lists.
2522 Setting this variable to nil causes subtrees of a match to be skipped.
2524 This variable is semi-obsolete and probably should always be true. It
2525 is better to limit inheritance to certain tags using the variables
2526 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2527 :group 'org-tags
2528 :type '(choice
2529 (const :tag "No, don't list them" nil)
2530 (const :tag "Yes, do list them" t)
2531 (const :tag "List them, indented with leading dots" indented)))
2533 (defcustom org-tags-sort-function nil
2534 "When set, tags are sorted using this function as a comparator"
2535 :group 'org-tags
2536 :type '(choice
2537 (const :tag "No sorting" nil)
2538 (const :tag "Alphabetical" string<)
2539 (const :tag "Reverse alphabetical" string>)
2540 (function :tag "Custom function" nil)))
2542 (defvar org-tags-history nil
2543 "History of minibuffer reads for tags.")
2544 (defvar org-last-tags-completion-table nil
2545 "The last used completion table for tags.")
2546 (defvar org-after-tags-change-hook nil
2547 "Hook that is run after the tags in a line have changed.")
2549 (defgroup org-properties nil
2550 "Options concerning properties in Org-mode."
2551 :tag "Org Properties"
2552 :group 'org)
2554 (defcustom org-property-format "%-10s %s"
2555 "How property key/value pairs should be formatted by `indent-line'.
2556 When `indent-line' hits a property definition, it will format the line
2557 according to this format, mainly to make sure that the values are
2558 lined-up with respect to each other."
2559 :group 'org-properties
2560 :type 'string)
2562 (defcustom org-use-property-inheritance nil
2563 "Non-nil means, properties apply also for sublevels.
2565 This setting is chiefly used during property searches. Turning it on can
2566 cause significant overhead when doing a search, which is why it is not
2567 on by default.
2569 When nil, only the properties directly given in the current entry count.
2570 When t, every property is inherited. The value may also be a list of
2571 properties that should have inheritance, or a regular expression matching
2572 properties that should be inherited.
2574 However, note that some special properties use inheritance under special
2575 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2576 and the properties ending in \"_ALL\" when they are used as descriptor
2577 for valid values of a property.
2579 Note for programmers:
2580 When querying an entry with `org-entry-get', you can control if inheritance
2581 should be used. By default, `org-entry-get' looks only at the local
2582 properties. You can request inheritance by setting the inherit argument
2583 to t (to force inheritance) or to `selective' (to respect the setting
2584 in this variable)."
2585 :group 'org-properties
2586 :type '(choice
2587 (const :tag "Not" nil)
2588 (const :tag "Always" t)
2589 (repeat :tag "Specific properties" (string :tag "Property"))
2590 (regexp :tag "Properties matched by regexp")))
2592 (defun org-property-inherit-p (property)
2593 "Check if PROPERTY is one that should be inherited."
2594 (cond
2595 ((eq org-use-property-inheritance t) t)
2596 ((not org-use-property-inheritance) nil)
2597 ((stringp org-use-property-inheritance)
2598 (string-match org-use-property-inheritance property))
2599 ((listp org-use-property-inheritance)
2600 (member property org-use-property-inheritance))
2601 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2603 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2604 "The default column format, if no other format has been defined.
2605 This variable can be set on the per-file basis by inserting a line
2607 #+COLUMNS: %25ITEM ....."
2608 :group 'org-properties
2609 :type 'string)
2611 (defcustom org-columns-ellipses ".."
2612 "The ellipses to be used when a field in column view is truncated.
2613 When this is the empty string, as many characters as possible are shown,
2614 but then there will be no visual indication that the field has been truncated.
2615 When this is a string of length N, the last N characters of a truncated
2616 field are replaced by this string. If the column is narrower than the
2617 ellipses string, only part of the ellipses string will be shown."
2618 :group 'org-properties
2619 :type 'string)
2621 (defcustom org-columns-modify-value-for-display-function nil
2622 "Function that modifies values for display in column view.
2623 For example, it can be used to cut out a certain part from a time stamp.
2624 The function must take 2 arguments:
2626 column-title The title of the column (*not* the property name)
2627 value The value that should be modified.
2629 The function should return the value that should be displayed,
2630 or nil if the normal value should be used."
2631 :group 'org-properties
2632 :type 'function)
2634 (defcustom org-effort-property "Effort"
2635 "The property that is being used to keep track of effort estimates.
2636 Effort estimates given in this property need to have the format H:MM."
2637 :group 'org-properties
2638 :group 'org-progress
2639 :type '(string :tag "Property"))
2641 (defconst org-global-properties-fixed
2642 '(("VISIBILITY_ALL" . "folded children content all")
2643 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2644 "List of property/value pairs that can be inherited by any entry.
2646 These are fixed values, for the preset properties. The user variable
2647 that can be used to add to this list is `org-global-properties'.
2649 The entries in this list are cons cells where the car is a property
2650 name and cdr is a string with the value. If the value represents
2651 multiple items like an \"_ALL\" property, separate the items by
2652 spaces.")
2654 (defcustom org-global-properties nil
2655 "List of property/value pairs that can be inherited by any entry.
2657 This list will be combined with the constant `org-global-properties-fixed'.
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.
2662 You can set buffer-local values for the same purpose in the variable
2663 `org-file-properties' this by adding lines like
2665 #+PROPERTY: NAME VALUE"
2666 :group 'org-properties
2667 :type '(repeat
2668 (cons (string :tag "Property")
2669 (string :tag "Value"))))
2671 (defvar org-file-properties nil
2672 "List of property/value pairs that can be inherited by any entry.
2673 Valid for the current buffer.
2674 This variable is populated from #+PROPERTY lines.")
2675 (make-variable-buffer-local 'org-file-properties)
2677 (defgroup org-agenda nil
2678 "Options concerning agenda views in Org-mode."
2679 :tag "Org Agenda"
2680 :group 'org)
2682 (defvar org-category nil
2683 "Variable used by org files to set a category for agenda display.
2684 Such files should use a file variable to set it, for example
2686 # -*- mode: org; org-category: \"ELisp\"
2688 or contain a special line
2690 #+CATEGORY: ELisp
2692 If the file does not specify a category, then file's base name
2693 is used instead.")
2694 (make-variable-buffer-local 'org-category)
2695 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2697 (defcustom org-agenda-files nil
2698 "The files to be used for agenda display.
2699 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2700 \\[org-remove-file]. You can also use customize to edit the list.
2702 If an entry is a directory, all files in that directory that are matched by
2703 `org-agenda-file-regexp' will be part of the file list.
2705 If the value of the variable is not a list but a single file name, then
2706 the list of agenda files is actually stored and maintained in that file, one
2707 agenda file per line."
2708 :group 'org-agenda
2709 :type '(choice
2710 (repeat :tag "List of files and directories" file)
2711 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2713 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2714 "Regular expression to match files for `org-agenda-files'.
2715 If any element in the list in that variable contains a directory instead
2716 of a normal file, all files in that directory that are matched by this
2717 regular expression will be included."
2718 :group 'org-agenda
2719 :type 'regexp)
2721 (defcustom org-agenda-text-search-extra-files nil
2722 "List of extra files to be searched by text search commands.
2723 These files will be search in addition to the agenda files by the
2724 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2725 Note that these files will only be searched for text search commands,
2726 not for the other agenda views like todo lists, tag searches or the weekly
2727 agenda. This variable is intended to list notes and possibly archive files
2728 that should also be searched by these two commands.
2729 In fact, if the first element in the list is the symbol `agenda-archives',
2730 than all archive files of all agenda files will be added to the search
2731 scope."
2732 :group 'org-agenda
2733 :type '(set :greedy t
2734 (const :tag "Agenda Archives" agenda-archives)
2735 (repeat :inline t (file))))
2737 (if (fboundp 'defvaralias)
2738 (defvaralias 'org-agenda-multi-occur-extra-files
2739 'org-agenda-text-search-extra-files))
2741 (defcustom org-agenda-skip-unavailable-files nil
2742 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2743 A nil value means to remove them, after a query, from the list."
2744 :group 'org-agenda
2745 :type 'boolean)
2747 (defcustom org-calendar-to-agenda-key [?c]
2748 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2749 The command `org-calendar-goto-agenda' will be bound to this key. The
2750 default is the character `c' because then `c' can be used to switch back and
2751 forth between agenda and calendar."
2752 :group 'org-agenda
2753 :type 'sexp)
2755 (defcustom org-calendar-agenda-action-key [?k]
2756 "The key to be installed in `calendar-mode-map' for agenda-action.
2757 The command `org-agenda-action' will be bound to this key. The
2758 default is the character `k' because we use the same key in the agenda."
2759 :group 'org-agenda
2760 :type 'sexp)
2762 (defcustom org-calendar-insert-diary-entry-key [?i]
2763 "The key to be installed in `calendar-mode-map' for adding diary entries.
2764 This option is irrelevant until `org-agenda-diary-file' has been configured
2765 to point to an Org-mode file. When that is the case, the command
2766 `org-agenda-diary-entry' will be bound to the key given here, by default
2767 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2768 if you want to continue doing this, you need to change this to a defferent
2769 key."
2770 :group 'org-agenda
2771 :type 'sexp)
2773 (defcustom org-agenda-diary-file 'diary-file
2774 "File to which to add new entries with the `i' key in agenda and calendar.
2775 When this is the symbol `diary-file', the functionality in the Emacs
2776 calendar will be used to add entries to the `diary-file'. But when this
2777 points to a file, `org-agenda-diary-entry' will be used instead."
2778 :group 'org-agenda
2779 :type '(choice
2780 (const :tag "The standard Emacs diary file" diary-file)
2781 (file :tag "Special Org file diary entries")))
2783 (eval-after-load "calendar"
2784 '(progn
2785 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2786 'org-calendar-goto-agenda)
2787 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2788 'org-agenda-action)
2789 (add-hook 'calendar-mode-hook
2790 (lambda ()
2791 (unless (eq org-agenda-diary-file 'diary-file)
2792 (define-key calendar-mode-map
2793 org-calendar-insert-diary-entry-key
2794 'org-agenda-diary-entry))))))
2796 (defgroup org-latex nil
2797 "Options for embedding LaTeX code into Org-mode."
2798 :tag "Org LaTeX"
2799 :group 'org)
2801 (defcustom org-format-latex-options
2802 '(:foreground default :background default :scale 1.0
2803 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2804 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2805 "Options for creating images from LaTeX fragments.
2806 This is a property list with the following properties:
2807 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2808 `default' means use the foreground of the default face.
2809 :background the background color, or \"Transparent\".
2810 `default' means use the background of the default face.
2811 :scale a scaling factor for the size of the images.
2812 :html-foreground, :html-background, :html-scale
2813 the same numbers for HTML export.
2814 :matchers a list indicating which matchers should be used to
2815 find LaTeX fragments. Valid members of this list are:
2816 \"begin\" find environments
2817 \"$1\" find single characters surrounded by $.$
2818 \"$\" find math expressions surrounded by $...$
2819 \"$$\" find math expressions surrounded by $$....$$
2820 \"\\(\" find math expressions surrounded by \\(...\\)
2821 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2822 :group 'org-latex
2823 :type 'plist)
2825 (defcustom org-format-latex-header "\\documentclass{article}
2826 \\usepackage{amssymb}
2827 \\usepackage[usenames]{color}
2828 \\usepackage{amsmath}
2829 \\usepackage{latexsym}
2830 \\usepackage[mathscr]{eucal}
2831 \\pagestyle{empty} % do not remove
2832 % The settings below are copied from fullpage.sty
2833 \\setlength{\\textwidth}{\\paperwidth}
2834 \\addtolength{\\textwidth}{-3cm}
2835 \\setlength{\\oddsidemargin}{1.5cm}
2836 \\addtolength{\\oddsidemargin}{-2.54cm}
2837 \\setlength{\\evensidemargin}{\\oddsidemargin}
2838 \\setlength{\\textheight}{\\paperheight}
2839 \\addtolength{\\textheight}{-\\headheight}
2840 \\addtolength{\\textheight}{-\\headsep}
2841 \\addtolength{\\textheight}{-\\footskip}
2842 \\addtolength{\\textheight}{-3cm}
2843 \\setlength{\\topmargin}{1.5cm}
2844 \\addtolength{\\topmargin}{-2.54cm}"
2845 "The document header used for processing LaTeX fragments.
2846 It is imperative that this header make sure that no page number
2847 appears on the page."
2848 :group 'org-latex
2849 :type 'string)
2852 (defgroup org-font-lock nil
2853 "Font-lock settings for highlighting in Org-mode."
2854 :tag "Org Font Lock"
2855 :group 'org)
2857 (defcustom org-level-color-stars-only nil
2858 "Non-nil means fontify only the stars in each headline.
2859 When nil, the entire headline is fontified.
2860 Changing it requires restart of `font-lock-mode' to become effective
2861 also in regions already fontified."
2862 :group 'org-font-lock
2863 :type 'boolean)
2865 (defcustom org-hide-leading-stars nil
2866 "Non-nil means, hide the first N-1 stars in a headline.
2867 This works by using the face `org-hide' for these stars. This
2868 face is white for a light background, and black for a dark
2869 background. You may have to customize the face `org-hide' to
2870 make this work.
2871 Changing it requires restart of `font-lock-mode' to become effective
2872 also in regions already fontified.
2873 You may also set this on a per-file basis by adding one of the following
2874 lines to the buffer:
2876 #+STARTUP: hidestars
2877 #+STARTUP: showstars"
2878 :group 'org-font-lock
2879 :type 'boolean)
2881 (defcustom org-fontify-done-headline nil
2882 "Non-nil means, change the face of a headline if it is marked DONE.
2883 Normally, only the TODO/DONE keyword indicates the state of a headline.
2884 When this is non-nil, the headline after the keyword is set to the
2885 `org-headline-done' as an additional indication."
2886 :group 'org-font-lock
2887 :type 'boolean)
2889 (defcustom org-fontify-emphasized-text t
2890 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2891 Changing this variable requires a restart of Emacs to take effect."
2892 :group 'org-font-lock
2893 :type 'boolean)
2895 (defcustom org-fontify-whole-heading-line nil
2896 "Non-nil means fontify the whole line for headings.
2897 This is useful when setting a background color for the
2898 org-leve-* faces."
2899 :group 'org-font-lock
2900 :type 'boolean)
2902 (defcustom org-highlight-latex-fragments-and-specials nil
2903 "Non-nil means, fontify what is treated specially by the exporters."
2904 :group 'org-font-lock
2905 :type 'boolean)
2907 (defcustom org-hide-emphasis-markers nil
2908 "Non-nil mean font-lock should hide the emphasis marker characters."
2909 :group 'org-font-lock
2910 :type 'boolean)
2912 (defvar org-emph-re nil
2913 "Regular expression for matching emphasis.")
2914 (defvar org-verbatim-re nil
2915 "Regular expression for matching verbatim text.")
2916 (defvar org-emphasis-regexp-components) ; defined just below
2917 (defvar org-emphasis-alist) ; defined just below
2918 (defun org-set-emph-re (var val)
2919 "Set variable and compute the emphasis regular expression."
2920 (set var val)
2921 (when (and (boundp 'org-emphasis-alist)
2922 (boundp 'org-emphasis-regexp-components)
2923 org-emphasis-alist org-emphasis-regexp-components)
2924 (let* ((e org-emphasis-regexp-components)
2925 (pre (car e))
2926 (post (nth 1 e))
2927 (border (nth 2 e))
2928 (body (nth 3 e))
2929 (nl (nth 4 e))
2930 (body1 (concat body "*?"))
2931 (markers (mapconcat 'car org-emphasis-alist ""))
2932 (vmarkers (mapconcat
2933 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2934 org-emphasis-alist "")))
2935 ;; make sure special characters appear at the right position in the class
2936 (if (string-match "\\^" markers)
2937 (setq markers (concat (replace-match "" t t markers) "^")))
2938 (if (string-match "-" markers)
2939 (setq markers (concat (replace-match "" t t markers) "-")))
2940 (if (string-match "\\^" vmarkers)
2941 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2942 (if (string-match "-" vmarkers)
2943 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2944 (if (> nl 0)
2945 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2946 (int-to-string nl) "\\}")))
2947 ;; Make the regexp
2948 (setq org-emph-re
2949 (concat "\\([" pre "]\\|^\\)"
2950 "\\("
2951 "\\([" markers "]\\)"
2952 "\\("
2953 "[^" border "]\\|"
2954 "[^" border "]"
2955 body1
2956 "[^" border "]"
2957 "\\)"
2958 "\\3\\)"
2959 "\\([" post "]\\|$\\)"))
2960 (setq org-verbatim-re
2961 (concat "\\([" pre "]\\|^\\)"
2962 "\\("
2963 "\\([" vmarkers "]\\)"
2964 "\\("
2965 "[^" border "]\\|"
2966 "[^" border "]"
2967 body1
2968 "[^" border "]"
2969 "\\)"
2970 "\\3\\)"
2971 "\\([" post "]\\|$\\)")))))
2973 (defcustom org-emphasis-regexp-components
2974 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2975 "Components used to build the regular expression for emphasis.
2976 This is a list with 6 entries. Terminology: In an emphasis string
2977 like \" *strong word* \", we call the initial space PREMATCH, the final
2978 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2979 and \"trong wor\" is the body. The different components in this variable
2980 specify what is allowed/forbidden in each part:
2982 pre Chars allowed as prematch. Beginning of line will be allowed too.
2983 post Chars allowed as postmatch. End of line will be allowed too.
2984 border The chars *forbidden* as border characters.
2985 body-regexp A regexp like \".\" to match a body character. Don't use
2986 non-shy groups here, and don't allow newline here.
2987 newline The maximum number of newlines allowed in an emphasis exp.
2989 Use customize to modify this, or restart Emacs after changing it."
2990 :group 'org-font-lock
2991 :set 'org-set-emph-re
2992 :type '(list
2993 (sexp :tag "Allowed chars in pre ")
2994 (sexp :tag "Allowed chars in post ")
2995 (sexp :tag "Forbidden chars in border ")
2996 (sexp :tag "Regexp for body ")
2997 (integer :tag "number of newlines allowed")
2998 (option (boolean :tag "Please ignore this button"))))
3000 (defcustom org-emphasis-alist
3001 `(("*" bold "<b>" "</b>")
3002 ("/" italic "<i>" "</i>")
3003 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3004 ("=" org-code "<code>" "</code>" verbatim)
3005 ("~" org-verbatim "<code>" "</code>" verbatim)
3006 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3007 "<del>" "</del>")
3009 "Special syntax for emphasized text.
3010 Text starting and ending with a special character will be emphasized, for
3011 example *bold*, _underlined_ and /italic/. This variable sets the marker
3012 characters, the face to be used by font-lock for highlighting in Org-mode
3013 Emacs buffers, and the HTML tags to be used for this.
3014 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3015 Use customize to modify this, or restart Emacs after changing it."
3016 :group 'org-font-lock
3017 :set 'org-set-emph-re
3018 :type '(repeat
3019 (list
3020 (string :tag "Marker character")
3021 (choice
3022 (face :tag "Font-lock-face")
3023 (plist :tag "Face property list"))
3024 (string :tag "HTML start tag")
3025 (string :tag "HTML end tag")
3026 (option (const verbatim)))))
3028 (defvar org-protecting-blocks
3029 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3030 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3031 This is needed for font-lock setup.")
3033 ;;; Miscellaneous options
3035 (defgroup org-completion nil
3036 "Completion in Org-mode."
3037 :tag "Org Completion"
3038 :group 'org)
3040 (defcustom org-completion-use-ido nil
3041 "Non-nil means, use ido completion wherever possible.
3042 Note that `ido-mode' must be active for this variable to be relevant.
3043 If you decide to turn this variable on, you might well want to turn off
3044 `org-outline-path-complete-in-steps'.
3045 See also `org-completion-use-iswitchb'."
3046 :group 'org-completion
3047 :type 'boolean)
3049 (defcustom org-completion-use-iswitchb nil
3050 "Non-nil means, use iswitchb completion wherever possible.
3051 Note that `iswitchb-mode' must be active for this variable to be relevant.
3052 If you decide to turn this variable on, you might well want to turn off
3053 `org-outline-path-complete-in-steps'.
3054 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
3055 :group 'org-completion
3056 :type 'boolean)
3058 (defcustom org-completion-fallback-command 'hippie-expand
3059 "The expansion command called by \\[org-complete] in normal context.
3060 Normal means, no org-mode-specific context."
3061 :group 'org-completion
3062 :type 'function)
3064 ;;; Functions and variables from ther packages
3065 ;; Declared here to avoid compiler warnings
3067 ;; XEmacs only
3068 (defvar outline-mode-menu-heading)
3069 (defvar outline-mode-menu-show)
3070 (defvar outline-mode-menu-hide)
3071 (defvar zmacs-regions) ; XEmacs regions
3073 ;; Emacs only
3074 (defvar mark-active)
3076 ;; Various packages
3077 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3078 (declare-function calendar-forward-day "cal-move" (arg))
3079 (declare-function calendar-goto-date "cal-move" (date))
3080 (declare-function calendar-goto-today "cal-move" ())
3081 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3082 (defvar calc-embedded-close-formula)
3083 (defvar calc-embedded-open-formula)
3084 (declare-function cdlatex-tab "ext:cdlatex" ())
3085 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3086 (defvar font-lock-unfontify-region-function)
3087 (declare-function iswitchb-read-buffer "iswitchb"
3088 (prompt &optional default require-match start matches-set))
3089 (defvar iswitchb-temp-buflist)
3090 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3091 (defvar org-agenda-tags-todo-honor-ignore-options)
3092 (declare-function org-agenda-skip "org-agenda" ())
3093 (declare-function org-format-agenda-item "org-agenda"
3094 (extra txt &optional category tags dotime noprefix remove-re))
3095 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3096 (declare-function org-agenda-change-all-lines "org-agenda"
3097 (newhead hdmarker &optional fixface just-this))
3098 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3099 (declare-function org-agenda-maybe-redo "org-agenda" ())
3100 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3101 (beg end))
3102 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3103 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3104 "org-agenda" (&optional end))
3105 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3106 (declare-function org-indent-mode "org-indent" (&optional arg))
3107 (declare-function parse-time-string "parse-time" (string))
3108 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3109 (defvar remember-data-file)
3110 (defvar texmathp-why)
3111 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3112 (declare-function table--at-cell-p "table" (position &optional object at-column))
3114 (defvar w3m-current-url)
3115 (defvar w3m-current-title)
3117 (defvar org-latex-regexps)
3119 ;;; Autoload and prepare some org modules
3121 ;; Some table stuff that needs to be defined here, because it is used
3122 ;; by the functions setting up org-mode or checking for table context.
3124 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3125 "Detects an org-type or table-type table.")
3126 (defconst org-table-line-regexp "^[ \t]*|"
3127 "Detects an org-type table line.")
3128 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3129 "Detects an org-type table line.")
3130 (defconst org-table-hline-regexp "^[ \t]*|-"
3131 "Detects an org-type table hline.")
3132 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3133 "Detects a table-type table hline.")
3134 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3135 "Searching from within a table (any type) this finds the first line
3136 outside the table.")
3138 ;; Autoload the functions in org-table.el that are needed by functions here.
3140 (eval-and-compile
3141 (org-autoload "org-table"
3142 '(org-table-align org-table-begin org-table-blank-field
3143 org-table-convert org-table-convert-region org-table-copy-down
3144 org-table-copy-region org-table-create
3145 org-table-create-or-convert-from-region
3146 org-table-create-with-table.el org-table-current-dline
3147 org-table-cut-region org-table-delete-column org-table-edit-field
3148 org-table-edit-formulas org-table-end org-table-eval-formula
3149 org-table-export org-table-field-info
3150 org-table-get-stored-formulas org-table-goto-column
3151 org-table-hline-and-move org-table-import org-table-insert-column
3152 org-table-insert-hline org-table-insert-row org-table-iterate
3153 org-table-justify-field-maybe org-table-kill-row
3154 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3155 org-table-move-column org-table-move-column-left
3156 org-table-move-column-right org-table-move-row
3157 org-table-move-row-down org-table-move-row-up
3158 org-table-next-field org-table-next-row org-table-paste-rectangle
3159 org-table-previous-field org-table-recalculate
3160 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3161 org-table-toggle-coordinate-overlays
3162 org-table-toggle-formula-debugger org-table-wrap-region
3163 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3165 (defun org-at-table-p (&optional table-type)
3166 "Return t if the cursor is inside an org-type table.
3167 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3168 (if org-enable-table-editor
3169 (save-excursion
3170 (beginning-of-line 1)
3171 (looking-at (if table-type org-table-any-line-regexp
3172 org-table-line-regexp)))
3173 nil))
3174 (defsubst org-table-p () (org-at-table-p))
3176 (defun org-at-table.el-p ()
3177 "Return t if and only if we are at a table.el table."
3178 (and (org-at-table-p 'any)
3179 (save-excursion
3180 (goto-char (org-table-begin 'any))
3181 (looking-at org-table1-hline-regexp))))
3182 (defun org-table-recognize-table.el ()
3183 "If there is a table.el table nearby, recognize it and move into it."
3184 (if org-table-tab-recognizes-table.el
3185 (if (org-at-table.el-p)
3186 (progn
3187 (beginning-of-line 1)
3188 (if (looking-at org-table-dataline-regexp)
3190 (if (looking-at org-table1-hline-regexp)
3191 (progn
3192 (beginning-of-line 2)
3193 (if (looking-at org-table-any-border-regexp)
3194 (beginning-of-line -1)))))
3195 (if (re-search-forward "|" (org-table-end t) t)
3196 (progn
3197 (require 'table)
3198 (if (table--at-cell-p (point))
3200 (message "recognizing table.el table...")
3201 (table-recognize-table)
3202 (message "recognizing table.el table...done")))
3203 (error "This should not happen..."))
3205 nil)
3206 nil))
3208 (defun org-at-table-hline-p ()
3209 "Return t if the cursor is inside a hline in a table."
3210 (if org-enable-table-editor
3211 (save-excursion
3212 (beginning-of-line 1)
3213 (looking-at org-table-hline-regexp))
3214 nil))
3216 (defvar org-table-clean-did-remove-column nil)
3218 (defun org-table-map-tables (function)
3219 "Apply FUNCTION to the start of all tables in the buffer."
3220 (save-excursion
3221 (save-restriction
3222 (widen)
3223 (goto-char (point-min))
3224 (while (re-search-forward org-table-any-line-regexp nil t)
3225 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3226 (beginning-of-line 1)
3227 (when (looking-at org-table-line-regexp)
3228 (save-excursion (funcall function))
3229 (or (looking-at org-table-line-regexp)
3230 (forward-char 1)))
3231 (re-search-forward org-table-any-border-regexp nil 1))))
3232 (message "Mapping tables: done"))
3234 ;; Declare and autoload functions from org-exp.el & Co
3236 (declare-function org-default-export-plist "org-exp")
3237 (declare-function org-infile-export-plist "org-exp")
3238 (declare-function org-get-current-options "org-exp")
3239 (eval-and-compile
3240 (org-autoload "org-exp"
3241 '(org-export org-export-visible
3242 org-insert-export-options-template
3243 org-table-clean-before-export))
3244 (org-autoload "org-ascii"
3245 '(org-export-as-ascii org-export-ascii-preprocess
3246 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3247 org-export-region-as-ascii))
3248 (org-autoload "org-html"
3249 '(org-export-as-html-and-open
3250 org-export-as-html-batch org-export-as-html-to-buffer
3251 org-replace-region-by-html org-export-region-as-html
3252 org-export-as-html))
3253 (org-autoload "org-icalendar"
3254 '(org-export-icalendar-this-file
3255 org-export-icalendar-all-agenda-files
3256 org-export-icalendar-combine-agenda-files))
3257 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3259 ;; Declare and autoload functions from org-agenda.el
3261 (eval-and-compile
3262 (org-autoload "org-agenda"
3263 '(org-agenda org-agenda-list org-search-view
3264 org-todo-list org-tags-view org-agenda-list-stuck-projects
3265 org-diary org-agenda-to-appt
3266 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3268 ;; Autoload org-remember
3270 (eval-and-compile
3271 (org-autoload "org-remember"
3272 '(org-remember-insinuate org-remember-annotation
3273 org-remember-apply-template org-remember org-remember-handler)))
3275 ;; Autoload org-clock.el
3278 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3279 (beg end))
3280 (declare-function org-clock-update-mode-line "org-clock" ())
3281 (declare-function org-resolve-clocks "org-clock"
3282 (&optional also-non-dangling-p prompt last-valid))
3283 (defvar org-clock-start-time)
3284 (defvar org-clock-marker (make-marker)
3285 "Marker recording the last clock-in.")
3286 (defvar org-clock-hd-marker (make-marker)
3287 "Marker recording the last clock-in, but the headline position.")
3288 (defvar org-clock-heading ""
3289 "The heading of the current clock entry.")
3290 (defun org-clock-is-active ()
3291 "Return non-nil if clock is currently running.
3292 The return value is actually the clock marker."
3293 (marker-buffer org-clock-marker))
3295 (eval-and-compile
3296 (org-autoload
3297 "org-clock"
3298 '(org-clock-in org-clock-out org-clock-cancel
3299 org-clock-goto org-clock-sum org-clock-display
3300 org-clock-remove-overlays org-clock-report
3301 org-clocktable-shift org-dblock-write:clocktable
3302 org-get-clocktable org-resolve-clocks)))
3304 (defun org-clock-update-time-maybe ()
3305 "If this is a CLOCK line, update it and return t.
3306 Otherwise, return nil."
3307 (interactive)
3308 (save-excursion
3309 (beginning-of-line 1)
3310 (skip-chars-forward " \t")
3311 (when (looking-at org-clock-string)
3312 (let ((re (concat "[ \t]*" org-clock-string
3313 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3314 "\\([ \t]*=>.*\\)?\\)?"))
3315 ts te h m s neg)
3316 (cond
3317 ((not (looking-at re))
3318 nil)
3319 ((not (match-end 2))
3320 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3321 (> org-clock-marker (point))
3322 (<= org-clock-marker (point-at-eol)))
3323 ;; The clock is running here
3324 (setq org-clock-start-time
3325 (apply 'encode-time
3326 (org-parse-time-string (match-string 1))))
3327 (org-clock-update-mode-line)))
3329 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3330 (end-of-line 1)
3331 (setq ts (match-string 1)
3332 te (match-string 3))
3333 (setq s (- (org-float-time
3334 (apply 'encode-time (org-parse-time-string te)))
3335 (org-float-time
3336 (apply 'encode-time (org-parse-time-string ts))))
3337 neg (< s 0)
3338 s (abs s)
3339 h (floor (/ s 3600))
3340 s (- s (* 3600 h))
3341 m (floor (/ s 60))
3342 s (- s (* 60 s)))
3343 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3344 t))))))
3346 (defun org-check-running-clock ()
3347 "Check if the current buffer contains the running clock.
3348 If yes, offer to stop it and to save the buffer with the changes."
3349 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3350 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3351 (buffer-name))))
3352 (org-clock-out)
3353 (when (y-or-n-p "Save changed buffer?")
3354 (save-buffer))))
3356 (defun org-clocktable-try-shift (dir n)
3357 "Check if this line starts a clock table, if yes, shift the time block."
3358 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3359 (org-clocktable-shift dir n)))
3361 ;; Autoload org-timer.el
3363 (eval-and-compile
3364 (org-autoload
3365 "org-timer"
3366 '(org-timer-start org-timer org-timer-item
3367 org-timer-change-times-in-region
3368 org-timer-set-timer
3369 org-timer-reset-timers
3370 org-timer-show-remaining-time)))
3372 ;; Autoload org-feed.el
3374 (eval-and-compile
3375 (org-autoload
3376 "org-feed"
3377 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3380 ;; Autoload org-indent.el
3382 ;; Define the variable already here, to make sure we have it.
3383 (defvar org-indent-mode nil
3384 "Non-nil if Org-Indent mode is enabled.
3385 Use the command `org-indent-mode' to change this variable.")
3387 (eval-and-compile
3388 (org-autoload
3389 "org-indent"
3390 '(org-indent-mode)))
3392 ;; Autoload org-mobile.el
3394 (eval-and-compile
3395 (org-autoload
3396 "org-mobile"
3397 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3399 ;; Autoload archiving code
3400 ;; The stuff that is needed for cycling and tags has to be defined here.
3402 (defgroup org-archive nil
3403 "Options concerning archiving in Org-mode."
3404 :tag "Org Archive"
3405 :group 'org-structure)
3407 (defcustom org-archive-location "%s_archive::"
3408 "The location where subtrees should be archived.
3410 The value of this variable is a string, consisting of two parts,
3411 separated by a double-colon. The first part is a filename and
3412 the second part is a headline.
3414 When the filename is omitted, archiving happens in the same file.
3415 %s in the filename will be replaced by the current file
3416 name (without the directory part). Archiving to a different file
3417 is useful to keep archived entries from contributing to the
3418 Org-mode Agenda.
3420 The archived entries will be filed as subtrees of the specified
3421 headline. When the headline is omitted, the subtrees are simply
3422 filed away at the end of the file, as top-level entries. Also in
3423 the heading you can use %s to represent the file name, this can be
3424 useful when using the same archive for a number of different files.
3426 Here are a few examples:
3427 \"%s_archive::\"
3428 If the current file is Projects.org, archive in file
3429 Projects.org_archive, as top-level trees. This is the default.
3431 \"::* Archived Tasks\"
3432 Archive in the current file, under the top-level headline
3433 \"* Archived Tasks\".
3435 \"~/org/archive.org::\"
3436 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3438 \"~/org/archive.org::From %s\"
3439 Archive in file ~/org/archive.org (absolute path), und headlines
3440 \"From FILENAME\" where file name is the current file name.
3442 \"basement::** Finished Tasks\"
3443 Archive in file ./basement (relative path), as level 3 trees
3444 below the level 2 heading \"** Finished Tasks\".
3446 You may set this option on a per-file basis by adding to the buffer a
3447 line like
3449 #+ARCHIVE: basement::** Finished Tasks
3451 You may also define it locally for a subtree by setting an ARCHIVE property
3452 in the entry. If such a property is found in an entry, or anywhere up
3453 the hierarchy, it will be used."
3454 :group 'org-archive
3455 :type 'string)
3457 (defcustom org-archive-tag "ARCHIVE"
3458 "The tag that marks a subtree as archived.
3459 An archived subtree does not open during visibility cycling, and does
3460 not contribute to the agenda listings.
3461 After changing this, font-lock must be restarted in the relevant buffers to
3462 get the proper fontification."
3463 :group 'org-archive
3464 :group 'org-keywords
3465 :type 'string)
3467 (defcustom org-agenda-skip-archived-trees t
3468 "Non-nil means, the agenda will skip any items located in archived trees.
3469 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3470 variable is no longer recommended, you should leave it at the value t.
3471 Instead, use the key `v' to cycle the archives-mode in the agenda."
3472 :group 'org-archive
3473 :group 'org-agenda-skip
3474 :type 'boolean)
3476 (defcustom org-columns-skip-archived-trees t
3477 "Non-nil means, ignore archived trees when creating column view."
3478 :group 'org-archive
3479 :group 'org-properties
3480 :type 'boolean)
3482 (defcustom org-cycle-open-archived-trees nil
3483 "Non-nil means, `org-cycle' will open archived trees.
3484 An archived tree is a tree marked with the tag ARCHIVE.
3485 When nil, archived trees will stay folded. You can still open them with
3486 normal outline commands like `show-all', but not with the cycling commands."
3487 :group 'org-archive
3488 :group 'org-cycle
3489 :type 'boolean)
3491 (defcustom org-sparse-tree-open-archived-trees nil
3492 "Non-nil means sparse tree construction shows matches in archived trees.
3493 When nil, matches in these trees are highlighted, but the trees are kept in
3494 collapsed state."
3495 :group 'org-archive
3496 :group 'org-sparse-trees
3497 :type 'boolean)
3499 (defun org-cycle-hide-archived-subtrees (state)
3500 "Re-hide all archived subtrees after a visibility state change."
3501 (when (and (not org-cycle-open-archived-trees)
3502 (not (memq state '(overview folded))))
3503 (save-excursion
3504 (let* ((globalp (memq state '(contents all)))
3505 (beg (if globalp (point-min) (point)))
3506 (end (if globalp (point-max) (org-end-of-subtree t))))
3507 (org-hide-archived-subtrees beg end)
3508 (goto-char beg)
3509 (if (looking-at (concat ".*:" org-archive-tag ":"))
3510 (message "%s" (substitute-command-keys
3511 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3513 (defun org-force-cycle-archived ()
3514 "Cycle subtree even if it is archived."
3515 (interactive)
3516 (setq this-command 'org-cycle)
3517 (let ((org-cycle-open-archived-trees t))
3518 (call-interactively 'org-cycle)))
3520 (defun org-hide-archived-subtrees (beg end)
3521 "Re-hide all archived subtrees after a visibility state change."
3522 (save-excursion
3523 (let* ((re (concat ":" org-archive-tag ":")))
3524 (goto-char beg)
3525 (while (re-search-forward re end t)
3526 (and (org-on-heading-p) (org-flag-subtree t))
3527 (org-end-of-subtree t)))))
3529 (defun org-flag-subtree (flag)
3530 (save-excursion
3531 (org-back-to-heading t)
3532 (outline-end-of-heading)
3533 (outline-flag-region (point)
3534 (progn (org-end-of-subtree t) (point))
3535 flag)))
3537 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3539 (eval-and-compile
3540 (org-autoload "org-archive"
3541 '(org-add-archive-files org-archive-subtree
3542 org-archive-to-archive-sibling org-toggle-archive-tag)))
3544 ;; Autoload Column View Code
3546 (declare-function org-columns-number-to-string "org-colview")
3547 (declare-function org-columns-get-format-and-top-level "org-colview")
3548 (declare-function org-columns-compute "org-colview")
3550 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3551 '(org-columns-number-to-string org-columns-get-format-and-top-level
3552 org-columns-compute org-agenda-columns org-columns-remove-overlays
3553 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3555 ;; Autoload ID code
3557 (declare-function org-id-store-link "org-id")
3558 (declare-function org-id-locations-load "org-id")
3559 (declare-function org-id-locations-save "org-id")
3560 (defvar org-id-track-globally)
3561 (org-autoload "org-id"
3562 '(org-id-get-create org-id-new org-id-copy org-id-get
3563 org-id-get-with-outline-path-completion
3564 org-id-get-with-outline-drilling
3565 org-id-goto org-id-find org-id-store-link))
3567 ;; Autoload Plotting Code
3569 (org-autoload "org-plot"
3570 '(org-plot/gnuplot))
3572 ;;; Variables for pre-computed regular expressions, all buffer local
3574 (defvar org-drawer-regexp nil
3575 "Matches first line of a hidden block.")
3576 (make-variable-buffer-local 'org-drawer-regexp)
3577 (defvar org-todo-regexp nil
3578 "Matches any of the TODO state keywords.")
3579 (make-variable-buffer-local 'org-todo-regexp)
3580 (defvar org-not-done-regexp nil
3581 "Matches any of the TODO state keywords except the last one.")
3582 (make-variable-buffer-local 'org-not-done-regexp)
3583 (defvar org-not-done-heading-regexp nil
3584 "Matches a TODO headline that is not done.")
3585 (make-variable-buffer-local 'org-not-done-regexp)
3586 (defvar org-todo-line-regexp nil
3587 "Matches a headline and puts TODO state into group 2 if present.")
3588 (make-variable-buffer-local 'org-todo-line-regexp)
3589 (defvar org-complex-heading-regexp nil
3590 "Matches a headline and puts everything into groups:
3591 group 1: the stars
3592 group 2: The todo keyword, maybe
3593 group 3: Priority cookie
3594 group 4: True headline
3595 group 5: Tags")
3596 (make-variable-buffer-local 'org-complex-heading-regexp)
3597 (defvar org-complex-heading-regexp-format nil)
3598 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3599 (defvar org-todo-line-tags-regexp nil
3600 "Matches a headline and puts TODO state into group 2 if present.
3601 Also put tags into group 4 if tags are present.")
3602 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3603 (defvar org-nl-done-regexp nil
3604 "Matches newline followed by a headline with the DONE keyword.")
3605 (make-variable-buffer-local 'org-nl-done-regexp)
3606 (defvar org-looking-at-done-regexp nil
3607 "Matches the DONE keyword a point.")
3608 (make-variable-buffer-local 'org-looking-at-done-regexp)
3609 (defvar org-ds-keyword-length 12
3610 "Maximum length of the Deadline and SCHEDULED keywords.")
3611 (make-variable-buffer-local 'org-ds-keyword-length)
3612 (defvar org-deadline-regexp nil
3613 "Matches the DEADLINE keyword.")
3614 (make-variable-buffer-local 'org-deadline-regexp)
3615 (defvar org-deadline-time-regexp nil
3616 "Matches the DEADLINE keyword together with a time stamp.")
3617 (make-variable-buffer-local 'org-deadline-time-regexp)
3618 (defvar org-deadline-line-regexp nil
3619 "Matches the DEADLINE keyword and the rest of the line.")
3620 (make-variable-buffer-local 'org-deadline-line-regexp)
3621 (defvar org-scheduled-regexp nil
3622 "Matches the SCHEDULED keyword.")
3623 (make-variable-buffer-local 'org-scheduled-regexp)
3624 (defvar org-scheduled-time-regexp nil
3625 "Matches the SCHEDULED keyword together with a time stamp.")
3626 (make-variable-buffer-local 'org-scheduled-time-regexp)
3627 (defvar org-closed-time-regexp nil
3628 "Matches the CLOSED keyword together with a time stamp.")
3629 (make-variable-buffer-local 'org-closed-time-regexp)
3631 (defvar org-keyword-time-regexp nil
3632 "Matches any of the 4 keywords, together with the time stamp.")
3633 (make-variable-buffer-local 'org-keyword-time-regexp)
3634 (defvar org-keyword-time-not-clock-regexp nil
3635 "Matches any of the 3 keywords, together with the time stamp.")
3636 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3637 (defvar org-maybe-keyword-time-regexp nil
3638 "Matches a timestamp, possibly preceeded by a keyword.")
3639 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3640 (defvar org-planning-or-clock-line-re nil
3641 "Matches a line with planning or clock info.")
3642 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3644 (defconst org-plain-time-of-day-regexp
3645 (concat
3646 "\\(\\<[012]?[0-9]"
3647 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3648 "\\(--?"
3649 "\\(\\<[012]?[0-9]"
3650 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3651 "\\)?")
3652 "Regular expression to match a plain time or time range.
3653 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3654 groups carry important information:
3655 0 the full match
3656 1 the first time, range or not
3657 8 the second time, if it is a range.")
3659 (defconst org-plain-time-extension-regexp
3660 (concat
3661 "\\(\\<[012]?[0-9]"
3662 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3663 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3664 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3665 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3666 groups carry important information:
3667 0 the full match
3668 7 hours of duration
3669 9 minutes of duration")
3671 (defconst org-stamp-time-of-day-regexp
3672 (concat
3673 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3674 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3675 "\\(--?"
3676 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3677 "Regular expression to match a timestamp time or time range.
3678 After a match, the following groups carry important information:
3679 0 the full match
3680 1 date plus weekday, for backreferencing to make sure both times on same day
3681 2 the first time, range or not
3682 4 the second time, if it is a range.")
3684 (defconst org-startup-options
3685 '(("fold" org-startup-folded t)
3686 ("overview" org-startup-folded t)
3687 ("nofold" org-startup-folded nil)
3688 ("showall" org-startup-folded nil)
3689 ("showeverything" org-startup-folded showeverything)
3690 ("content" org-startup-folded content)
3691 ("indent" org-startup-indented t)
3692 ("noindent" org-startup-indented nil)
3693 ("hidestars" org-hide-leading-stars t)
3694 ("showstars" org-hide-leading-stars nil)
3695 ("odd" org-odd-levels-only t)
3696 ("oddeven" org-odd-levels-only nil)
3697 ("align" org-startup-align-all-tables t)
3698 ("noalign" org-startup-align-all-tables nil)
3699 ("customtime" org-display-custom-times t)
3700 ("logdone" org-log-done time)
3701 ("lognotedone" org-log-done note)
3702 ("nologdone" org-log-done nil)
3703 ("lognoteclock-out" org-log-note-clock-out t)
3704 ("nolognoteclock-out" org-log-note-clock-out nil)
3705 ("logrepeat" org-log-repeat state)
3706 ("lognoterepeat" org-log-repeat note)
3707 ("nologrepeat" org-log-repeat nil)
3708 ("logreschedule" org-log-reschedule time)
3709 ("lognotereschedule" org-log-reschedule note)
3710 ("nologreschedule" org-log-reschedule nil)
3711 ("logredeadline" org-log-redeadline time)
3712 ("lognoteredeadline" org-log-redeadline note)
3713 ("nologredeadline" org-log-redeadline nil)
3714 ("fninline" org-footnote-define-inline t)
3715 ("nofninline" org-footnote-define-inline nil)
3716 ("fnlocal" org-footnote-section nil)
3717 ("fnauto" org-footnote-auto-label t)
3718 ("fnprompt" org-footnote-auto-label nil)
3719 ("fnconfirm" org-footnote-auto-label confirm)
3720 ("fnplain" org-footnote-auto-label plain)
3721 ("fnadjust" org-footnote-auto-adjust t)
3722 ("nofnadjust" org-footnote-auto-adjust nil)
3723 ("constcgs" constants-unit-system cgs)
3724 ("constSI" constants-unit-system SI)
3725 ("noptag" org-tag-persistent-alist nil)
3726 ("hideblocks" org-hide-block-startup t)
3727 ("nohideblocks" org-hide-block-startup nil))
3728 "Variable associated with STARTUP options for org-mode.
3729 Each element is a list of three items: The startup options as written
3730 in the #+STARTUP line, the corresponding variable, and the value to
3731 set this variable to if the option is found. An optional forth element PUSH
3732 means to push this value onto the list in the variable.")
3734 (defun org-set-regexps-and-options ()
3735 "Precompute regular expressions for current buffer."
3736 (when (org-mode-p)
3737 (org-set-local 'org-todo-kwd-alist nil)
3738 (org-set-local 'org-todo-key-alist nil)
3739 (org-set-local 'org-todo-key-trigger nil)
3740 (org-set-local 'org-todo-keywords-1 nil)
3741 (org-set-local 'org-done-keywords nil)
3742 (org-set-local 'org-todo-heads nil)
3743 (org-set-local 'org-todo-sets nil)
3744 (org-set-local 'org-todo-log-states nil)
3745 (org-set-local 'org-file-properties nil)
3746 (org-set-local 'org-file-tags nil)
3747 (let ((re (org-make-options-regexp
3748 '("CATEGORY" "TODO" "COLUMNS"
3749 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3750 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3751 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3752 (splitre "[ \t]+")
3753 kwds kws0 kwsa key log value cat arch tags const links hw dws
3754 tail sep kws1 prio props ftags drawers
3755 ext-setup-or-nil setup-contents (start 0))
3756 (save-excursion
3757 (save-restriction
3758 (widen)
3759 (goto-char (point-min))
3760 (while (or (and ext-setup-or-nil
3761 (string-match re ext-setup-or-nil start)
3762 (setq start (match-end 0)))
3763 (and (setq ext-setup-or-nil nil start 0)
3764 (re-search-forward re nil t)))
3765 (setq key (upcase (match-string 1 ext-setup-or-nil))
3766 value (org-match-string-no-properties 2 ext-setup-or-nil))
3767 (cond
3768 ((equal key "CATEGORY")
3769 (if (string-match "[ \t]+$" value)
3770 (setq value (replace-match "" t t value)))
3771 (setq cat value))
3772 ((member key '("SEQ_TODO" "TODO"))
3773 (push (cons 'sequence (org-split-string value splitre)) kwds))
3774 ((equal key "TYP_TODO")
3775 (push (cons 'type (org-split-string value splitre)) kwds))
3776 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3777 ;; general TODO-like setup
3778 (push (cons (intern (downcase (match-string 1 key)))
3779 (org-split-string value splitre)) kwds))
3780 ((equal key "TAGS")
3781 (setq tags (append tags (if tags '("\\n") nil)
3782 (org-split-string value splitre))))
3783 ((equal key "COLUMNS")
3784 (org-set-local 'org-columns-default-format value))
3785 ((equal key "LINK")
3786 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3787 (push (cons (match-string 1 value)
3788 (org-trim (match-string 2 value)))
3789 links)))
3790 ((equal key "PRIORITIES")
3791 (setq prio (org-split-string value " +")))
3792 ((equal key "PROPERTY")
3793 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3794 (push (cons (match-string 1 value) (match-string 2 value))
3795 props)))
3796 ((equal key "FILETAGS")
3797 (when (string-match "\\S-" value)
3798 (setq ftags
3799 (append
3800 ftags
3801 (apply 'append
3802 (mapcar (lambda (x) (org-split-string x ":"))
3803 (org-split-string value)))))))
3804 ((equal key "DRAWERS")
3805 (setq drawers (org-split-string value splitre)))
3806 ((equal key "CONSTANTS")
3807 (setq const (append const (org-split-string value splitre))))
3808 ((equal key "STARTUP")
3809 (let ((opts (org-split-string value splitre))
3810 l var val)
3811 (while (setq l (pop opts))
3812 (when (setq l (assoc l org-startup-options))
3813 (setq var (nth 1 l) val (nth 2 l))
3814 (if (not (nth 3 l))
3815 (set (make-local-variable var) val)
3816 (if (not (listp (symbol-value var)))
3817 (set (make-local-variable var) nil))
3818 (set (make-local-variable var) (symbol-value var))
3819 (add-to-list var val))))))
3820 ((equal key "ARCHIVE")
3821 (string-match " *$" value)
3822 (setq arch (replace-match "" t t value))
3823 (remove-text-properties 0 (length arch)
3824 '(face t fontified t) arch))
3825 ((equal key "SETUPFILE")
3826 (setq setup-contents (org-file-contents
3827 (expand-file-name
3828 (org-remove-double-quotes value))
3829 'noerror))
3830 (if (not ext-setup-or-nil)
3831 (setq ext-setup-or-nil setup-contents start 0)
3832 (setq ext-setup-or-nil
3833 (concat (substring ext-setup-or-nil 0 start)
3834 "\n" setup-contents "\n"
3835 (substring ext-setup-or-nil start)))))
3836 ))))
3837 (when cat
3838 (org-set-local 'org-category (intern cat))
3839 (push (cons "CATEGORY" cat) props))
3840 (when prio
3841 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3842 (setq prio (mapcar 'string-to-char prio))
3843 (org-set-local 'org-highest-priority (nth 0 prio))
3844 (org-set-local 'org-lowest-priority (nth 1 prio))
3845 (org-set-local 'org-default-priority (nth 2 prio)))
3846 (and props (org-set-local 'org-file-properties (nreverse props)))
3847 (and ftags (org-set-local 'org-file-tags
3848 (mapcar 'org-add-prop-inherited ftags)))
3849 (and drawers (org-set-local 'org-drawers drawers))
3850 (and arch (org-set-local 'org-archive-location arch))
3851 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3852 ;; Process the TODO keywords
3853 (unless kwds
3854 ;; Use the global values as if they had been given locally.
3855 (setq kwds (default-value 'org-todo-keywords))
3856 (if (stringp (car kwds))
3857 (setq kwds (list (cons org-todo-interpretation
3858 (default-value 'org-todo-keywords)))))
3859 (setq kwds (reverse kwds)))
3860 (setq kwds (nreverse kwds))
3861 (let (inter kws kw)
3862 (while (setq kws (pop kwds))
3863 (let ((kws (or
3864 (run-hook-with-args-until-success
3865 'org-todo-setup-filter-hook kws)
3866 kws)))
3867 (setq inter (pop kws) sep (member "|" kws)
3868 kws0 (delete "|" (copy-sequence kws))
3869 kwsa nil
3870 kws1 (mapcar
3871 (lambda (x)
3872 ;; 1 2
3873 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3874 (progn
3875 (setq kw (match-string 1 x)
3876 key (and (match-end 2) (match-string 2 x))
3877 log (org-extract-log-state-settings x))
3878 (push (cons kw (and key (string-to-char key))) kwsa)
3879 (and log (push log org-todo-log-states))
3881 (error "Invalid TODO keyword %s" x)))
3882 kws0)
3883 kwsa (if kwsa (append '((:startgroup))
3884 (nreverse kwsa)
3885 '((:endgroup))))
3886 hw (car kws1)
3887 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3888 tail (list inter hw (car dws) (org-last dws))))
3889 (add-to-list 'org-todo-heads hw 'append)
3890 (push kws1 org-todo-sets)
3891 (setq org-done-keywords (append org-done-keywords dws nil))
3892 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3893 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3894 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3895 (setq org-todo-sets (nreverse org-todo-sets)
3896 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3897 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3898 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3899 ;; Process the constants
3900 (when const
3901 (let (e cst)
3902 (while (setq e (pop const))
3903 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3904 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3905 (setq org-table-formula-constants-local cst)))
3907 ;; Process the tags.
3908 (when tags
3909 (let (e tgs)
3910 (while (setq e (pop tags))
3911 (cond
3912 ((equal e "{") (push '(:startgroup) tgs))
3913 ((equal e "}") (push '(:endgroup) tgs))
3914 ((equal e "\\n") (push '(:newline) tgs))
3915 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3916 (push (cons (match-string 1 e)
3917 (string-to-char (match-string 2 e)))
3918 tgs))
3919 (t (push (list e) tgs))))
3920 (org-set-local 'org-tag-alist nil)
3921 (while (setq e (pop tgs))
3922 (or (and (stringp (car e))
3923 (assoc (car e) org-tag-alist))
3924 (push e org-tag-alist)))))
3926 ;; Compute the regular expressions and other local variables
3927 (if (not org-done-keywords)
3928 (setq org-done-keywords (and org-todo-keywords-1
3929 (list (org-last org-todo-keywords-1)))))
3930 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3931 (length org-scheduled-string)
3932 (length org-clock-string)
3933 (length org-closed-string)))
3934 org-drawer-regexp
3935 (concat "^[ \t]*:\\("
3936 (mapconcat 'regexp-quote org-drawers "\\|")
3937 "\\):[ \t]*$")
3938 org-not-done-keywords
3939 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3940 org-todo-regexp
3941 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3942 "\\|") "\\)\\>")
3943 org-not-done-regexp
3944 (concat "\\<\\("
3945 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3946 "\\)\\>")
3947 org-not-done-heading-regexp
3948 (concat "^\\(\\*+\\)[ \t]+\\("
3949 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3950 "\\)\\>")
3951 org-todo-line-regexp
3952 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3953 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3954 "\\)\\>\\)?[ \t]*\\(.*\\)")
3955 org-complex-heading-regexp
3956 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3957 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3958 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3959 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3960 org-complex-heading-regexp-format
3961 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3962 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3963 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3964 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3965 org-nl-done-regexp
3966 (concat "\n\\*+[ \t]+"
3967 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3968 "\\)" "\\>")
3969 org-todo-line-tags-regexp
3970 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3971 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3972 (org-re
3973 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3974 org-looking-at-done-regexp
3975 (concat "^" "\\(?:"
3976 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3977 "\\>")
3978 org-deadline-regexp (concat "\\<" org-deadline-string)
3979 org-deadline-time-regexp
3980 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3981 org-deadline-line-regexp
3982 (concat "\\<\\(" org-deadline-string "\\).*")
3983 org-scheduled-regexp
3984 (concat "\\<" org-scheduled-string)
3985 org-scheduled-time-regexp
3986 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3987 org-closed-time-regexp
3988 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3989 org-keyword-time-regexp
3990 (concat "\\<\\(" org-scheduled-string
3991 "\\|" org-deadline-string
3992 "\\|" org-closed-string
3993 "\\|" org-clock-string "\\)"
3994 " *[[<]\\([^]>]+\\)[]>]")
3995 org-keyword-time-not-clock-regexp
3996 (concat "\\<\\(" org-scheduled-string
3997 "\\|" org-deadline-string
3998 "\\|" org-closed-string
3999 "\\)"
4000 " *[[<]\\([^]>]+\\)[]>]")
4001 org-maybe-keyword-time-regexp
4002 (concat "\\(\\<\\(" org-scheduled-string
4003 "\\|" org-deadline-string
4004 "\\|" org-closed-string
4005 "\\|" org-clock-string "\\)\\)?"
4006 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4007 org-planning-or-clock-line-re
4008 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4009 "\\|" org-deadline-string
4010 "\\|" org-closed-string "\\|" org-clock-string
4011 "\\)\\>\\)")
4013 (org-compute-latex-and-specials-regexp)
4014 (org-set-font-lock-defaults))))
4016 (defun org-file-contents (file &optional noerror)
4017 "Return the contents of FILE, as a string."
4018 (if (or (not file)
4019 (not (file-readable-p file)))
4020 (if noerror
4021 (progn
4022 (message "Cannot read file %s" file)
4023 (ding) (sit-for 2)
4025 (error "Cannot read file %s" file))
4026 (with-temp-buffer
4027 (insert-file-contents file)
4028 (buffer-string))))
4030 (defun org-extract-log-state-settings (x)
4031 "Extract the log state setting from a TODO keyword string.
4032 This will extract info from a string like \"WAIT(w@/!)\"."
4033 (let (kw key log1 log2)
4034 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4035 (setq kw (match-string 1 x)
4036 key (and (match-end 2) (match-string 2 x))
4037 log1 (and (match-end 3) (match-string 3 x))
4038 log2 (and (match-end 4) (match-string 4 x)))
4039 (and (or log1 log2)
4040 (list kw
4041 (and log1 (if (equal log1 "!") 'time 'note))
4042 (and log2 (if (equal log2 "!") 'time 'note)))))))
4044 (defun org-remove-keyword-keys (list)
4045 "Remove a pair of parenthesis at the end of each string in LIST."
4046 (mapcar (lambda (x)
4047 (if (string-match "(.*)$" x)
4048 (substring x 0 (match-beginning 0))
4050 list))
4052 ;; FIXME: this could be done much better, using second characters etc.
4053 (defun org-assign-fast-keys (alist)
4054 "Assign fast keys to a keyword-key alist.
4055 Respect keys that are already there."
4056 (let (new e k c c1 c2 (char ?a))
4057 (while (setq e (pop alist))
4058 (cond
4059 ((equal e '(:startgroup)) (push e new))
4060 ((equal e '(:endgroup)) (push e new))
4061 ((equal e '(:newline)) (push e new))
4063 (setq k (car e) c2 nil)
4064 (if (cdr e)
4065 (setq c (cdr e))
4066 ;; automatically assign a character.
4067 (setq c1 (string-to-char
4068 (downcase (substring
4069 k (if (= (string-to-char k) ?@) 1 0)))))
4070 (if (or (rassoc c1 new) (rassoc c1 alist))
4071 (while (or (rassoc char new) (rassoc char alist))
4072 (setq char (1+ char)))
4073 (setq c2 c1))
4074 (setq c (or c2 char)))
4075 (push (cons k c) new))))
4076 (nreverse new)))
4078 ;;; Some variables used in various places
4080 (defvar org-window-configuration nil
4081 "Used in various places to store a window configuration.")
4082 (defvar org-selected-window nil
4083 "Used in various places to store a window configuration.")
4084 (defvar org-finish-function nil
4085 "Function to be called when `C-c C-c' is used.
4086 This is for getting out of special buffers like remember.")
4089 ;; FIXME: Occasionally check by commenting these, to make sure
4090 ;; no other functions uses these, forgetting to let-bind them.
4091 (defvar entry)
4092 (defvar last-state)
4093 (defvar date)
4095 ;; Defined somewhere in this file, but used before definition.
4096 (defvar org-html-entities)
4097 (defvar org-struct-menu)
4098 (defvar org-org-menu)
4099 (defvar org-tbl-menu)
4101 ;;;; Define the Org-mode
4103 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4104 (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."))
4107 ;; We use a before-change function to check if a table might need
4108 ;; an update.
4109 (defvar org-table-may-need-update t
4110 "Indicates that a table might need an update.
4111 This variable is set by `org-before-change-function'.
4112 `org-table-align' sets it back to nil.")
4113 (defun org-before-change-function (beg end)
4114 "Every change indicates that a table might need an update."
4115 (setq org-table-may-need-update t))
4116 (defvar org-mode-map)
4117 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4118 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4119 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4120 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4121 (defvar org-table-buffer-is-an nil)
4122 (defconst org-outline-regexp "\\*+ ")
4124 ;;;###autoload
4125 (define-derived-mode org-mode outline-mode "Org"
4126 "Outline-based notes management and organizer, alias
4127 \"Carsten's outline-mode for keeping track of everything.\"
4129 Org-mode develops organizational tasks around a NOTES file which
4130 contains information about projects as plain text. Org-mode is
4131 implemented on top of outline-mode, which is ideal to keep the content
4132 of large files well structured. It supports ToDo items, deadlines and
4133 time stamps, which magically appear in the diary listing of the Emacs
4134 calendar. Tables are easily created with a built-in table editor.
4135 Plain text URL-like links connect to websites, emails (VM), Usenet
4136 messages (Gnus), BBDB entries, and any files related to the project.
4137 For printing and sharing of notes, an Org-mode file (or a part of it)
4138 can be exported as a structured ASCII or HTML file.
4140 The following commands are available:
4142 \\{org-mode-map}"
4144 ;; Get rid of Outline menus, they are not needed
4145 ;; Need to do this here because define-derived-mode sets up
4146 ;; the keymap so late. Still, it is a waste to call this each time
4147 ;; we switch another buffer into org-mode.
4148 (if (featurep 'xemacs)
4149 (when (boundp 'outline-mode-menu-heading)
4150 ;; Assume this is Greg's port, it used easymenu
4151 (easy-menu-remove outline-mode-menu-heading)
4152 (easy-menu-remove outline-mode-menu-show)
4153 (easy-menu-remove outline-mode-menu-hide))
4154 (define-key org-mode-map [menu-bar headings] 'undefined)
4155 (define-key org-mode-map [menu-bar hide] 'undefined)
4156 (define-key org-mode-map [menu-bar show] 'undefined))
4158 (org-load-modules-maybe)
4159 (easy-menu-add org-org-menu)
4160 (easy-menu-add org-tbl-menu)
4161 (org-install-agenda-files-menu)
4162 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4163 (org-add-to-invisibility-spec '(org-cwidth))
4164 (org-add-to-invisibility-spec '(org-hide-block . t))
4165 (when (featurep 'xemacs)
4166 (org-set-local 'line-move-ignore-invisible t))
4167 (org-set-local 'outline-regexp org-outline-regexp)
4168 (org-set-local 'outline-level 'org-outline-level)
4169 (when (and org-ellipsis
4170 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4171 (fboundp 'make-glyph-code))
4172 (unless org-display-table
4173 (setq org-display-table (make-display-table)))
4174 (set-display-table-slot
4175 org-display-table 4
4176 (vconcat (mapcar
4177 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4178 org-ellipsis)))
4179 (if (stringp org-ellipsis) org-ellipsis "..."))))
4180 (setq buffer-display-table org-display-table))
4181 (org-set-regexps-and-options)
4182 (when (and org-tag-faces (not org-tags-special-faces-re))
4183 ;; tag faces set outside customize.... force initialization.
4184 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4185 ;; Calc embedded
4186 (org-set-local 'calc-embedded-open-mode "# ")
4187 (modify-syntax-entry ?# "<")
4188 (modify-syntax-entry ?@ "w")
4189 (if org-startup-truncated (setq truncate-lines t))
4190 (org-set-local 'font-lock-unfontify-region-function
4191 'org-unfontify-region)
4192 ;; Activate before-change-function
4193 (org-set-local 'org-table-may-need-update t)
4194 (org-add-hook 'before-change-functions 'org-before-change-function nil
4195 'local)
4196 ;; Check for running clock before killing a buffer
4197 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4198 ;; Paragraphs and auto-filling
4199 (org-set-autofill-regexps)
4200 (setq indent-line-function 'org-indent-line-function)
4201 (org-update-radio-target-regexp)
4202 ;; Make sure dependence stuff works reliably, even for users who set it
4203 ;; too late :-(
4204 (if org-enforce-todo-dependencies
4205 (add-hook 'org-blocker-hook
4206 'org-block-todo-from-children-or-siblings-or-parent)
4207 (remove-hook 'org-blocker-hook
4208 'org-block-todo-from-children-or-siblings-or-parent))
4209 (if org-enforce-todo-checkbox-dependencies
4210 (add-hook 'org-blocker-hook
4211 'org-block-todo-from-checkboxes)
4212 (remove-hook 'org-blocker-hook
4213 'org-block-todo-from-checkboxes))
4215 ;; Comment characters
4216 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4217 (org-set-local 'comment-padding " ")
4219 ;; Align options lines
4220 (org-set-local
4221 'align-mode-rules-list
4222 '((org-in-buffer-settings
4223 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4224 (modes . '(org-mode)))))
4226 ;; Imenu
4227 (org-set-local 'imenu-create-index-function
4228 'org-imenu-get-tree)
4230 ;; Make isearch reveal context
4231 (if (or (featurep 'xemacs)
4232 (not (boundp 'outline-isearch-open-invisible-function)))
4233 ;; Emacs 21 and XEmacs make use of the hook
4234 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4235 ;; Emacs 22 deals with this through a special variable
4236 (org-set-local 'outline-isearch-open-invisible-function
4237 (lambda (&rest ignore) (org-show-context 'isearch))))
4239 ;; If empty file that did not turn on org-mode automatically, make it to.
4240 (if (and org-insert-mode-line-in-empty-file
4241 (interactive-p)
4242 (= (point-min) (point-max)))
4243 (insert "# -*- mode: org -*-\n\n"))
4245 (unless org-inhibit-startup
4246 (when org-startup-align-all-tables
4247 (let ((bmp (buffer-modified-p)))
4248 (org-table-map-tables 'org-table-align)
4249 (set-buffer-modified-p bmp)))
4250 (when org-startup-indented
4251 (require 'org-indent)
4252 (org-indent-mode 1))
4253 (org-set-startup-visibility)))
4255 (when (fboundp 'abbrev-table-put)
4256 (abbrev-table-put org-mode-abbrev-table
4257 :parents (list text-mode-abbrev-table)))
4259 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4261 (defun org-current-time ()
4262 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4263 (if (> (car org-time-stamp-rounding-minutes) 1)
4264 (let ((r (car org-time-stamp-rounding-minutes))
4265 (time (decode-time)))
4266 (apply 'encode-time
4267 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4268 (nthcdr 2 time))))
4269 (current-time)))
4271 ;;;; Font-Lock stuff, including the activators
4273 (defvar org-mouse-map (make-sparse-keymap))
4274 (org-defkey org-mouse-map
4275 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4276 (org-defkey org-mouse-map
4277 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4278 (when org-mouse-1-follows-link
4279 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4280 (when org-tab-follows-link
4281 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4282 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4284 (require 'font-lock)
4286 (defconst org-non-link-chars "]\t\n\r<>")
4287 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4288 "shell" "elisp"))
4289 (defvar org-link-types-re nil
4290 "Matches a link that has a url-like prefix like \"http:\"")
4291 (defvar org-link-re-with-space nil
4292 "Matches a link with spaces, optional angular brackets around it.")
4293 (defvar org-link-re-with-space2 nil
4294 "Matches a link with spaces, optional angular brackets around it.")
4295 (defvar org-link-re-with-space3 nil
4296 "Matches a link with spaces, only for internal part in bracket links.")
4297 (defvar org-angle-link-re nil
4298 "Matches link with angular brackets, spaces are allowed.")
4299 (defvar org-plain-link-re nil
4300 "Matches plain link, without spaces.")
4301 (defvar org-bracket-link-regexp nil
4302 "Matches a link in double brackets.")
4303 (defvar org-bracket-link-analytic-regexp nil
4304 "Regular expression used to analyze links.
4305 Here is what the match groups contain after a match:
4306 1: http:
4307 2: http
4308 3: path
4309 4: [desc]
4310 5: desc")
4311 (defvar org-bracket-link-analytic-regexp++ nil
4312 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4313 (defvar org-any-link-re nil
4314 "Regular expression matching any link.")
4316 (defun org-make-link-regexps ()
4317 "Update the link regular expressions.
4318 This should be called after the variable `org-link-types' has changed."
4319 (setq org-link-types-re
4320 (concat
4321 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4322 org-link-re-with-space
4323 (concat
4324 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4325 "\\([^" org-non-link-chars " ]"
4326 "[^" org-non-link-chars "]*"
4327 "[^" org-non-link-chars " ]\\)>?")
4328 org-link-re-with-space2
4329 (concat
4330 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4331 "\\([^" org-non-link-chars " ]"
4332 "[^\t\n\r]*"
4333 "[^" org-non-link-chars " ]\\)>?")
4334 org-link-re-with-space3
4335 (concat
4336 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4337 "\\([^" org-non-link-chars " ]"
4338 "[^\t\n\r]*\\)")
4339 org-angle-link-re
4340 (concat
4341 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4342 "\\([^" org-non-link-chars " ]"
4343 "[^" org-non-link-chars "]*"
4344 "\\)>")
4345 org-plain-link-re
4346 (concat
4347 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4348 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4349 org-bracket-link-regexp
4350 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4351 org-bracket-link-analytic-regexp
4352 (concat
4353 "\\[\\["
4354 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4355 "\\([^]]+\\)"
4356 "\\]"
4357 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4358 "\\]")
4359 org-bracket-link-analytic-regexp++
4360 (concat
4361 "\\[\\["
4362 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4363 "\\([^]]+\\)"
4364 "\\]"
4365 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4366 "\\]")
4367 org-any-link-re
4368 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4369 org-angle-link-re "\\)\\|\\("
4370 org-plain-link-re "\\)")))
4372 (org-make-link-regexps)
4374 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4375 "Regular expression for fast time stamp matching.")
4376 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4377 "Regular expression for fast time stamp matching.")
4378 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4379 "Regular expression matching time strings for analysis.
4380 This one does not require the space after the date, so it can be used
4381 on a string that terminates immediately after the date.")
4382 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4383 "Regular expression matching time strings for analysis.")
4384 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4385 "Regular expression matching time stamps, with groups.")
4386 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4387 "Regular expression matching time stamps (also [..]), with groups.")
4388 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4389 "Regular expression matching a time stamp range.")
4390 (defconst org-tr-regexp-both
4391 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4392 "Regular expression matching a time stamp range.")
4393 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4394 org-ts-regexp "\\)?")
4395 "Regular expression matching a time stamp or time stamp range.")
4396 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4397 org-ts-regexp-both "\\)?")
4398 "Regular expression matching a time stamp or time stamp range.
4399 The time stamps may be either active or inactive.")
4401 (defvar org-emph-face nil)
4403 (defun org-do-emphasis-faces (limit)
4404 "Run through the buffer and add overlays to links."
4405 (let (rtn a)
4406 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4407 (if (not (= (char-after (match-beginning 3))
4408 (char-after (match-beginning 4))))
4409 (progn
4410 (setq rtn t)
4411 (setq a (assoc (match-string 3) org-emphasis-alist))
4412 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4413 'face
4414 (nth 1 a))
4415 (and (nth 4 a)
4416 (org-remove-flyspell-overlays-in
4417 (match-beginning 0) (match-end 0)))
4418 (add-text-properties (match-beginning 2) (match-end 2)
4419 '(font-lock-multiline t))
4420 (when org-hide-emphasis-markers
4421 (add-text-properties (match-end 4) (match-beginning 5)
4422 '(invisible org-link))
4423 (add-text-properties (match-beginning 3) (match-end 3)
4424 '(invisible org-link)))))
4425 (backward-char 1))
4426 rtn))
4428 (defun org-emphasize (&optional char)
4429 "Insert or change an emphasis, i.e. a font like bold or italic.
4430 If there is an active region, change that region to a new emphasis.
4431 If there is no region, just insert the marker characters and position
4432 the cursor between them.
4433 CHAR should be either the marker character, or the first character of the
4434 HTML tag associated with that emphasis. If CHAR is a space, the means
4435 to remove the emphasis of the selected region.
4436 If char is not given (for example in an interactive call) it
4437 will be prompted for."
4438 (interactive)
4439 (let ((eal org-emphasis-alist) e det
4440 (erc org-emphasis-regexp-components)
4441 (prompt "")
4442 (string "") beg end move tag c s)
4443 (if (org-region-active-p)
4444 (setq beg (region-beginning) end (region-end)
4445 string (buffer-substring beg end))
4446 (setq move t))
4448 (while (setq e (pop eal))
4449 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4450 c (aref tag 0))
4451 (push (cons c (string-to-char (car e))) det)
4452 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4453 (substring tag 1)))))
4454 (setq det (nreverse det))
4455 (unless char
4456 (message "%s" (concat "Emphasis marker or tag:" prompt))
4457 (setq char (read-char-exclusive)))
4458 (setq char (or (cdr (assoc char det)) char))
4459 (if (equal char ?\ )
4460 (setq s "" move nil)
4461 (unless (assoc (char-to-string char) org-emphasis-alist)
4462 (error "No such emphasis marker: \"%c\"" char))
4463 (setq s (char-to-string char)))
4464 (while (and (> (length string) 1)
4465 (equal (substring string 0 1) (substring string -1))
4466 (assoc (substring string 0 1) org-emphasis-alist))
4467 (setq string (substring string 1 -1)))
4468 (setq string (concat s string s))
4469 (if beg (delete-region beg end))
4470 (unless (or (bolp)
4471 (string-match (concat "[" (nth 0 erc) "\n]")
4472 (char-to-string (char-before (point)))))
4473 (insert " "))
4474 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4475 (char-to-string (char-after (point))))
4476 (insert " ") (backward-char 1))
4477 (insert string)
4478 (and move (backward-char 1))))
4480 (defconst org-nonsticky-props
4481 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4483 (defsubst org-rear-nonsticky-at (pos)
4484 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4486 (defun org-activate-plain-links (limit)
4487 "Run through the buffer and add overlays to links."
4488 (catch 'exit
4489 (let (f)
4490 (if (re-search-forward org-plain-link-re limit t)
4491 (progn
4492 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4493 (setq f (get-text-property (match-beginning 0) 'face))
4494 (if (or (eq f 'org-tag)
4495 (and (listp f) (memq 'org-tag f)))
4497 (add-text-properties (match-beginning 0) (match-end 0)
4498 (list 'mouse-face 'highlight
4499 'keymap org-mouse-map))
4500 (org-rear-nonsticky-at (match-end 0)))
4501 t)))))
4503 (defun org-activate-code (limit)
4504 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4505 (progn
4506 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4507 (remove-text-properties (match-beginning 0) (match-end 0)
4508 '(display t invisible t intangible t))
4509 t)))
4511 (defun org-fontify-meta-lines-and-blocks (limit)
4512 "Fontify #+ lines and blocks, in the correct ways."
4513 (let ((case-fold-search t))
4514 (if (re-search-forward
4515 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4516 limit t)
4517 (let ((beg (match-beginning 0))
4518 (beg1 (line-beginning-position 2))
4519 (dc1 (downcase (match-string 2)))
4520 (dc3 (downcase (match-string 3)))
4521 end end1 quoting)
4522 (cond
4523 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4524 ;; a single line of backend-specific content
4525 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4526 (remove-text-properties (match-beginning 0) (match-end 0)
4527 '(display t invisible t intangible t))
4528 (add-text-properties (match-beginning 1) (match-end 3)
4529 '(font-lock-fontified t face org-meta-line))
4530 (add-text-properties (match-beginning 6) (match-end 6)
4531 '(font-lock-fontified t face org-block))
4533 ((and (match-end 4) (equal dc3 "begin"))
4534 ;; Truely a block
4535 (setq quoting (member (downcase (match-string 5))
4536 org-protecting-blocks))
4537 (when (re-search-forward
4538 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4539 nil t) ;; on purpose, we look further than LIMIT
4540 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4541 (when quoting
4542 (remove-text-properties beg end
4543 '(display t invisible t intangible t)))
4544 (add-text-properties
4545 beg end
4546 '(font-lock-fontified t font-lock-multiline t))
4547 (add-text-properties beg beg1 '(face org-meta-line))
4548 (add-text-properties end1 end '(face org-meta-line))
4549 (when quoting
4550 (add-text-properties beg1 end1 '(face org-block)))
4552 ((not (member (char-after beg) '(?\ ?\t)))
4553 ;; just any other in-buffer setting, but not indented
4554 (add-text-properties
4555 beg (match-end 0)
4556 '(font-lock-fontified t face org-meta-line))
4558 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4559 "orgtbl:" "tblfm:" "tblname:"))
4560 (and (match-end 4) (equal dc3 "attr")))
4561 (add-text-properties
4562 beg (match-end 0)
4563 '(font-lock-fontified t face org-meta-line))
4565 ((member dc3 '(" " ""))
4566 (add-text-properties
4567 beg (match-end 0)
4568 '(font-lock-fontified t face font-lock-comment-face)))
4569 (t nil))))))
4571 (defun org-activate-angle-links (limit)
4572 "Run through the buffer and add overlays to links."
4573 (if (re-search-forward org-angle-link-re limit t)
4574 (progn
4575 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4576 (add-text-properties (match-beginning 0) (match-end 0)
4577 (list 'mouse-face 'highlight
4578 'keymap org-mouse-map))
4579 (org-rear-nonsticky-at (match-end 0))
4580 t)))
4582 (defun org-activate-footnote-links (limit)
4583 "Run through the buffer and add overlays to links."
4584 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4585 limit t)
4586 (progn
4587 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4588 (add-text-properties (match-beginning 2) (match-end 2)
4589 (list 'mouse-face 'highlight
4590 'keymap org-mouse-map
4591 'help-echo
4592 (if (= (point-at-bol) (match-beginning 2))
4593 "Footnote definition"
4594 "Footnote reference")
4596 (org-rear-nonsticky-at (match-end 2))
4597 t)))
4599 (defun org-activate-bracket-links (limit)
4600 "Run through the buffer and add overlays to bracketed links."
4601 (if (re-search-forward org-bracket-link-regexp limit t)
4602 (let* ((help (concat "LINK: "
4603 (org-match-string-no-properties 1)))
4604 ;; FIXME: above we should remove the escapes.
4605 ;; but that requires another match, protecting match data,
4606 ;; a lot of overhead for font-lock.
4607 (ip (org-maybe-intangible
4608 (list 'invisible 'org-link
4609 'keymap org-mouse-map 'mouse-face 'highlight
4610 'font-lock-multiline t 'help-echo help)))
4611 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4612 'font-lock-multiline t 'help-echo help)))
4613 ;; We need to remove the invisible property here. Table narrowing
4614 ;; may have made some of this invisible.
4615 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4616 (remove-text-properties (match-beginning 0) (match-end 0)
4617 '(invisible nil))
4618 (if (match-end 3)
4619 (progn
4620 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4621 (org-rear-nonsticky-at (match-beginning 3))
4622 (add-text-properties (match-beginning 3) (match-end 3) vp)
4623 (org-rear-nonsticky-at (match-end 3))
4624 (add-text-properties (match-end 3) (match-end 0) ip)
4625 (org-rear-nonsticky-at (match-end 0)))
4626 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4627 (org-rear-nonsticky-at (match-beginning 1))
4628 (add-text-properties (match-beginning 1) (match-end 1) vp)
4629 (org-rear-nonsticky-at (match-end 1))
4630 (add-text-properties (match-end 1) (match-end 0) ip)
4631 (org-rear-nonsticky-at (match-end 0)))
4632 t)))
4634 (defun org-activate-dates (limit)
4635 "Run through the buffer and add overlays to dates."
4636 (if (re-search-forward org-tsr-regexp-both limit t)
4637 (progn
4638 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4639 (add-text-properties (match-beginning 0) (match-end 0)
4640 (list 'mouse-face 'highlight
4641 'keymap org-mouse-map))
4642 (org-rear-nonsticky-at (match-end 0))
4643 (when org-display-custom-times
4644 (if (match-end 3)
4645 (org-display-custom-time (match-beginning 3) (match-end 3)))
4646 (org-display-custom-time (match-beginning 1) (match-end 1)))
4647 t)))
4649 (defvar org-target-link-regexp nil
4650 "Regular expression matching radio targets in plain text.")
4651 (make-variable-buffer-local 'org-target-link-regexp)
4652 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4653 "Regular expression matching a link target.")
4654 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4655 "Regular expression matching a radio target.")
4656 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4657 "Regular expression matching any target.")
4659 (defun org-activate-target-links (limit)
4660 "Run through the buffer and add overlays to target matches."
4661 (when org-target-link-regexp
4662 (let ((case-fold-search t))
4663 (if (re-search-forward org-target-link-regexp limit t)
4664 (progn
4665 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4666 (add-text-properties (match-beginning 0) (match-end 0)
4667 (list 'mouse-face 'highlight
4668 'keymap org-mouse-map
4669 'help-echo "Radio target link"
4670 'org-linked-text t))
4671 (org-rear-nonsticky-at (match-end 0))
4672 t)))))
4674 (defun org-update-radio-target-regexp ()
4675 "Find all radio targets in this file and update the regular expression."
4676 (interactive)
4677 (when (memq 'radio org-activate-links)
4678 (setq org-target-link-regexp
4679 (org-make-target-link-regexp (org-all-targets 'radio)))
4680 (org-restart-font-lock)))
4682 (defun org-hide-wide-columns (limit)
4683 (let (s e)
4684 (setq s (text-property-any (point) (or limit (point-max))
4685 'org-cwidth t))
4686 (when s
4687 (setq e (next-single-property-change s 'org-cwidth))
4688 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4689 (goto-char e)
4690 t)))
4692 (defvar org-latex-and-specials-regexp nil
4693 "Regular expression for highlighting export special stuff.")
4694 (defvar org-match-substring-regexp)
4695 (defvar org-match-substring-with-braces-regexp)
4697 ;; This should be with the exporter code, but we also use if for font-locking
4698 (defconst org-export-html-special-string-regexps
4699 '(("\\\\-" . "&shy;")
4700 ("---\\([^-]\\)" . "&mdash;\\1")
4701 ("--\\([^-]\\)" . "&ndash;\\1")
4702 ("\\.\\.\\." . "&hellip;"))
4703 "Regular expressions for special string conversion.")
4706 (defun org-compute-latex-and-specials-regexp ()
4707 "Compute regular expression for stuff treated specially by exporters."
4708 (if (not org-highlight-latex-fragments-and-specials)
4709 (org-set-local 'org-latex-and-specials-regexp nil)
4710 (require 'org-exp)
4711 (let*
4712 ((matchers (plist-get org-format-latex-options :matchers))
4713 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4714 org-latex-regexps)))
4715 (options (org-combine-plists (org-default-export-plist)
4716 (org-infile-export-plist)))
4717 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4718 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4719 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4720 (org-export-html-expand (plist-get options :expand-quoted-html))
4721 (org-export-with-special-strings (plist-get options :special-strings))
4722 (re-sub
4723 (cond
4724 ((equal org-export-with-sub-superscripts '{})
4725 (list org-match-substring-with-braces-regexp))
4726 (org-export-with-sub-superscripts
4727 (list org-match-substring-regexp))
4728 (t nil)))
4729 (re-latex
4730 (if org-export-with-LaTeX-fragments
4731 (mapcar (lambda (x) (nth 1 x)) latexs)))
4732 (re-macros
4733 (if org-export-with-TeX-macros
4734 (list (concat "\\\\"
4735 (regexp-opt
4736 (append (mapcar 'car org-html-entities)
4737 (if (boundp 'org-latex-entities)
4738 (mapcar (lambda (x)
4739 (or (car-safe x) x))
4740 org-latex-entities)
4741 nil))
4742 'words))) ; FIXME
4744 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4745 (re-special (if org-export-with-special-strings
4746 (mapcar (lambda (x) (car x))
4747 org-export-html-special-string-regexps)))
4748 (re-rest
4749 (delq nil
4750 (list
4751 (if org-export-html-expand "@<[^>\n]+>")
4752 ))))
4753 (org-set-local
4754 'org-latex-and-specials-regexp
4755 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4756 re-rest) "\\|")))))
4758 (defun org-do-latex-and-special-faces (limit)
4759 "Run through the buffer and add overlays to links."
4760 (when org-latex-and-specials-regexp
4761 (let (rtn d)
4762 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4763 limit t))
4764 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4765 'face))
4766 '(org-code org-verbatim underline)))
4767 (progn
4768 (setq rtn t
4769 d (cond ((member (char-after (1+ (match-beginning 0)))
4770 '(?_ ?^)) 1)
4771 (t 0)))
4772 (font-lock-prepend-text-property
4773 (+ d (match-beginning 0)) (match-end 0)
4774 'face 'org-latex-and-export-specials)
4775 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4776 '(font-lock-multiline t)))))
4777 rtn)))
4779 (defun org-restart-font-lock ()
4780 "Restart font-lock-mode, to force refontification."
4781 (when (and (boundp 'font-lock-mode) font-lock-mode)
4782 (font-lock-mode -1)
4783 (font-lock-mode 1)))
4785 (defun org-all-targets (&optional radio)
4786 "Return a list of all targets in this file.
4787 With optional argument RADIO, only find radio targets."
4788 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4789 rtn)
4790 (save-excursion
4791 (goto-char (point-min))
4792 (while (re-search-forward re nil t)
4793 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4794 rtn)))
4796 (defun org-make-target-link-regexp (targets)
4797 "Make regular expression matching all strings in TARGETS.
4798 The regular expression finds the targets also if there is a line break
4799 between words."
4800 (and targets
4801 (concat
4802 "\\<\\("
4803 (mapconcat
4804 (lambda (x)
4805 (while (string-match " +" x)
4806 (setq x (replace-match "\\s-+" t t x)))
4808 targets
4809 "\\|")
4810 "\\)\\>")))
4812 (defun org-activate-tags (limit)
4813 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4814 (progn
4815 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4816 (add-text-properties (match-beginning 1) (match-end 1)
4817 (list 'mouse-face 'highlight
4818 'keymap org-mouse-map))
4819 (org-rear-nonsticky-at (match-end 1))
4820 t)))
4822 (defun org-outline-level ()
4823 "Compute the outline level of the heading at point.
4824 This function assumes that the cursor is at the beginning of a line matched
4825 by outline-regexp. Otherwise it returns garbage.
4826 If this is called at a normal headline, the level is the number of stars.
4827 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4828 For plain list items, if they are matched by `outline-regexp', this returns
4829 1000 plus the line indentation."
4830 (save-excursion
4831 (looking-at outline-regexp)
4832 (if (match-beginning 1)
4833 (+ (org-get-string-indentation (match-string 1)) 1000)
4834 (1- (- (match-end 0) (match-beginning 0))))))
4836 (defvar org-font-lock-keywords nil)
4838 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4839 "Regular expression matching a property line.")
4841 (defvar org-font-lock-hook nil
4842 "Functions to be called for special font lock stuff.")
4844 (defun org-font-lock-hook (limit)
4845 (run-hook-with-args 'org-font-lock-hook limit))
4847 (defun org-set-font-lock-defaults ()
4848 (let* ((em org-fontify-emphasized-text)
4849 (lk org-activate-links)
4850 (org-font-lock-extra-keywords
4851 (list
4852 ;; Call the hook
4853 '(org-font-lock-hook)
4854 ;; Headlines
4855 `(,(if org-fontify-whole-heading-line
4856 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4857 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4858 (1 (org-get-level-face 1))
4859 (2 (org-get-level-face 2))
4860 (3 (org-get-level-face 3)))
4861 ;; Table lines
4862 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4863 (1 'org-table t))
4864 ;; Table internals
4865 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4866 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4867 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4868 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4869 ;; Drawers
4870 (list org-drawer-regexp '(0 'org-special-keyword t))
4871 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4872 ;; Properties
4873 (list org-property-re
4874 '(1 'org-special-keyword t)
4875 '(3 'org-property-value t))
4876 ;; Links
4877 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4878 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4879 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4880 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4881 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4882 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4883 (if (memq 'footnote lk) '(org-activate-footnote-links
4884 (2 'org-footnote t)))
4885 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4886 '(org-hide-wide-columns (0 nil append))
4887 ;; TODO lines
4888 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4889 '(1 (org-get-todo-face 1) t))
4890 ;; DONE
4891 (if org-fontify-done-headline
4892 (list (concat "^[*]+ +\\<\\("
4893 (mapconcat 'regexp-quote org-done-keywords "\\|")
4894 "\\)\\(.*\\)")
4895 '(2 'org-headline-done t))
4896 nil)
4897 ;; Priorities
4898 '(org-font-lock-add-priority-faces)
4899 ;; Tags
4900 '(org-font-lock-add-tag-faces)
4901 ;; Special keywords
4902 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4903 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4904 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4905 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4906 ;; Emphasis
4907 (if em
4908 (if (featurep 'xemacs)
4909 '(org-do-emphasis-faces (0 nil append))
4910 '(org-do-emphasis-faces)))
4911 ;; Checkboxes
4912 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4913 2 'org-checkbox prepend)
4914 (if org-provide-checkbox-statistics
4915 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4916 (0 (org-get-checkbox-statistics-face) t)))
4917 ;; Description list items
4918 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4919 2 'bold prepend)
4920 ;; ARCHIVEd headings
4921 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4922 '(1 'org-archived prepend))
4923 ;; Specials
4924 '(org-do-latex-and-special-faces)
4925 ;; Code
4926 '(org-activate-code (1 'org-code t))
4927 ;; COMMENT
4928 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4929 "\\|" org-quote-string "\\)\\>")
4930 '(1 'org-special-keyword t))
4931 '("^#.*" (0 'font-lock-comment-face t))
4932 ;; Blocks and meta lines
4933 '(org-fontify-meta-lines-and-blocks)
4935 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4936 ;; Now set the full font-lock-keywords
4937 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4938 (org-set-local 'font-lock-defaults
4939 '(org-font-lock-keywords t nil nil backward-paragraph))
4940 (kill-local-variable 'font-lock-keywords) nil))
4942 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4943 "Fontify string S like in Org-mode"
4944 (with-temp-buffer
4945 (insert s)
4946 (let ((org-odd-levels-only odd-levels))
4947 (org-mode)
4948 (font-lock-fontify-buffer)
4949 (buffer-string))))
4951 (defvar org-m nil)
4952 (defvar org-l nil)
4953 (defvar org-f nil)
4954 (defun org-get-level-face (n)
4955 "Get the right face for match N in font-lock matching of headlines."
4956 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4957 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4958 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4959 (cond
4960 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4961 ((eq n 2) org-f)
4962 (t (if org-level-color-stars-only nil org-f))))
4964 (defun org-get-todo-face (kwd)
4965 "Get the right face for a TODO keyword KWD.
4966 If KWD is a number, get the corresponding match group."
4967 (if (numberp kwd) (setq kwd (match-string kwd)))
4968 (or (cdr (assoc kwd org-todo-keyword-faces))
4969 (and (member kwd org-done-keywords) 'org-done)
4970 'org-todo))
4972 (defun org-font-lock-add-tag-faces (limit)
4973 "Add the special tag faces."
4974 (when (and org-tag-faces org-tags-special-faces-re)
4975 (while (re-search-forward org-tags-special-faces-re limit t)
4976 (add-text-properties (match-beginning 1) (match-end 1)
4977 (list 'face (org-get-tag-face 1)
4978 'font-lock-fontified t))
4979 (backward-char 1))))
4981 (defun org-font-lock-add-priority-faces (limit)
4982 "Add the special priority faces."
4983 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4984 (add-text-properties
4985 (match-beginning 0) (match-end 0)
4986 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4987 org-priority-faces))
4988 'org-special-keyword)
4989 'font-lock-fontified t))))
4991 (defun org-get-tag-face (kwd)
4992 "Get the right face for a TODO keyword KWD.
4993 If KWD is a number, get the corresponding match group."
4994 (if (numberp kwd) (setq kwd (match-string kwd)))
4995 (or (cdr (assoc kwd org-tag-faces))
4996 'org-tag))
4998 (defun org-unfontify-region (beg end &optional maybe_loudly)
4999 "Remove fontification and activation overlays from links."
5000 (font-lock-default-unfontify-region beg end)
5001 (let* ((buffer-undo-list t)
5002 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5003 (inhibit-modification-hooks t)
5004 deactivate-mark buffer-file-name buffer-file-truename)
5005 (remove-text-properties
5006 beg end
5007 (if org-indent-mode
5008 ;; also remove line-prefix and wrap-prefix properties
5009 '(mouse-face t keymap t org-linked-text t
5010 invisible t intangible t
5011 line-prefix t wrap-prefix t
5012 org-no-flyspell t)
5013 '(mouse-face t keymap t org-linked-text t
5014 invisible t intangible t
5015 org-no-flyspell t)))))
5017 ;;;; Visibility cycling, including org-goto and indirect buffer
5019 ;;; Cycling
5021 (defvar org-cycle-global-status nil)
5022 (make-variable-buffer-local 'org-cycle-global-status)
5023 (defvar org-cycle-subtree-status nil)
5024 (make-variable-buffer-local 'org-cycle-subtree-status)
5026 ;;;###autoload
5028 (defvar org-inlinetask-min-level)
5030 (defun org-cycle (&optional arg)
5031 "TAB-action and visibility cycling for Org-mode.
5033 This is the command invoked in Org-mode by the TAB key. Its main purpose
5034 is outine visibility cycling, but it also invokes other actions
5035 in special contexts.
5037 - When this function is called with a prefix argument, rotate the entire
5038 buffer through 3 states (global cycling)
5039 1. OVERVIEW: Show only top-level headlines.
5040 2. CONTENTS: Show all headlines of all levels, but no body text.
5041 3. SHOW ALL: Show everything.
5042 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5043 determined by the variable `org-startup-folded', and by any VISIBILITY
5044 properties in the buffer.
5045 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5046 including any drawers.
5048 - When inside a table, re-align the table and move to the next field.
5050 - When point is at the beginning of a headline, rotate the subtree started
5051 by this line through 3 different states (local cycling)
5052 1. FOLDED: Only the main headline is shown.
5053 2. CHILDREN: The main headline and the direct children are shown.
5054 From this state, you can move to one of the children
5055 and zoom in further.
5056 3. SUBTREE: Show the entire subtree, including body text.
5057 If there is no subtree, switch directly from CHILDREN to FOLDED.
5059 - When there is a numeric prefix, go up to a heading with level ARG, do
5060 a `show-subtree' and return to the previous cursor position. If ARG
5061 is negative, go up that many levels.
5063 - When point is not at the beginning of a headline, execute the global
5064 binding for TAB, which is re-indenting the line. See the option
5065 `org-cycle-emulate-tab' for details.
5067 - Special case: if point is at the beginning of the buffer and there is
5068 no headline in line 1, this function will act as if called with prefix arg.
5069 But only if also the variable `org-cycle-global-at-bob' is t."
5070 (interactive "P")
5071 (org-load-modules-maybe)
5072 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5073 (and org-cycle-level-after-item/entry-creation
5074 (or (org-cycle-level)
5075 (org-cycle-item-indentation))))
5076 (let* ((limit-level
5077 (or org-cycle-max-level
5078 (and (boundp 'org-inlinetask-min-level)
5079 org-inlinetask-min-level
5080 (1- org-inlinetask-min-level))))
5081 (nstars (and limit-level
5082 (if org-odd-levels-only
5083 (and limit-level (1- (* limit-level 2)))
5084 limit-level)))
5085 (outline-regexp
5086 (cond
5087 ((not (org-mode-p)) outline-regexp)
5088 ((or (eq org-cycle-include-plain-lists 'integrate)
5089 (and org-cycle-include-plain-lists (org-at-item-p)))
5090 (concat "\\(?:\\*"
5091 (if nstars (format "\\{1,%d\\}" nstars) "+")
5092 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5093 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5094 (bob-special (and org-cycle-global-at-bob (bobp)
5095 (not (looking-at outline-regexp))))
5096 (org-cycle-hook
5097 (if bob-special
5098 (delq 'org-optimize-window-after-visibility-change
5099 (copy-sequence org-cycle-hook))
5100 org-cycle-hook))
5101 (pos (point)))
5103 (if (or bob-special (equal arg '(4)))
5104 ;; special case: use global cycling
5105 (setq arg t))
5107 (cond
5109 ((equal arg '(16))
5110 (org-set-startup-visibility)
5111 (message "Startup visibility, plus VISIBILITY properties"))
5113 ((equal arg '(64))
5114 (show-all)
5115 (message "Entire buffer visible, including drawers"))
5117 ((org-at-table-p 'any)
5118 ;; Enter the table or move to the next field in the table
5119 (or (org-table-recognize-table.el)
5120 (progn
5121 (if arg (org-table-edit-field t)
5122 (org-table-justify-field-maybe)
5123 (call-interactively 'org-table-next-field)))))
5125 ((run-hook-with-args-until-success
5126 'org-tab-after-check-for-table-hook))
5128 ((eq arg t) ;; Global cycling
5129 (org-cycle-internal-global))
5131 ((and org-drawers org-drawer-regexp
5132 (save-excursion
5133 (beginning-of-line 1)
5134 (looking-at org-drawer-regexp)))
5135 ;; Toggle block visibility
5136 (org-flag-drawer
5137 (not (get-char-property (match-end 0) 'invisible))))
5139 ((integerp arg)
5140 ;; Show-subtree, ARG levels up from here.
5141 (save-excursion
5142 (org-back-to-heading)
5143 (outline-up-heading (if (< arg 0) (- arg)
5144 (- (funcall outline-level) arg)))
5145 (org-show-subtree)))
5147 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5148 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5150 (org-cycle-internal-local))
5152 ;; TAB emulation and template completion
5153 (buffer-read-only (org-back-to-heading))
5155 ((run-hook-with-args-until-success
5156 'org-tab-after-check-for-cycling-hook))
5158 ((org-try-structure-completion))
5160 ((org-try-cdlatex-tab))
5162 ((run-hook-with-args-until-success
5163 'org-tab-before-tab-emulation-hook))
5165 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5166 (or (not (bolp))
5167 (not (looking-at outline-regexp))))
5168 (call-interactively (global-key-binding "\t")))
5170 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5171 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5172 (or (and (eq org-cycle-emulate-tab 'white)
5173 (= (match-end 0) (point-at-eol)))
5174 (and (eq org-cycle-emulate-tab 'whitestart)
5175 (>= (match-end 0) pos))))
5177 (eq org-cycle-emulate-tab t))
5178 (call-interactively (global-key-binding "\t")))
5180 (t (save-excursion
5181 (org-back-to-heading)
5182 (org-cycle)))))))
5184 (defun org-cycle-internal-global ()
5185 "Do the global cycling action."
5186 (cond
5187 ((and (eq last-command this-command)
5188 (eq org-cycle-global-status 'overview))
5189 ;; We just created the overview - now do table of contents
5190 ;; This can be slow in very large buffers, so indicate action
5191 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5192 (message "CONTENTS...")
5193 (org-content)
5194 (message "CONTENTS...done")
5195 (setq org-cycle-global-status 'contents)
5196 (run-hook-with-args 'org-cycle-hook 'contents))
5198 ((and (eq last-command this-command)
5199 (eq org-cycle-global-status 'contents))
5200 ;; We just showed the table of contents - now show everything
5201 (run-hook-with-args 'org-pre-cycle-hook 'all)
5202 (show-all)
5203 (message "SHOW ALL")
5204 (setq org-cycle-global-status 'all)
5205 (run-hook-with-args 'org-cycle-hook 'all))
5208 ;; Default action: go to overview
5209 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5210 (org-overview)
5211 (message "OVERVIEW")
5212 (setq org-cycle-global-status 'overview)
5213 (run-hook-with-args 'org-cycle-hook 'overview))))
5215 (defun org-cycle-internal-local ()
5216 "Do the local cycling action."
5217 (org-back-to-heading)
5218 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5219 ;; First, some boundaries
5220 (save-excursion
5221 (org-back-to-heading)
5222 (setq level (funcall outline-level))
5223 (save-excursion
5224 (beginning-of-line 2)
5225 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5226 ; XEmacs does not have `next-single-char-property-change'
5227 ; I'm not sure about Emacs 21.
5228 (while (and (not (eobp)) ;; this is like `next-line'
5229 (get-char-property (1- (point)) 'invisible))
5230 (beginning-of-line 2))
5231 (while (and (not (eobp)) ;; this is like `next-line'
5232 (get-char-property (1- (point)) 'invisible))
5233 (goto-char (next-single-char-property-change (point) 'invisible))
5234 ;;;??? (or (bolp) (beginning-of-line 2))))
5235 (and (eolp) (beginning-of-line 2))))
5236 (setq eol (point)))
5237 (outline-end-of-heading) (setq eoh (point))
5238 (save-excursion
5239 (outline-next-heading)
5240 (setq has-children (and (org-at-heading-p t)
5241 (> (funcall outline-level) level))))
5242 (org-end-of-subtree t)
5243 (unless (eobp)
5244 (skip-chars-forward " \t\n")
5245 (beginning-of-line 1) ; in case this is an item
5247 (setq eos (if (eobp) (point) (1- (point)))))
5248 ;; Find out what to do next and set `this-command'
5249 (cond
5250 ((= eos eoh)
5251 ;; Nothing is hidden behind this heading
5252 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5253 (message "EMPTY ENTRY")
5254 (setq org-cycle-subtree-status nil)
5255 (save-excursion
5256 (goto-char eos)
5257 (outline-next-heading)
5258 (if (org-invisible-p) (org-flag-heading nil))))
5259 ((and (or (>= eol eos)
5260 (not (string-match "\\S-" (buffer-substring eol eos))))
5261 (or has-children
5262 (not (setq children-skipped
5263 org-cycle-skip-children-state-if-no-children))))
5264 ;; Entire subtree is hidden in one line: children view
5265 (run-hook-with-args 'org-pre-cycle-hook 'children)
5266 (org-show-entry)
5267 (show-children)
5268 (message "CHILDREN")
5269 (save-excursion
5270 (goto-char eos)
5271 (outline-next-heading)
5272 (if (org-invisible-p) (org-flag-heading nil)))
5273 (setq org-cycle-subtree-status 'children)
5274 (run-hook-with-args 'org-cycle-hook 'children))
5275 ((or children-skipped
5276 (and (eq last-command this-command)
5277 (eq org-cycle-subtree-status 'children)))
5278 ;; We just showed the children, or no children are there,
5279 ;; now show everything.
5280 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5281 (org-show-subtree)
5282 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5283 (setq org-cycle-subtree-status 'subtree)
5284 (run-hook-with-args 'org-cycle-hook 'subtree))
5286 ;; Default action: hide the subtree.
5287 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5288 (hide-subtree)
5289 (message "FOLDED")
5290 (setq org-cycle-subtree-status 'folded)
5291 (run-hook-with-args 'org-cycle-hook 'folded)))))
5293 ;;;###autoload
5294 (defun org-global-cycle (&optional arg)
5295 "Cycle the global visibility. For details see `org-cycle'.
5296 With C-u prefix arg, switch to startup visibility.
5297 With a numeric prefix, show all headlines up to that level."
5298 (interactive "P")
5299 (let ((org-cycle-include-plain-lists
5300 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5301 (cond
5302 ((integerp arg)
5303 (show-all)
5304 (hide-sublevels arg)
5305 (setq org-cycle-global-status 'contents))
5306 ((equal arg '(4))
5307 (org-set-startup-visibility)
5308 (message "Startup visibility, plus VISIBILITY properties."))
5310 (org-cycle '(4))))))
5312 (defun org-set-startup-visibility ()
5313 "Set the visibility required by startup options and properties."
5314 (cond
5315 ((eq org-startup-folded t)
5316 (org-cycle '(4)))
5317 ((eq org-startup-folded 'content)
5318 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5319 (org-cycle '(4)) (org-cycle '(4)))))
5320 (unless (eq org-startup-folded 'showeverything)
5321 (if org-hide-block-startup (org-hide-block-all))
5322 (org-set-visibility-according-to-property 'no-cleanup)
5323 (org-cycle-hide-archived-subtrees 'all)
5324 (org-cycle-hide-drawers 'all)
5325 (org-cycle-show-empty-lines 'all)))
5327 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5328 "Switch subtree visibilities according to :VISIBILITY: property."
5329 (interactive)
5330 (let (org-show-entry-below state)
5331 (save-excursion
5332 (goto-char (point-min))
5333 (while (re-search-forward
5334 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5335 nil t)
5336 (setq state (match-string 1))
5337 (save-excursion
5338 (org-back-to-heading t)
5339 (hide-subtree)
5340 (org-reveal)
5341 (cond
5342 ((equal state '("fold" "folded"))
5343 (hide-subtree))
5344 ((equal state "children")
5345 (org-show-hidden-entry)
5346 (show-children))
5347 ((equal state "content")
5348 (save-excursion
5349 (save-restriction
5350 (org-narrow-to-subtree)
5351 (org-content))))
5352 ((member state '("all" "showall"))
5353 (show-subtree)))))
5354 (unless no-cleanup
5355 (org-cycle-hide-archived-subtrees 'all)
5356 (org-cycle-hide-drawers 'all)
5357 (org-cycle-show-empty-lines 'all)))))
5359 (defun org-overview ()
5360 "Switch to overview mode, showing only top-level headlines.
5361 Really, this shows all headlines with level equal or greater than the level
5362 of the first headline in the buffer. This is important, because if the
5363 first headline is not level one, then (hide-sublevels 1) gives confusing
5364 results."
5365 (interactive)
5366 (let ((level (save-excursion
5367 (goto-char (point-min))
5368 (if (re-search-forward (concat "^" outline-regexp) nil t)
5369 (progn
5370 (goto-char (match-beginning 0))
5371 (funcall outline-level))))))
5372 (and level (hide-sublevels level))))
5374 (defun org-content (&optional arg)
5375 "Show all headlines in the buffer, like a table of contents.
5376 With numerical argument N, show content up to level N."
5377 (interactive "P")
5378 (save-excursion
5379 ;; Visit all headings and show their offspring
5380 (and (integerp arg) (org-overview))
5381 (goto-char (point-max))
5382 (catch 'exit
5383 (while (and (progn (condition-case nil
5384 (outline-previous-visible-heading 1)
5385 (error (goto-char (point-min))))
5387 (looking-at outline-regexp))
5388 (if (integerp arg)
5389 (show-children (1- arg))
5390 (show-branches))
5391 (if (bobp) (throw 'exit nil))))))
5394 (defun org-optimize-window-after-visibility-change (state)
5395 "Adjust the window after a change in outline visibility.
5396 This function is the default value of the hook `org-cycle-hook'."
5397 (when (get-buffer-window (current-buffer))
5398 (cond
5399 ((eq state 'content) nil)
5400 ((eq state 'all) nil)
5401 ((eq state 'folded) nil)
5402 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5403 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5405 ;; FIXME: no longer in use
5406 (defun org-compact-display-after-subtree-move ()
5407 "Show a compacter version of the tree of the entry's parent."
5408 (save-excursion
5409 (if (org-up-heading-safe)
5410 (progn
5411 (hide-subtree)
5412 (show-entry)
5413 (show-children)
5414 (org-cycle-show-empty-lines 'children)
5415 (org-cycle-hide-drawers 'children))
5416 (org-overview))))
5418 (defun org-remove-empty-overlays-at (pos)
5419 "Remove outline overlays that do not contain non-white stuff."
5420 (mapc
5421 (lambda (o)
5422 (and (eq 'outline (org-overlay-get o 'invisible))
5423 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5424 (org-overlay-end o))))
5425 (org-delete-overlay o)))
5426 (org-overlays-at pos)))
5428 (defun org-clean-visibility-after-subtree-move ()
5429 "Fix visibility issues after moving a subtree."
5430 ;; First, find a reasonable region to look at:
5431 ;; Start two siblings above, end three below
5432 (let* ((beg (save-excursion
5433 (and (org-get-last-sibling)
5434 (org-get-last-sibling))
5435 (point)))
5436 (end (save-excursion
5437 (and (org-get-next-sibling)
5438 (org-get-next-sibling)
5439 (org-get-next-sibling))
5440 (if (org-at-heading-p)
5441 (point-at-eol)
5442 (point))))
5443 (level (looking-at "\\*+"))
5444 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5445 (save-excursion
5446 (save-restriction
5447 (narrow-to-region beg end)
5448 (when re
5449 ;; Properly fold already folded siblings
5450 (goto-char (point-min))
5451 (while (re-search-forward re nil t)
5452 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5453 (hide-entry))))
5454 (org-cycle-show-empty-lines 'overview)
5455 (org-cycle-hide-drawers 'overview)))))
5457 (defun org-cycle-show-empty-lines (state)
5458 "Show empty lines above all visible headlines.
5459 The region to be covered depends on STATE when called through
5460 `org-cycle-hook'. Lisp program can use t for STATE to get the
5461 entire buffer covered. Note that an empty line is only shown if there
5462 are at least `org-cycle-separator-lines' empty lines before the headline."
5463 (when (not (= org-cycle-separator-lines 0))
5464 (save-excursion
5465 (let* ((n (abs org-cycle-separator-lines))
5466 (re (cond
5467 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5468 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5469 (t (let ((ns (number-to-string (- n 2))))
5470 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5471 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5472 beg end b e)
5473 (cond
5474 ((memq state '(overview contents t))
5475 (setq beg (point-min) end (point-max)))
5476 ((memq state '(children folded))
5477 (setq beg (point) end (progn (org-end-of-subtree t t)
5478 (beginning-of-line 2)
5479 (point)))))
5480 (when beg
5481 (goto-char beg)
5482 (while (re-search-forward re end t)
5483 (unless (get-char-property (match-end 1) 'invisible)
5484 (setq e (match-end 1))
5485 (if (< org-cycle-separator-lines 0)
5486 (setq b (save-excursion
5487 (goto-char (match-beginning 0))
5488 (org-back-over-empty-lines)
5489 (if (save-excursion
5490 (goto-char (max (point-min) (1- (point))))
5491 (org-on-heading-p))
5492 (1- (point))
5493 (point))))
5494 (setq b (match-beginning 1)))
5495 (outline-flag-region b e nil)))))))
5496 ;; Never hide empty lines at the end of the file.
5497 (save-excursion
5498 (goto-char (point-max))
5499 (outline-previous-heading)
5500 (outline-end-of-heading)
5501 (if (and (looking-at "[ \t\n]+")
5502 (= (match-end 0) (point-max)))
5503 (outline-flag-region (point) (match-end 0) nil))))
5505 (defun org-show-empty-lines-in-parent ()
5506 "Move to the parent and re-show empty lines before visible headlines."
5507 (save-excursion
5508 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5509 (org-cycle-show-empty-lines context))))
5511 (defun org-files-list ()
5512 "Return `org-agenda-files' list, plus all open org-mode files.
5513 This is useful for operations that need to scan all of a user's
5514 open and agenda-wise Org files."
5515 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5516 (dolist (buf (buffer-list))
5517 (with-current-buffer buf
5518 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5519 (let ((file (expand-file-name (buffer-file-name))))
5520 (unless (member file files)
5521 (push file files))))))
5522 files))
5524 (defsubst org-entry-beginning-position ()
5525 "Return the beginning position of the current entry."
5526 (save-excursion (outline-back-to-heading t) (point)))
5528 (defsubst org-entry-end-position ()
5529 "Return the end position of the current entry."
5530 (save-excursion (outline-next-heading) (point)))
5532 (defun org-cycle-hide-drawers (state)
5533 "Re-hide all drawers after a visibility state change."
5534 (when (and (org-mode-p)
5535 (not (memq state '(overview folded contents))))
5536 (save-excursion
5537 (let* ((globalp (memq state '(contents all)))
5538 (beg (if globalp (point-min) (point)))
5539 (end (if globalp (point-max)
5540 (if (eq state 'children)
5541 (save-excursion (outline-next-heading) (point))
5542 (org-end-of-subtree t)))))
5543 (goto-char beg)
5544 (while (re-search-forward org-drawer-regexp end t)
5545 (org-flag-drawer t))))))
5547 (defun org-flag-drawer (flag)
5548 (save-excursion
5549 (beginning-of-line 1)
5550 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5551 (let ((b (match-end 0))
5552 (outline-regexp org-outline-regexp))
5553 (if (re-search-forward
5554 "^[ \t]*:END:"
5555 (save-excursion (outline-next-heading) (point)) t)
5556 (outline-flag-region b (point-at-eol) flag)
5557 (error ":END: line missing at position %s" b))))))
5559 (defun org-subtree-end-visible-p ()
5560 "Is the end of the current subtree visible?"
5561 (pos-visible-in-window-p
5562 (save-excursion (org-end-of-subtree t) (point))))
5564 (defun org-first-headline-recenter (&optional N)
5565 "Move cursor to the first headline and recenter the headline.
5566 Optional argument N means, put the headline into the Nth line of the window."
5567 (goto-char (point-min))
5568 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5569 (beginning-of-line)
5570 (recenter (prefix-numeric-value N))))
5572 ;;; Folding of blocks
5574 (defconst org-block-regexp
5576 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5577 "Regular expression for hiding blocks.")
5579 (defvar org-hide-block-overlays nil
5580 "Overays hiding blocks.")
5581 (make-variable-buffer-local 'org-hide-block-overlays)
5583 (defun org-block-map (function &optional start end)
5584 "Call func at the head of all source blocks in the current
5585 buffer. Optional arguments START and END can be used to limit
5586 the range."
5587 (let ((start (or start (point-min)))
5588 (end (or end (point-max))))
5589 (save-excursion
5590 (goto-char start)
5591 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5592 (save-excursion
5593 (save-match-data
5594 (goto-char (match-beginning 0))
5595 (funcall function)))))))
5597 (defun org-hide-block-toggle-all ()
5598 "Toggle the visibility of all blocks in the current buffer."
5599 (org-block-map #'org-hide-block-toggle))
5601 (defun org-hide-block-all ()
5602 "Fold all blocks in the current buffer."
5603 (interactive)
5604 (org-show-block-all)
5605 (org-block-map #'org-hide-block-toggle-maybe))
5607 (defun org-show-block-all ()
5608 "Unfold all blocks in the current buffer."
5609 (mapc 'org-delete-overlay org-hide-block-overlays)
5610 (setq org-hide-block-overlays nil))
5612 (defun org-hide-block-toggle-maybe ()
5613 "Toggle visibility of block at point."
5614 (interactive)
5615 (let ((case-fold-search t))
5616 (if (save-excursion
5617 (beginning-of-line 1)
5618 (looking-at org-block-regexp))
5619 (progn (org-hide-block-toggle)
5620 t) ;; to signal that we took action
5621 nil))) ;; to signal that we did not
5623 (defun org-hide-block-toggle (&optional force)
5624 "Toggle the visibility of the current block."
5625 (interactive)
5626 (save-excursion
5627 (beginning-of-line)
5628 (if (re-search-forward org-block-regexp nil t)
5629 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5630 (end (match-end 0)) ;; end of entire body
5632 (if (memq t (mapcar (lambda (overlay)
5633 (eq (org-overlay-get overlay 'invisible)
5634 'org-hide-block))
5635 (org-overlays-at start)))
5636 (if (or (not force) (eq force 'off))
5637 (mapc (lambda (ov)
5638 (when (member ov org-hide-block-overlays)
5639 (setq org-hide-block-overlays
5640 (delq ov org-hide-block-overlays)))
5641 (when (eq (org-overlay-get ov 'invisible)
5642 'org-hide-block)
5643 (org-delete-overlay ov)))
5644 (org-overlays-at start)))
5645 (setq ov (org-make-overlay start end))
5646 (org-overlay-put ov 'invisible 'org-hide-block)
5647 ;; make the block accessible to isearch
5648 (org-overlay-put
5649 ov 'isearch-open-invisible
5650 (lambda (ov)
5651 (when (member ov org-hide-block-overlays)
5652 (setq org-hide-block-overlays
5653 (delq ov org-hide-block-overlays)))
5654 (when (eq (org-overlay-get ov 'invisible)
5655 'org-hide-block)
5656 (org-delete-overlay ov))))
5657 (push ov org-hide-block-overlays)))
5658 (error "Not looking at a source block"))))
5660 ;; org-tab-after-check-for-cycling-hook
5661 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5662 ;; Remove overlays when changing major mode
5663 (add-hook 'org-mode-hook
5664 (lambda () (org-add-hook 'change-major-mode-hook
5665 'org-show-block-all 'append 'local)))
5667 ;;; Org-goto
5669 (defvar org-goto-window-configuration nil)
5670 (defvar org-goto-marker nil)
5671 (defvar org-goto-map
5672 (let ((map (make-sparse-keymap)))
5673 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5674 (while (setq cmd (pop cmds))
5675 (substitute-key-definition cmd cmd map global-map)))
5676 (suppress-keymap map)
5677 (org-defkey map "\C-m" 'org-goto-ret)
5678 (org-defkey map [(return)] 'org-goto-ret)
5679 (org-defkey map [(left)] 'org-goto-left)
5680 (org-defkey map [(right)] 'org-goto-right)
5681 (org-defkey map [(control ?g)] 'org-goto-quit)
5682 (org-defkey map "\C-i" 'org-cycle)
5683 (org-defkey map [(tab)] 'org-cycle)
5684 (org-defkey map [(down)] 'outline-next-visible-heading)
5685 (org-defkey map [(up)] 'outline-previous-visible-heading)
5686 (if org-goto-auto-isearch
5687 (if (fboundp 'define-key-after)
5688 (define-key-after map [t] 'org-goto-local-auto-isearch)
5689 nil)
5690 (org-defkey map "q" 'org-goto-quit)
5691 (org-defkey map "n" 'outline-next-visible-heading)
5692 (org-defkey map "p" 'outline-previous-visible-heading)
5693 (org-defkey map "f" 'outline-forward-same-level)
5694 (org-defkey map "b" 'outline-backward-same-level)
5695 (org-defkey map "u" 'outline-up-heading))
5696 (org-defkey map "/" 'org-occur)
5697 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5698 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5699 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5700 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5701 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5702 map))
5704 (defconst org-goto-help
5705 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5706 RET=jump to location [Q]uit and return to previous location
5707 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5709 (defvar org-goto-start-pos) ; dynamically scoped parameter
5711 ;; FIXME: Docstring doe not mention both interfaces
5712 (defun org-goto (&optional alternative-interface)
5713 "Look up a different location in the current file, keeping current visibility.
5715 When you want look-up or go to a different location in a document, the
5716 fastest way is often to fold the entire buffer and then dive into the tree.
5717 This method has the disadvantage, that the previous location will be folded,
5718 which may not be what you want.
5720 This command works around this by showing a copy of the current buffer
5721 in an indirect buffer, in overview mode. You can dive into the tree in
5722 that copy, use org-occur and incremental search to find a location.
5723 When pressing RET or `Q', the command returns to the original buffer in
5724 which the visibility is still unchanged. After RET is will also jump to
5725 the location selected in the indirect buffer and expose the
5726 the headline hierarchy above."
5727 (interactive "P")
5728 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5729 (org-refile-use-outline-path t)
5730 (org-refile-target-verify-function nil)
5731 (interface
5732 (if (not alternative-interface)
5733 org-goto-interface
5734 (if (eq org-goto-interface 'outline)
5735 'outline-path-completion
5736 'outline)))
5737 (org-goto-start-pos (point))
5738 (selected-point
5739 (if (eq interface 'outline)
5740 (car (org-get-location (current-buffer) org-goto-help))
5741 (nth 3 (org-refile-get-location "Goto: ")))))
5742 (if selected-point
5743 (progn
5744 (org-mark-ring-push org-goto-start-pos)
5745 (goto-char selected-point)
5746 (if (or (org-invisible-p) (org-invisible-p2))
5747 (org-show-context 'org-goto)))
5748 (message "Quit"))))
5750 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5751 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5752 (defvar org-goto-local-auto-isearch-map) ; defined below
5754 (defun org-get-location (buf help)
5755 "Let the user select a location in the Org-mode buffer BUF.
5756 This function uses a recursive edit. It returns the selected position
5757 or nil."
5758 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5759 (isearch-hide-immediately nil)
5760 (isearch-search-fun-function
5761 (lambda () 'org-goto-local-search-headings))
5762 (org-goto-selected-point org-goto-exit-command))
5763 (save-excursion
5764 (save-window-excursion
5765 (delete-other-windows)
5766 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5767 (switch-to-buffer
5768 (condition-case nil
5769 (make-indirect-buffer (current-buffer) "*org-goto*")
5770 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5771 (with-output-to-temp-buffer "*Help*"
5772 (princ help))
5773 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5774 (setq buffer-read-only nil)
5775 (let ((org-startup-truncated t)
5776 (org-startup-folded nil)
5777 (org-startup-align-all-tables nil))
5778 (org-mode)
5779 (org-overview))
5780 (setq buffer-read-only t)
5781 (if (and (boundp 'org-goto-start-pos)
5782 (integer-or-marker-p org-goto-start-pos))
5783 (let ((org-show-hierarchy-above t)
5784 (org-show-siblings t)
5785 (org-show-following-heading t))
5786 (goto-char org-goto-start-pos)
5787 (and (org-invisible-p) (org-show-context)))
5788 (goto-char (point-min)))
5789 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5790 (message "Select location and press RET")
5791 (use-local-map org-goto-map)
5792 (recursive-edit)
5794 (kill-buffer "*org-goto*")
5795 (cons org-goto-selected-point org-goto-exit-command)))
5797 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5798 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5799 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5800 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5802 (defun org-goto-local-search-headings (string bound noerror)
5803 "Search and make sure that any matches are in headlines."
5804 (catch 'return
5805 (while (if isearch-forward
5806 (search-forward string bound noerror)
5807 (search-backward string bound noerror))
5808 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5809 (and (member :headline context)
5810 (not (member :tags context))))
5811 (throw 'return (point))))))
5813 (defun org-goto-local-auto-isearch ()
5814 "Start isearch."
5815 (interactive)
5816 (goto-char (point-min))
5817 (let ((keys (this-command-keys)))
5818 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5819 (isearch-mode t)
5820 (isearch-process-search-char (string-to-char keys)))))
5822 (defun org-goto-ret (&optional arg)
5823 "Finish `org-goto' by going to the new location."
5824 (interactive "P")
5825 (setq org-goto-selected-point (point)
5826 org-goto-exit-command 'return)
5827 (throw 'exit nil))
5829 (defun org-goto-left ()
5830 "Finish `org-goto' by going to the new location."
5831 (interactive)
5832 (if (org-on-heading-p)
5833 (progn
5834 (beginning-of-line 1)
5835 (setq org-goto-selected-point (point)
5836 org-goto-exit-command 'left)
5837 (throw 'exit nil))
5838 (error "Not on a heading")))
5840 (defun org-goto-right ()
5841 "Finish `org-goto' by going to the new location."
5842 (interactive)
5843 (if (org-on-heading-p)
5844 (progn
5845 (setq org-goto-selected-point (point)
5846 org-goto-exit-command 'right)
5847 (throw 'exit nil))
5848 (error "Not on a heading")))
5850 (defun org-goto-quit ()
5851 "Finish `org-goto' without cursor motion."
5852 (interactive)
5853 (setq org-goto-selected-point nil)
5854 (setq org-goto-exit-command 'quit)
5855 (throw 'exit nil))
5857 ;;; Indirect buffer display of subtrees
5859 (defvar org-indirect-dedicated-frame nil
5860 "This is the frame being used for indirect tree display.")
5861 (defvar org-last-indirect-buffer nil)
5863 (defun org-tree-to-indirect-buffer (&optional arg)
5864 "Create indirect buffer and narrow it to current subtree.
5865 With numerical prefix ARG, go up to this level and then take that tree.
5866 If ARG is negative, go up that many levels.
5867 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5868 indirect buffer previously made with this command, to avoid proliferation of
5869 indirect buffers. However, when you call the command with a `C-u' prefix, or
5870 when `org-indirect-buffer-display' is `new-frame', the last buffer
5871 is kept so that you can work with several indirect buffers at the same time.
5872 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5873 requests that a new frame be made for the new buffer, so that the dedicated
5874 frame is not changed."
5875 (interactive "P")
5876 (let ((cbuf (current-buffer))
5877 (cwin (selected-window))
5878 (pos (point))
5879 beg end level heading ibuf)
5880 (save-excursion
5881 (org-back-to-heading t)
5882 (when (numberp arg)
5883 (setq level (org-outline-level))
5884 (if (< arg 0) (setq arg (+ level arg)))
5885 (while (> (setq level (org-outline-level)) arg)
5886 (outline-up-heading 1 t)))
5887 (setq beg (point)
5888 heading (org-get-heading))
5889 (org-end-of-subtree t t) (setq end (point)))
5890 (if (and (buffer-live-p org-last-indirect-buffer)
5891 (not (eq org-indirect-buffer-display 'new-frame))
5892 (not arg))
5893 (kill-buffer org-last-indirect-buffer))
5894 (setq ibuf (org-get-indirect-buffer cbuf)
5895 org-last-indirect-buffer ibuf)
5896 (cond
5897 ((or (eq org-indirect-buffer-display 'new-frame)
5898 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5899 (select-frame (make-frame))
5900 (delete-other-windows)
5901 (switch-to-buffer ibuf)
5902 (org-set-frame-title heading))
5903 ((eq org-indirect-buffer-display 'dedicated-frame)
5904 (raise-frame
5905 (select-frame (or (and org-indirect-dedicated-frame
5906 (frame-live-p org-indirect-dedicated-frame)
5907 org-indirect-dedicated-frame)
5908 (setq org-indirect-dedicated-frame (make-frame)))))
5909 (delete-other-windows)
5910 (switch-to-buffer ibuf)
5911 (org-set-frame-title (concat "Indirect: " heading)))
5912 ((eq org-indirect-buffer-display 'current-window)
5913 (switch-to-buffer ibuf))
5914 ((eq org-indirect-buffer-display 'other-window)
5915 (pop-to-buffer ibuf))
5916 (t (error "Invalid value")))
5917 (if (featurep 'xemacs)
5918 (save-excursion (org-mode) (turn-on-font-lock)))
5919 (narrow-to-region beg end)
5920 (show-all)
5921 (goto-char pos)
5922 (and (window-live-p cwin) (select-window cwin))))
5924 (defun org-get-indirect-buffer (&optional buffer)
5925 (setq buffer (or buffer (current-buffer)))
5926 (let ((n 1) (base (buffer-name buffer)) bname)
5927 (while (buffer-live-p
5928 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5929 (setq n (1+ n)))
5930 (condition-case nil
5931 (make-indirect-buffer buffer bname 'clone)
5932 (error (make-indirect-buffer buffer bname)))))
5934 (defun org-set-frame-title (title)
5935 "Set the title of the current frame to the string TITLE."
5936 ;; FIXME: how to name a single frame in XEmacs???
5937 (unless (featurep 'xemacs)
5938 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5940 ;;;; Structure editing
5942 ;;; Inserting headlines
5944 (defun org-previous-line-empty-p ()
5945 (save-excursion
5946 (and (not (bobp))
5947 (or (beginning-of-line 0) t)
5948 (save-match-data
5949 (looking-at "[ \t]*$")))))
5951 (defun org-insert-heading (&optional force-heading)
5952 "Insert a new heading or item with same depth at point.
5953 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5954 If point is at the beginning of a headline, insert a sibling before the
5955 current headline. If point is not at the beginning, do not split the line,
5956 but create the new headline after the current line."
5957 (interactive "P")
5958 (if (= (buffer-size) 0)
5959 (insert "\n* ")
5960 (when (or force-heading (not (org-insert-item)))
5961 (let* ((empty-line-p nil)
5962 (head (save-excursion
5963 (condition-case nil
5964 (progn
5965 (org-back-to-heading)
5966 (setq empty-line-p (org-previous-line-empty-p))
5967 (match-string 0))
5968 (error "*"))))
5969 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5970 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5971 pos hide-previous previous-pos)
5972 (cond
5973 ((and (org-on-heading-p) (bolp)
5974 (or (bobp)
5975 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5976 ;; insert before the current line
5977 (open-line (if blank 2 1)))
5978 ((and (bolp)
5979 (not org-insert-heading-respect-content)
5980 (or (bobp)
5981 (save-excursion
5982 (backward-char 1) (not (org-invisible-p)))))
5983 ;; insert right here
5984 nil)
5986 ;; somewhere in the line
5987 (save-excursion
5988 (setq previous-pos (point-at-bol))
5989 (end-of-line)
5990 (setq hide-previous (org-invisible-p)))
5991 (and org-insert-heading-respect-content (org-show-subtree))
5992 (let ((split
5993 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5994 (save-excursion
5995 (let ((p (point)))
5996 (goto-char (point-at-bol))
5997 (and (looking-at org-complex-heading-regexp)
5998 (> p (match-beginning 4)))))))
5999 tags pos)
6000 (cond
6001 (org-insert-heading-respect-content
6002 (org-end-of-subtree nil t)
6003 (or (bolp) (newline))
6004 (or (org-previous-line-empty-p)
6005 (and blank (newline)))
6006 (open-line 1))
6007 ((org-on-heading-p)
6008 (when hide-previous
6009 (show-children)
6010 (org-show-entry))
6011 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6012 (setq tags (and (match-end 2) (match-string 2)))
6013 (and (match-end 1)
6014 (delete-region (match-beginning 1) (match-end 1)))
6015 (setq pos (point-at-bol))
6016 (or split (end-of-line 1))
6017 (delete-horizontal-space)
6018 (newline (if blank 2 1))
6019 (when tags
6020 (save-excursion
6021 (goto-char pos)
6022 (end-of-line 1)
6023 (insert " " tags)
6024 (org-set-tags nil 'align))))
6026 (or split (end-of-line 1))
6027 (newline (if blank 2 1)))))))
6028 (insert head) (just-one-space)
6029 (setq pos (point))
6030 (end-of-line 1)
6031 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6032 (when (and org-insert-heading-respect-content hide-previous)
6033 (save-excursion
6034 (goto-char previous-pos)
6035 (hide-subtree)))
6036 (run-hooks 'org-insert-heading-hook)))))
6038 (defun org-get-heading (&optional no-tags)
6039 "Return the heading of the current entry, without the stars."
6040 (save-excursion
6041 (org-back-to-heading t)
6042 (if (looking-at
6043 (if no-tags
6044 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6045 "\\*+[ \t]+\\([^\r\n]*\\)"))
6046 (match-string 1) "")))
6048 (defun org-heading-components ()
6049 "Return the components of the current heading.
6050 This is a list with the following elements:
6051 - the level as an integer
6052 - the reduced level, different if `org-odd-levels-only' is set.
6053 - the TODO keyword, or nil
6054 - the priority character, like ?A, or nil if no priority is given
6055 - the headline text itself, or the tags string if no headline text
6056 - the tags string, or nil."
6057 (save-excursion
6058 (org-back-to-heading t)
6059 (if (looking-at org-complex-heading-regexp)
6060 (list (length (match-string 1))
6061 (org-reduced-level (length (match-string 1)))
6062 (org-match-string-no-properties 2)
6063 (and (match-end 3) (aref (match-string 3) 2))
6064 (org-match-string-no-properties 4)
6065 (org-match-string-no-properties 5)))))
6067 (defun org-get-entry ()
6068 "Get the entry text, after heading, entire subtree."
6069 (save-excursion
6070 (org-back-to-heading t)
6071 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6073 (defun org-insert-heading-after-current ()
6074 "Insert a new heading with same level as current, after current subtree."
6075 (interactive)
6076 (org-back-to-heading)
6077 (org-insert-heading)
6078 (org-move-subtree-down)
6079 (end-of-line 1))
6081 (defun org-insert-heading-respect-content ()
6082 (interactive)
6083 (let ((org-insert-heading-respect-content t))
6084 (org-insert-heading t)))
6086 (defun org-insert-todo-heading-respect-content (&optional force-state)
6087 (interactive "P")
6088 (let ((org-insert-heading-respect-content t))
6089 (org-insert-todo-heading force-state t)))
6091 (defun org-insert-todo-heading (arg &optional force-heading)
6092 "Insert a new heading with the same level and TODO state as current heading.
6093 If the heading has no TODO state, or if the state is DONE, use the first
6094 state (TODO by default). Also with prefix arg, force first state."
6095 (interactive "P")
6096 (when (or force-heading (not (org-insert-item 'checkbox)))
6097 (org-insert-heading force-heading)
6098 (save-excursion
6099 (org-back-to-heading)
6100 (outline-previous-heading)
6101 (looking-at org-todo-line-regexp))
6102 (let*
6103 ((new-mark-x
6104 (if (or arg
6105 (not (match-beginning 2))
6106 (member (match-string 2) org-done-keywords))
6107 (car org-todo-keywords-1)
6108 (match-string 2)))
6109 (new-mark
6111 (run-hook-with-args-until-success
6112 'org-todo-get-default-hook new-mark-x nil)
6113 new-mark-x)))
6114 (beginning-of-line 1)
6115 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6116 (if org-treat-insert-todo-heading-as-state-change
6117 (org-todo new-mark)
6118 (insert new-mark " "))))
6119 (when org-provide-todo-statistics
6120 (org-update-parent-todo-statistics))))
6122 (defun org-insert-subheading (arg)
6123 "Insert a new subheading and demote it.
6124 Works for outline headings and for plain lists alike."
6125 (interactive "P")
6126 (org-insert-heading arg)
6127 (cond
6128 ((org-on-heading-p) (org-do-demote))
6129 ((org-at-item-p) (org-indent-item 1))))
6131 (defun org-insert-todo-subheading (arg)
6132 "Insert a new subheading with TODO keyword or checkbox and demote it.
6133 Works for outline headings and for plain lists alike."
6134 (interactive "P")
6135 (org-insert-todo-heading arg)
6136 (cond
6137 ((org-on-heading-p) (org-do-demote))
6138 ((org-at-item-p) (org-indent-item 1))))
6140 ;;; Promotion and Demotion
6142 (defvar org-after-demote-entry-hook nil
6143 "Hook run after an entry has been demoted.
6144 The cursor will be at the beginning of the entry.
6145 When a subtree is being demoted, the hook will be called for each node.")
6147 (defvar org-after-promote-entry-hook nil
6148 "Hook run after an entry has been promoted.
6149 The cursor will be at the beginning of the entry.
6150 When a subtree is being promoted, the hook will be called for each node.")
6152 (defun org-promote-subtree ()
6153 "Promote the entire subtree.
6154 See also `org-promote'."
6155 (interactive)
6156 (save-excursion
6157 (org-map-tree 'org-promote))
6158 (org-fix-position-after-promote))
6160 (defun org-demote-subtree ()
6161 "Demote the entire subtree. See `org-demote'.
6162 See also `org-promote'."
6163 (interactive)
6164 (save-excursion
6165 (org-map-tree 'org-demote))
6166 (org-fix-position-after-promote))
6169 (defun org-do-promote ()
6170 "Promote the current heading higher up the tree.
6171 If the region is active in `transient-mark-mode', promote all headings
6172 in the region."
6173 (interactive)
6174 (save-excursion
6175 (if (org-region-active-p)
6176 (org-map-region 'org-promote (region-beginning) (region-end))
6177 (org-promote)))
6178 (org-fix-position-after-promote))
6180 (defun org-do-demote ()
6181 "Demote the current heading lower down the tree.
6182 If the region is active in `transient-mark-mode', demote all headings
6183 in the region."
6184 (interactive)
6185 (save-excursion
6186 (if (org-region-active-p)
6187 (org-map-region 'org-demote (region-beginning) (region-end))
6188 (org-demote)))
6189 (org-fix-position-after-promote))
6191 (defun org-fix-position-after-promote ()
6192 "Make sure that after pro/demotion cursor position is right."
6193 (let ((pos (point)))
6194 (when (save-excursion
6195 (beginning-of-line 1)
6196 (looking-at org-todo-line-regexp)
6197 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6198 (cond ((eobp) (insert " "))
6199 ((eolp) (insert " "))
6200 ((equal (char-after) ?\ ) (forward-char 1))))))
6202 (defun org-current-level ()
6203 "Return the level of the current entry, or nil if before the first headline.
6204 The level is the number of stars at the beginning of the headline."
6205 (save-excursion
6206 (condition-case nil
6207 (progn
6208 (org-back-to-heading t)
6209 (funcall outline-level))
6210 (error nil))))
6212 (defun org-reduced-level (l)
6213 "Compute the effective level of a heading.
6214 This takes into account the setting of `org-odd-levels-only'."
6215 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6217 (defun org-get-valid-level (level &optional change)
6218 "Rectify a level change under the influence of `org-odd-levels-only'
6219 LEVEL is a current level, CHANGE is by how much the level should be
6220 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6221 even level numbers will become the next higher odd number."
6222 (if org-odd-levels-only
6223 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6224 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6225 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6226 (max 1 (+ level (or change 0)))))
6228 (if (boundp 'define-obsolete-function-alias)
6229 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6230 (define-obsolete-function-alias 'org-get-legal-level
6231 'org-get-valid-level)
6232 (define-obsolete-function-alias 'org-get-legal-level
6233 'org-get-valid-level "23.1")))
6235 (defun org-promote ()
6236 "Promote the current heading higher up the tree.
6237 If the region is active in `transient-mark-mode', promote all headings
6238 in the region."
6239 (org-back-to-heading t)
6240 (let* ((level (save-match-data (funcall outline-level)))
6241 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6242 (diff (abs (- level (length up-head) -1))))
6243 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6244 (replace-match up-head nil t)
6245 ;; Fixup tag positioning
6246 (and org-auto-align-tags (org-set-tags nil t))
6247 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6248 (run-hooks 'org-after-promote-entry-hook)))
6250 (defun org-demote ()
6251 "Demote the current heading lower down the tree.
6252 If the region is active in `transient-mark-mode', demote all headings
6253 in the region."
6254 (org-back-to-heading t)
6255 (let* ((level (save-match-data (funcall outline-level)))
6256 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6257 (diff (abs (- level (length down-head) -1))))
6258 (replace-match down-head nil t)
6259 ;; Fixup tag positioning
6260 (and org-auto-align-tags (org-set-tags nil t))
6261 (if org-adapt-indentation (org-fixup-indentation diff))
6262 (run-hooks 'org-after-demote-entry-hook)))
6264 (defvar org-tab-ind-state nil)
6266 (defun org-cycle-level ()
6267 (let ((org-adapt-indentation nil))
6268 (when (and (looking-at "[ \t]*$")
6269 (looking-back
6270 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6271 (setq this-command 'org-cycle-level)
6272 (if (eq last-command 'org-cycle-level)
6273 (condition-case nil
6274 (progn (org-do-promote)
6275 (if (equal org-tab-ind-state (org-current-level))
6276 (org-do-promote)))
6277 (error
6278 (progn
6279 (save-excursion
6280 (beginning-of-line 1)
6281 (and (looking-at "\\*+")
6282 (replace-match
6283 (make-string org-tab-ind-state ?*))))
6284 (setq this-command 'org-cycle))))
6285 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6286 (org-do-demote))
6287 t)))
6289 (defun org-map-tree (fun)
6290 "Call FUN for every heading underneath the current one."
6291 (org-back-to-heading)
6292 (let ((level (funcall outline-level)))
6293 (save-excursion
6294 (funcall fun)
6295 (while (and (progn
6296 (outline-next-heading)
6297 (> (funcall outline-level) level))
6298 (not (eobp)))
6299 (funcall fun)))))
6301 (defun org-map-region (fun beg end)
6302 "Call FUN for every heading between BEG and END."
6303 (let ((org-ignore-region t))
6304 (save-excursion
6305 (setq end (copy-marker end))
6306 (goto-char beg)
6307 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6308 (< (point) end))
6309 (funcall fun))
6310 (while (and (progn
6311 (outline-next-heading)
6312 (< (point) end))
6313 (not (eobp)))
6314 (funcall fun)))))
6316 (defun org-fixup-indentation (diff)
6317 "Change the indentation in the current entry by DIFF
6318 However, if any line in the current entry has no indentation, or if it
6319 would end up with no indentation after the change, nothing at all is done."
6320 (save-excursion
6321 (let ((end (save-excursion (outline-next-heading)
6322 (point-marker)))
6323 (prohibit (if (> diff 0)
6324 "^\\S-"
6325 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6326 col)
6327 (unless (save-excursion (end-of-line 1)
6328 (re-search-forward prohibit end t))
6329 (while (and (< (point) end)
6330 (re-search-forward "^[ \t]+" end t))
6331 (goto-char (match-end 0))
6332 (setq col (current-column))
6333 (if (< diff 0) (replace-match ""))
6334 (org-indent-to-column (+ diff col))))
6335 (move-marker end nil))))
6337 (defun org-convert-to-odd-levels ()
6338 "Convert an org-mode file with all levels allowed to one with odd levels.
6339 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6340 level 5 etc."
6341 (interactive)
6342 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6343 (let ((outline-regexp org-outline-regexp)
6344 (outline-level 'org-outline-level)
6345 (org-odd-levels-only nil) n)
6346 (save-excursion
6347 (goto-char (point-min))
6348 (while (re-search-forward "^\\*\\*+ " nil t)
6349 (setq n (- (length (match-string 0)) 2))
6350 (while (>= (setq n (1- n)) 0)
6351 (org-demote))
6352 (end-of-line 1))))))
6354 (defun org-convert-to-oddeven-levels ()
6355 "Convert an org-mode file with only odd levels to one with odd and even levels.
6356 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6357 section with an even level, conversion would destroy the structure of the file. An error
6358 is signaled in this case."
6359 (interactive)
6360 (goto-char (point-min))
6361 ;; First check if there are no even levels
6362 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6363 (org-show-context t)
6364 (error "Not all levels are odd in this file. Conversion not possible"))
6365 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6366 (let ((outline-regexp org-outline-regexp)
6367 (outline-level 'org-outline-level)
6368 (org-odd-levels-only nil) n)
6369 (save-excursion
6370 (goto-char (point-min))
6371 (while (re-search-forward "^\\*\\*+ " nil t)
6372 (setq n (/ (1- (length (match-string 0))) 2))
6373 (while (>= (setq n (1- n)) 0)
6374 (org-promote))
6375 (end-of-line 1))))))
6377 (defun org-tr-level (n)
6378 "Make N odd if required."
6379 (if org-odd-levels-only (1+ (/ n 2)) n))
6381 ;;; Vertical tree motion, cutting and pasting of subtrees
6383 (defun org-move-subtree-up (&optional arg)
6384 "Move the current subtree up past ARG headlines of the same level."
6385 (interactive "p")
6386 (org-move-subtree-down (- (prefix-numeric-value arg))))
6388 (defun org-move-subtree-down (&optional arg)
6389 "Move the current subtree down past ARG headlines of the same level."
6390 (interactive "p")
6391 (setq arg (prefix-numeric-value arg))
6392 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6393 'org-get-last-sibling))
6394 (ins-point (make-marker))
6395 (cnt (abs arg))
6396 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6397 ;; Select the tree
6398 (org-back-to-heading)
6399 (setq beg0 (point))
6400 (save-excursion
6401 (setq ne-beg (org-back-over-empty-lines))
6402 (setq beg (point)))
6403 (save-match-data
6404 (save-excursion (outline-end-of-heading)
6405 (setq folded (org-invisible-p)))
6406 (outline-end-of-subtree))
6407 (outline-next-heading)
6408 (setq ne-end (org-back-over-empty-lines))
6409 (setq end (point))
6410 (goto-char beg0)
6411 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6412 ;; include less whitespace
6413 (save-excursion
6414 (goto-char beg)
6415 (forward-line (- ne-beg ne-end))
6416 (setq beg (point))))
6417 ;; Find insertion point, with error handling
6418 (while (> cnt 0)
6419 (or (and (funcall movfunc) (looking-at outline-regexp))
6420 (progn (goto-char beg0)
6421 (error "Cannot move past superior level or buffer limit")))
6422 (setq cnt (1- cnt)))
6423 (if (> arg 0)
6424 ;; Moving forward - still need to move over subtree
6425 (progn (org-end-of-subtree t t)
6426 (save-excursion
6427 (org-back-over-empty-lines)
6428 (or (bolp) (newline)))))
6429 (setq ne-ins (org-back-over-empty-lines))
6430 (move-marker ins-point (point))
6431 (setq txt (buffer-substring beg end))
6432 (org-save-markers-in-region beg end)
6433 (delete-region beg end)
6434 (org-remove-empty-overlays-at beg)
6435 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6436 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6437 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6438 (let ((bbb (point)))
6439 (insert-before-markers txt)
6440 (org-reinstall-markers-in-region bbb)
6441 (move-marker ins-point bbb))
6442 (or (bolp) (insert "\n"))
6443 (setq ins-end (point))
6444 (goto-char ins-point)
6445 (org-skip-whitespace)
6446 (when (and (< arg 0)
6447 (org-first-sibling-p)
6448 (> ne-ins ne-beg))
6449 ;; Move whitespace back to beginning
6450 (save-excursion
6451 (goto-char ins-end)
6452 (let ((kill-whole-line t))
6453 (kill-line (- ne-ins ne-beg)) (point)))
6454 (insert (make-string (- ne-ins ne-beg) ?\n)))
6455 (move-marker ins-point nil)
6456 (if folded
6457 (hide-subtree)
6458 (org-show-entry)
6459 (show-children)
6460 (org-cycle-hide-drawers 'children))
6461 (org-clean-visibility-after-subtree-move)))
6463 (defvar org-subtree-clip ""
6464 "Clipboard for cut and paste of subtrees.
6465 This is actually only a copy of the kill, because we use the normal kill
6466 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6468 (defvar org-subtree-clip-folded nil
6469 "Was the last copied subtree folded?
6470 This is used to fold the tree back after pasting.")
6472 (defun org-cut-subtree (&optional n)
6473 "Cut the current subtree into the clipboard.
6474 With prefix arg N, cut this many sequential subtrees.
6475 This is a short-hand for marking the subtree and then cutting it."
6476 (interactive "p")
6477 (org-copy-subtree n 'cut))
6479 (defun org-copy-subtree (&optional n cut force-store-markers)
6480 "Cut the current subtree into the clipboard.
6481 With prefix arg N, cut this many sequential subtrees.
6482 This is a short-hand for marking the subtree and then copying it.
6483 If CUT is non-nil, actually cut the subtree.
6484 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6485 of some markers in the region, even if CUT is non-nil. This is
6486 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6487 (interactive "p")
6488 (let (beg end folded (beg0 (point)))
6489 (if (interactive-p)
6490 (org-back-to-heading nil) ; take what looks like a subtree
6491 (org-back-to-heading t)) ; take what is really there
6492 (org-back-over-empty-lines)
6493 (setq beg (point))
6494 (skip-chars-forward " \t\r\n")
6495 (save-match-data
6496 (save-excursion (outline-end-of-heading)
6497 (setq folded (org-invisible-p)))
6498 (condition-case nil
6499 (org-forward-same-level (1- n) t)
6500 (error nil))
6501 (org-end-of-subtree t t))
6502 (org-back-over-empty-lines)
6503 (setq end (point))
6504 (goto-char beg0)
6505 (when (> end beg)
6506 (setq org-subtree-clip-folded folded)
6507 (when (or cut force-store-markers)
6508 (org-save-markers-in-region beg end))
6509 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6510 (setq org-subtree-clip (current-kill 0))
6511 (message "%s: Subtree(s) with %d characters"
6512 (if cut "Cut" "Copied")
6513 (length org-subtree-clip)))))
6515 (defun org-paste-subtree (&optional level tree for-yank)
6516 "Paste the clipboard as a subtree, with modification of headline level.
6517 The entire subtree is promoted or demoted in order to match a new headline
6518 level.
6520 If the cursor is at the beginning of a headline, the same level as
6521 that headline is used to paste the tree
6523 If not, the new level is derived from the *visible* headings
6524 before and after the insertion point, and taken to be the inferior headline
6525 level of the two. So if the previous visible heading is level 3 and the
6526 next is level 4 (or vice versa), level 4 will be used for insertion.
6527 This makes sure that the subtree remains an independent subtree and does
6528 not swallow low level entries.
6530 You can also force a different level, either by using a numeric prefix
6531 argument, or by inserting the heading marker by hand. For example, if the
6532 cursor is after \"*****\", then the tree will be shifted to level 5.
6534 If optional TREE is given, use this text instead of the kill ring.
6536 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6537 move back over whitespace before inserting, and move point to the end of
6538 the inserted text when done."
6539 (interactive "P")
6540 (setq tree (or tree (and kill-ring (current-kill 0))))
6541 (unless (org-kill-is-subtree-p tree)
6542 (error "%s"
6543 (substitute-command-keys
6544 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6545 (let* ((visp (not (org-invisible-p)))
6546 (txt tree)
6547 (^re (concat "^\\(" outline-regexp "\\)"))
6548 (re (concat "\\(" outline-regexp "\\)"))
6549 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6551 (old-level (if (string-match ^re txt)
6552 (- (match-end 0) (match-beginning 0) 1)
6553 -1))
6554 (force-level (cond (level (prefix-numeric-value level))
6555 ((and (looking-at "[ \t]*$")
6556 (string-match
6557 ^re_ (buffer-substring
6558 (point-at-bol) (point))))
6559 (- (match-end 1) (match-beginning 1)))
6560 ((and (bolp)
6561 (looking-at org-outline-regexp))
6562 (- (match-end 0) (point) 1))
6563 (t nil)))
6564 (previous-level (save-excursion
6565 (condition-case nil
6566 (progn
6567 (outline-previous-visible-heading 1)
6568 (if (looking-at re)
6569 (- (match-end 0) (match-beginning 0) 1)
6571 (error 1))))
6572 (next-level (save-excursion
6573 (condition-case nil
6574 (progn
6575 (or (looking-at outline-regexp)
6576 (outline-next-visible-heading 1))
6577 (if (looking-at re)
6578 (- (match-end 0) (match-beginning 0) 1)
6580 (error 1))))
6581 (new-level (or force-level (max previous-level next-level)))
6582 (shift (if (or (= old-level -1)
6583 (= new-level -1)
6584 (= old-level new-level))
6586 (- new-level old-level)))
6587 (delta (if (> shift 0) -1 1))
6588 (func (if (> shift 0) 'org-demote 'org-promote))
6589 (org-odd-levels-only nil)
6590 beg end newend)
6591 ;; Remove the forced level indicator
6592 (if force-level
6593 (delete-region (point-at-bol) (point)))
6594 ;; Paste
6595 (beginning-of-line 1)
6596 (unless for-yank (org-back-over-empty-lines))
6597 (setq beg (point))
6598 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6599 (insert-before-markers txt)
6600 (unless (string-match "\n\\'" txt) (insert "\n"))
6601 (setq newend (point))
6602 (org-reinstall-markers-in-region beg)
6603 (setq end (point))
6604 (goto-char beg)
6605 (skip-chars-forward " \t\n\r")
6606 (setq beg (point))
6607 (if (and (org-invisible-p) visp)
6608 (save-excursion (outline-show-heading)))
6609 ;; Shift if necessary
6610 (unless (= shift 0)
6611 (save-restriction
6612 (narrow-to-region beg end)
6613 (while (not (= shift 0))
6614 (org-map-region func (point-min) (point-max))
6615 (setq shift (+ delta shift)))
6616 (goto-char (point-min))
6617 (setq newend (point-max))))
6618 (when (or (interactive-p) for-yank)
6619 (message "Clipboard pasted as level %d subtree" new-level))
6620 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6621 kill-ring
6622 (eq org-subtree-clip (current-kill 0))
6623 org-subtree-clip-folded)
6624 ;; The tree was folded before it was killed/copied
6625 (hide-subtree))
6626 (and for-yank (goto-char newend))))
6628 (defun org-kill-is-subtree-p (&optional txt)
6629 "Check if the current kill is an outline subtree, or a set of trees.
6630 Returns nil if kill does not start with a headline, or if the first
6631 headline level is not the largest headline level in the tree.
6632 So this will actually accept several entries of equal levels as well,
6633 which is OK for `org-paste-subtree'.
6634 If optional TXT is given, check this string instead of the current kill."
6635 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6636 (start-level (and kill
6637 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6638 org-outline-regexp "\\)")
6639 kill)
6640 (- (match-end 2) (match-beginning 2) 1)))
6641 (re (concat "^" org-outline-regexp))
6642 (start (1+ (or (match-beginning 2) -1))))
6643 (if (not start-level)
6644 (progn
6645 nil) ;; does not even start with a heading
6646 (catch 'exit
6647 (while (setq start (string-match re kill (1+ start)))
6648 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6649 (throw 'exit nil)))
6650 t))))
6652 (defvar org-markers-to-move nil
6653 "Markers that should be moved with a cut-and-paste operation.
6654 Those markers are stored together with their positions relative to
6655 the start of the region.")
6657 (defun org-save-markers-in-region (beg end)
6658 "Check markers in region.
6659 If these markers are between BEG and END, record their position relative
6660 to BEG, so that after moving the block of text, we can put the markers back
6661 into place.
6662 This function gets called just before an entry or tree gets cut from the
6663 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6664 called immediately, to move the markers with the entries."
6665 (setq org-markers-to-move nil)
6666 (when (featurep 'org-clock)
6667 (org-clock-save-markers-for-cut-and-paste beg end))
6668 (when (featurep 'org-agenda)
6669 (org-agenda-save-markers-for-cut-and-paste beg end)))
6671 (defun org-check-and-save-marker (marker beg end)
6672 "Check if MARKER is between BEG and END.
6673 If yes, remember the marker and the distance to BEG."
6674 (when (and (marker-buffer marker)
6675 (equal (marker-buffer marker) (current-buffer)))
6676 (if (and (>= marker beg) (< marker end))
6677 (push (cons marker (- marker beg)) org-markers-to-move))))
6679 (defun org-reinstall-markers-in-region (beg)
6680 "Move all remembered markers to their position relative to BEG."
6681 (mapc (lambda (x)
6682 (move-marker (car x) (+ beg (cdr x))))
6683 org-markers-to-move)
6684 (setq org-markers-to-move nil))
6686 (defun org-narrow-to-subtree ()
6687 "Narrow buffer to the current subtree."
6688 (interactive)
6689 (save-excursion
6690 (save-match-data
6691 (narrow-to-region
6692 (progn (org-back-to-heading t) (point))
6693 (progn (org-end-of-subtree t t) (point))))))
6695 (defun org-clone-subtree-with-time-shift (n &optional shift)
6696 "Clone the task (subtree) at point N times.
6697 The clones will be inserted as siblings.
6699 In interactive use, the user will be prompted for the number of clones
6700 to be produced, and for a time SHIFT, which may be a repeater as used
6701 in time stamps, for example `+3d'.
6703 When a valid repeater is given and the entry contains any time stamps,
6704 the clones will become a sequence in time, with time stamps in the
6705 subtree shifted for each clone produced. If SHIFT is nil or the
6706 empty string, time stamps will be left alone.
6708 If the original subtree did contain time stamps with a repeater,
6709 the following will happen:
6710 - the repeater will be removed in each clone
6711 - an additional clone will be produced, with the current, unshifted
6712 date(s) in the entry.
6713 - the original entry will be placed *after* all the clones, with
6714 repeater intact.
6715 - the start days in the repeater in the original entry will be shifted
6716 to past the last clone.
6717 I this way you can spell out a number of instances of a repeating task,
6718 and still retain the repeater to cover future instances of the task."
6719 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6720 (let (beg end template task
6721 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6722 (if (not (and (integerp n) (> n 0)))
6723 (error "Invalid number of replications %s" n))
6724 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6725 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6726 shift)))
6727 (error "Invalid shift specification %s" shift))
6728 (when doshift
6729 (setq shift-n (string-to-number (match-string 1 shift))
6730 shift-what (cdr (assoc (match-string 2 shift)
6731 '(("d" . day) ("w" . week)
6732 ("m" . month) ("y" . year))))))
6733 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6734 (setq nmin 1 nmax n)
6735 (org-back-to-heading t)
6736 (setq beg (point))
6737 (org-end-of-subtree t t)
6738 (setq end (point))
6739 (setq template (buffer-substring beg end))
6740 (when (and doshift
6741 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6742 (delete-region beg end)
6743 (setq end beg)
6744 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6745 (goto-char end)
6746 (loop for n from nmin to nmax do
6747 (if (not doshift)
6748 (setq task template)
6749 (with-temp-buffer
6750 (insert template)
6751 (org-mode)
6752 (goto-char (point-min))
6753 (while (re-search-forward org-ts-regexp-both nil t)
6754 (org-timestamp-change (* n shift-n) shift-what))
6755 (unless (= n n-no-remove)
6756 (goto-char (point-min))
6757 (while (re-search-forward org-ts-regexp nil t)
6758 (save-excursion
6759 (goto-char (match-beginning 0))
6760 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6761 (delete-region (match-beginning 1) (match-end 1))))))
6762 (setq task (buffer-string))))
6763 (insert task))
6764 (goto-char beg)))
6766 ;;; Outline Sorting
6768 (defun org-sort (with-case)
6769 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6770 Optional argument WITH-CASE means sort case-sensitively.
6771 With a double prefix argument, also remove duplicate entries."
6772 (interactive "P")
6773 (if (org-at-table-p)
6774 (org-call-with-arg 'org-table-sort-lines with-case)
6775 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6777 (defun org-sort-remove-invisible (s)
6778 (remove-text-properties 0 (length s) org-rm-props s)
6779 (while (string-match org-bracket-link-regexp s)
6780 (setq s (replace-match (if (match-end 2)
6781 (match-string 3 s)
6782 (match-string 1 s)) t t s)))
6785 (defvar org-priority-regexp) ; defined later in the file
6787 (defvar org-after-sorting-entries-or-items-hook nil
6788 "Hook that is run after a bunch of entries or items have been sorted.
6789 When children are sorted, the cursor is in the parent line when this
6790 hook gets called. When a region or a plain list is sorted, the cursor
6791 will be in the first entry of the sorted region/list.")
6793 (defun org-sort-entries-or-items
6794 (&optional with-case sorting-type getkey-func compare-func property)
6795 "Sort entries on a certain level of an outline tree, or plain list items.
6796 If there is an active region, the entries in the region are sorted.
6797 Else, if the cursor is before the first entry, sort the top-level items.
6798 Else, the children of the entry at point are sorted.
6799 If the cursor is at the first item in a plain list, the list items will be
6800 sorted.
6802 Sorting can be alphabetically, numerically, by date/time as given by
6803 a time stamp, by a property or by priority.
6805 The command prompts for the sorting type unless it has been given to the
6806 function through the SORTING-TYPE argument, which needs to a character,
6807 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6808 precise meaning of each character:
6810 n Numerically, by converting the beginning of the entry/item to a number.
6811 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6812 t By date/time, either the first active time stamp in the entry, or, if
6813 none exist, by the first inactive one.
6814 In items, only the first line will be chekced.
6815 s By the scheduled date/time.
6816 d By deadline date/time.
6817 c By creation time, which is assumed to be the first inactive time stamp
6818 at the beginning of a line.
6819 p By priority according to the cookie.
6820 r By the value of a property.
6822 Capital letters will reverse the sort order.
6824 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6825 called with point at the beginning of the record. It must return either
6826 a string or a number that should serve as the sorting key for that record.
6828 Comparing entries ignores case by default. However, with an optional argument
6829 WITH-CASE, the sorting considers case as well."
6830 (interactive "P")
6831 (let ((case-func (if with-case 'identity 'downcase))
6832 start beg end stars re re2
6833 txt what tmp plain-list-p)
6834 ;; Find beginning and end of region to sort
6835 (cond
6836 ((org-region-active-p)
6837 ;; we will sort the region
6838 (setq end (region-end)
6839 what "region")
6840 (goto-char (region-beginning))
6841 (if (not (org-on-heading-p)) (outline-next-heading))
6842 (setq start (point)))
6843 ((org-at-item-p)
6844 ;; we will sort this plain list
6845 (org-beginning-of-item-list) (setq start (point))
6846 (org-end-of-item-list) (setq end (point))
6847 (goto-char start)
6848 (setq plain-list-p t
6849 what "plain list"))
6850 ((or (org-on-heading-p)
6851 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6852 ;; we will sort the children of the current headline
6853 (org-back-to-heading)
6854 (setq start (point)
6855 end (progn (org-end-of-subtree t t)
6856 (org-back-over-empty-lines)
6857 (point))
6858 what "children")
6859 (goto-char start)
6860 (show-subtree)
6861 (outline-next-heading))
6863 ;; we will sort the top-level entries in this file
6864 (goto-char (point-min))
6865 (or (org-on-heading-p) (outline-next-heading))
6866 (setq start (point) end (point-max) what "top-level")
6867 (goto-char start)
6868 (show-all)))
6870 (setq beg (point))
6871 (if (>= beg end) (error "Nothing to sort"))
6873 (unless plain-list-p
6874 (looking-at "\\(\\*+\\)")
6875 (setq stars (match-string 1)
6876 re (concat "^" (regexp-quote stars) " +")
6877 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6878 txt (buffer-substring beg end))
6879 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6880 (if (and (not (equal stars "*")) (string-match re2 txt))
6881 (error "Region to sort contains a level above the first entry")))
6883 (unless sorting-type
6884 (message
6885 (if plain-list-p
6886 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6887 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6888 [t]ime [s]cheduled [d]eadline [c]reated
6889 A/N/T/S/D/C/P/O/F means reversed:")
6890 what)
6891 (setq sorting-type (read-char-exclusive))
6893 (and (= (downcase sorting-type) ?f)
6894 (setq getkey-func
6895 (org-icompleting-read "Sort using function: "
6896 obarray 'fboundp t nil nil))
6897 (setq getkey-func (intern getkey-func)))
6899 (and (= (downcase sorting-type) ?r)
6900 (setq property
6901 (org-icompleting-read "Property: "
6902 (mapcar 'list (org-buffer-property-keys t))
6903 nil t))))
6905 (message "Sorting entries...")
6907 (save-restriction
6908 (narrow-to-region start end)
6910 (let ((dcst (downcase sorting-type))
6911 (case-fold-search nil)
6912 (now (current-time)))
6913 (sort-subr
6914 (/= dcst sorting-type)
6915 ;; This function moves to the beginning character of the "record" to
6916 ;; be sorted.
6917 (if plain-list-p
6918 (lambda nil
6919 (if (org-at-item-p) t (goto-char (point-max))))
6920 (lambda nil
6921 (if (re-search-forward re nil t)
6922 (goto-char (match-beginning 0))
6923 (goto-char (point-max)))))
6924 ;; This function moves to the last character of the "record" being
6925 ;; sorted.
6926 (if plain-list-p
6927 'org-end-of-item
6928 (lambda nil
6929 (save-match-data
6930 (condition-case nil
6931 (outline-forward-same-level 1)
6932 (error
6933 (goto-char (point-max)))))))
6935 ;; This function returns the value that gets sorted against.
6936 (if plain-list-p
6937 (lambda nil
6938 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6939 (cond
6940 ((= dcst ?n)
6941 (string-to-number (buffer-substring (match-end 0)
6942 (point-at-eol))))
6943 ((= dcst ?a)
6944 (buffer-substring (match-end 0) (point-at-eol)))
6945 ((= dcst ?t)
6946 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6947 (re-search-forward org-ts-regexp-both
6948 (point-at-eol) t))
6949 (org-time-string-to-seconds (match-string 0))
6950 (org-float-time now)))
6951 ((= dcst ?f)
6952 (if getkey-func
6953 (progn
6954 (setq tmp (funcall getkey-func))
6955 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6956 tmp)
6957 (error "Invalid key function `%s'" getkey-func)))
6958 (t (error "Invalid sorting type `%c'" sorting-type)))))
6959 (lambda nil
6960 (cond
6961 ((= dcst ?n)
6962 (if (looking-at org-complex-heading-regexp)
6963 (string-to-number (match-string 4))
6964 nil))
6965 ((= dcst ?a)
6966 (if (looking-at org-complex-heading-regexp)
6967 (funcall case-func (match-string 4))
6968 nil))
6969 ((= dcst ?t)
6970 (let ((end (save-excursion (outline-next-heading) (point))))
6971 (if (or (re-search-forward org-ts-regexp end t)
6972 (re-search-forward org-ts-regexp-both end t))
6973 (org-time-string-to-seconds (match-string 0))
6974 (org-float-time now))))
6975 ((= dcst ?c)
6976 (let ((end (save-excursion (outline-next-heading) (point))))
6977 (if (re-search-forward
6978 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6979 end t)
6980 (org-time-string-to-seconds (match-string 0))
6981 (org-float-time now))))
6982 ((= dcst ?s)
6983 (let ((end (save-excursion (outline-next-heading) (point))))
6984 (if (re-search-forward org-scheduled-time-regexp end t)
6985 (org-time-string-to-seconds (match-string 1))
6986 (org-float-time now))))
6987 ((= dcst ?d)
6988 (let ((end (save-excursion (outline-next-heading) (point))))
6989 (if (re-search-forward org-deadline-time-regexp end t)
6990 (org-time-string-to-seconds (match-string 1))
6991 (org-float-time now))))
6992 ((= dcst ?p)
6993 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6994 (string-to-char (match-string 2))
6995 org-default-priority))
6996 ((= dcst ?r)
6997 (or (org-entry-get nil property) ""))
6998 ((= dcst ?o)
6999 (if (looking-at org-complex-heading-regexp)
7000 (- 9999 (length (member (match-string 2)
7001 org-todo-keywords-1)))))
7002 ((= dcst ?f)
7003 (if getkey-func
7004 (progn
7005 (setq tmp (funcall getkey-func))
7006 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7007 tmp)
7008 (error "Invalid key function `%s'" getkey-func)))
7009 (t (error "Invalid sorting type `%c'" sorting-type)))))
7011 (cond
7012 ((= dcst ?a) 'string<)
7013 ((= dcst ?f) compare-func)
7014 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7015 (t nil)))))
7016 (run-hooks 'org-after-sorting-entries-or-items-hook)
7017 (message "Sorting entries...done")))
7019 (defun org-do-sort (table what &optional with-case sorting-type)
7020 "Sort TABLE of WHAT according to SORTING-TYPE.
7021 The user will be prompted for the SORTING-TYPE if the call to this
7022 function does not specify it. WHAT is only for the prompt, to indicate
7023 what is being sorted. The sorting key will be extracted from
7024 the car of the elements of the table.
7025 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7026 (unless sorting-type
7027 (message
7028 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7029 what)
7030 (setq sorting-type (read-char-exclusive)))
7031 (let ((dcst (downcase sorting-type))
7032 extractfun comparefun)
7033 ;; Define the appropriate functions
7034 (cond
7035 ((= dcst ?n)
7036 (setq extractfun 'string-to-number
7037 comparefun (if (= dcst sorting-type) '< '>)))
7038 ((= dcst ?a)
7039 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7040 (lambda(x) (downcase (org-sort-remove-invisible x))))
7041 comparefun (if (= dcst sorting-type)
7042 'string<
7043 (lambda (a b) (and (not (string< a b))
7044 (not (string= a b)))))))
7045 ((= dcst ?t)
7046 (setq extractfun
7047 (lambda (x)
7048 (if (or (string-match org-ts-regexp x)
7049 (string-match org-ts-regexp-both x))
7050 (org-float-time
7051 (org-time-string-to-time (match-string 0 x)))
7053 comparefun (if (= dcst sorting-type) '< '>)))
7054 (t (error "Invalid sorting type `%c'" sorting-type)))
7056 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7057 table)
7058 (lambda (a b) (funcall comparefun (car a) (car b))))))
7061 ;;; The orgstruct minor mode
7063 ;; Define a minor mode which can be used in other modes in order to
7064 ;; integrate the org-mode structure editing commands.
7066 ;; This is really a hack, because the org-mode structure commands use
7067 ;; keys which normally belong to the major mode. Here is how it
7068 ;; works: The minor mode defines all the keys necessary to operate the
7069 ;; structure commands, but wraps the commands into a function which
7070 ;; tests if the cursor is currently at a headline or a plain list
7071 ;; item. If that is the case, the structure command is used,
7072 ;; temporarily setting many Org-mode variables like regular
7073 ;; expressions for filling etc. However, when any of those keys is
7074 ;; used at a different location, function uses `key-binding' to look
7075 ;; up if the key has an associated command in another currently active
7076 ;; keymap (minor modes, major mode, global), and executes that
7077 ;; command. There might be problems if any of the keys is otherwise
7078 ;; used as a prefix key.
7080 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7081 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7082 ;; addresses this by checking explicitly for both bindings.
7084 (defvar orgstruct-mode-map (make-sparse-keymap)
7085 "Keymap for the minor `orgstruct-mode'.")
7087 (defvar org-local-vars nil
7088 "List of local variables, for use by `orgstruct-mode'")
7090 ;;;###autoload
7091 (define-minor-mode orgstruct-mode
7092 "Toggle the minor more `orgstruct-mode'.
7093 This mode is for using Org-mode structure commands in other modes.
7094 The following key behave as if Org-mode was active, if the cursor
7095 is on a headline, or on a plain list item (both in the definition
7096 of Org-mode).
7098 M-up Move entry/item up
7099 M-down Move entry/item down
7100 M-left Promote
7101 M-right Demote
7102 M-S-up Move entry/item up
7103 M-S-down Move entry/item down
7104 M-S-left Promote subtree
7105 M-S-right Demote subtree
7106 M-q Fill paragraph and items like in Org-mode
7107 C-c ^ Sort entries
7108 C-c - Cycle list bullet
7109 TAB Cycle item visibility
7110 M-RET Insert new heading/item
7111 S-M-RET Insert new TODO heading / Checkbox item
7112 C-c C-c Set tags / toggle checkbox"
7113 nil " OrgStruct" nil
7114 (org-load-modules-maybe)
7115 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7117 ;;;###autoload
7118 (defun turn-on-orgstruct ()
7119 "Unconditionally turn on `orgstruct-mode'."
7120 (orgstruct-mode 1))
7122 (defun orgstruct++-mode (&optional arg)
7123 "Toggle `orgstruct-mode', the enhanced version of it.
7124 In addition to setting orgstruct-mode, this also exports all indentation
7125 and autofilling variables from org-mode into the buffer. It will also
7126 recognize item context in multiline items.
7127 Note that turning off orgstruct-mode will *not* remove the
7128 indentation/paragraph settings. This can only be done by refreshing the
7129 major mode, for example with \\[normal-mode]."
7130 (interactive "P")
7131 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7132 (if (< arg 1)
7133 (orgstruct-mode -1)
7134 (orgstruct-mode 1)
7135 (let (var val)
7136 (mapc
7137 (lambda (x)
7138 (when (string-match
7139 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7140 (symbol-name (car x)))
7141 (setq var (car x) val (nth 1 x))
7142 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7143 org-local-vars)
7144 (org-set-local 'orgstruct-is-++ t))))
7146 (defvar orgstruct-is-++ nil
7147 "Is orgstruct-mode in ++ version in the current-buffer?")
7148 (make-variable-buffer-local 'orgstruct-is-++)
7150 ;;;###autoload
7151 (defun turn-on-orgstruct++ ()
7152 "Unconditionally turn on `orgstruct++-mode'."
7153 (orgstruct++-mode 1))
7155 (defun orgstruct-error ()
7156 "Error when there is no default binding for a structure key."
7157 (interactive)
7158 (error "This key has no function outside structure elements"))
7160 (defun orgstruct-setup ()
7161 "Setup orgstruct keymaps."
7162 (let ((nfunc 0)
7163 (bindings
7164 (list
7165 '([(meta up)] org-metaup)
7166 '([(meta down)] org-metadown)
7167 '([(meta left)] org-metaleft)
7168 '([(meta right)] org-metaright)
7169 '([(meta shift up)] org-shiftmetaup)
7170 '([(meta shift down)] org-shiftmetadown)
7171 '([(meta shift left)] org-shiftmetaleft)
7172 '([(meta shift right)] org-shiftmetaright)
7173 '([?\e (up)] org-metaup)
7174 '([?\e (down)] org-metadown)
7175 '([?\e (left)] org-metaleft)
7176 '([?\e (right)] org-metaright)
7177 '([?\e (shift up)] org-shiftmetaup)
7178 '([?\e (shift down)] org-shiftmetadown)
7179 '([?\e (shift left)] org-shiftmetaleft)
7180 '([?\e (shift right)] org-shiftmetaright)
7181 '([(shift up)] org-shiftup)
7182 '([(shift down)] org-shiftdown)
7183 '([(shift left)] org-shiftleft)
7184 '([(shift right)] org-shiftright)
7185 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7186 '("\M-q" fill-paragraph)
7187 '("\C-c^" org-sort)
7188 '("\C-c-" org-cycle-list-bullet)))
7189 elt key fun cmd)
7190 (while (setq elt (pop bindings))
7191 (setq nfunc (1+ nfunc))
7192 (setq key (org-key (car elt))
7193 fun (nth 1 elt)
7194 cmd (orgstruct-make-binding fun nfunc key))
7195 (org-defkey orgstruct-mode-map key cmd))
7197 ;; Special treatment needed for TAB and RET
7198 (org-defkey orgstruct-mode-map [(tab)]
7199 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7200 (org-defkey orgstruct-mode-map "\C-i"
7201 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7203 (org-defkey orgstruct-mode-map "\M-\C-m"
7204 (orgstruct-make-binding 'org-insert-heading 105
7205 "\M-\C-m" [(meta return)]))
7206 (org-defkey orgstruct-mode-map [(meta return)]
7207 (orgstruct-make-binding 'org-insert-heading 106
7208 [(meta return)] "\M-\C-m"))
7210 (org-defkey orgstruct-mode-map [(shift meta return)]
7211 (orgstruct-make-binding 'org-insert-todo-heading 107
7212 [(meta return)] "\M-\C-m"))
7214 (org-defkey orgstruct-mode-map "\e\C-m"
7215 (orgstruct-make-binding 'org-insert-heading 108
7216 "\e\C-m" [?\e (return)]))
7217 (org-defkey orgstruct-mode-map [?\e (return)]
7218 (orgstruct-make-binding 'org-insert-heading 109
7219 [?\e (return)] "\e\C-m"))
7220 (org-defkey orgstruct-mode-map [?\e (shift return)]
7221 (orgstruct-make-binding 'org-insert-todo-heading 110
7222 [?\e (return)] "\e\C-m"))
7224 (unless org-local-vars
7225 (setq org-local-vars (org-get-local-variables)))
7229 (defun orgstruct-make-binding (fun n &rest keys)
7230 "Create a function for binding in the structure minor mode.
7231 FUN is the command to call inside a table. N is used to create a unique
7232 command name. KEYS are keys that should be checked in for a command
7233 to execute outside of tables."
7234 (eval
7235 (list 'defun
7236 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7237 '(arg)
7238 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7239 "Outside of structure, run the binding of `"
7240 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7241 "'.")
7242 '(interactive "p")
7243 (list 'if
7244 `(org-context-p 'headline 'item
7245 (and orgstruct-is-++
7246 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7247 'item-body))
7248 (list 'org-run-like-in-org-mode (list 'quote fun))
7249 (list 'let '(orgstruct-mode)
7250 (list 'call-interactively
7251 (append '(or)
7252 (mapcar (lambda (k)
7253 (list 'key-binding k))
7254 keys)
7255 '('orgstruct-error))))))))
7257 (defun org-context-p (&rest contexts)
7258 "Check if local context is any of CONTEXTS.
7259 Possible values in the list of contexts are `table', `headline', and `item'."
7260 (let ((pos (point)))
7261 (goto-char (point-at-bol))
7262 (prog1 (or (and (memq 'table contexts)
7263 (looking-at "[ \t]*|"))
7264 (and (memq 'headline contexts)
7265 ;;????????? (looking-at "\\*+"))
7266 (looking-at outline-regexp))
7267 (and (memq 'item contexts)
7268 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7269 (and (memq 'item-body contexts)
7270 (org-in-item-p)))
7271 (goto-char pos))))
7273 (defun org-get-local-variables ()
7274 "Return a list of all local variables in an org-mode buffer."
7275 (let (varlist)
7276 (with-current-buffer (get-buffer-create "*Org tmp*")
7277 (erase-buffer)
7278 (org-mode)
7279 (setq varlist (buffer-local-variables)))
7280 (kill-buffer "*Org tmp*")
7281 (delq nil
7282 (mapcar
7283 (lambda (x)
7284 (setq x
7285 (if (symbolp x)
7286 (list x)
7287 (list (car x) (list 'quote (cdr x)))))
7288 (if (string-match
7289 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7290 (symbol-name (car x)))
7291 x nil))
7292 varlist))))
7294 ;;;###autoload
7295 (defun org-run-like-in-org-mode (cmd)
7296 "Run a command, pretending that the current buffer is in Org-mode.
7297 This will temporarily bind local variables that are typically bound in
7298 Org-mode to the values they have in Org-mode, and then interactively
7299 call CMD."
7300 (org-load-modules-maybe)
7301 (unless org-local-vars
7302 (setq org-local-vars (org-get-local-variables)))
7303 (eval (list 'let org-local-vars
7304 (list 'call-interactively (list 'quote cmd)))))
7306 ;;;; Archiving
7308 (defun org-get-category (&optional pos)
7309 "Get the category applying to position POS."
7310 (get-text-property (or pos (point)) 'org-category))
7312 (defun org-refresh-category-properties ()
7313 "Refresh category text properties in the buffer."
7314 (let ((def-cat (cond
7315 ((null org-category)
7316 (if buffer-file-name
7317 (file-name-sans-extension
7318 (file-name-nondirectory buffer-file-name))
7319 "???"))
7320 ((symbolp org-category) (symbol-name org-category))
7321 (t org-category)))
7322 beg end cat pos optionp)
7323 (org-unmodified
7324 (save-excursion
7325 (save-restriction
7326 (widen)
7327 (goto-char (point-min))
7328 (put-text-property (point) (point-max) 'org-category def-cat)
7329 (while (re-search-forward
7330 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7331 (setq pos (match-end 0)
7332 optionp (equal (char-after (match-beginning 0)) ?#)
7333 cat (org-trim (match-string 2)))
7334 (if optionp
7335 (setq beg (point-at-bol) end (point-max))
7336 (org-back-to-heading t)
7337 (setq beg (point) end (org-end-of-subtree t t)))
7338 (put-text-property beg end 'org-category cat)
7339 (goto-char pos)))))))
7342 ;;;; Link Stuff
7344 ;;; Link abbreviations
7346 (defun org-link-expand-abbrev (link)
7347 "Apply replacements as defined in `org-link-abbrev-alist."
7348 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7349 (let* ((key (match-string 1 link))
7350 (as (or (assoc key org-link-abbrev-alist-local)
7351 (assoc key org-link-abbrev-alist)))
7352 (tag (and (match-end 2) (match-string 3 link)))
7353 rpl)
7354 (if (not as)
7355 link
7356 (setq rpl (cdr as))
7357 (cond
7358 ((symbolp rpl) (funcall rpl tag))
7359 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7360 ((string-match "%h" rpl)
7361 (replace-match (url-hexify-string (or tag "")) t t rpl))
7362 (t (concat rpl tag)))))
7363 link))
7365 ;;; Storing and inserting links
7367 (defvar org-insert-link-history nil
7368 "Minibuffer history for links inserted with `org-insert-link'.")
7370 (defvar org-stored-links nil
7371 "Contains the links stored with `org-store-link'.")
7373 (defvar org-store-link-plist nil
7374 "Plist with info about the most recently link created with `org-store-link'.")
7376 (defvar org-link-protocols nil
7377 "Link protocols added to Org-mode using `org-add-link-type'.")
7379 (defvar org-store-link-functions nil
7380 "List of functions that are called to create and store a link.
7381 Each function will be called in turn until one returns a non-nil
7382 value. Each function should check if it is responsible for creating
7383 this link (for example by looking at the major mode).
7384 If not, it must exit and return nil.
7385 If yes, it should return a non-nil value after a calling
7386 `org-store-link-props' with a list of properties and values.
7387 Special properties are:
7389 :type The link prefix. like \"http\". This must be given.
7390 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7391 This is obligatory as well.
7392 :description Optional default description for the second pair
7393 of brackets in an Org-mode link. The user can still change
7394 this when inserting this link into an Org-mode buffer.
7396 In addition to these, any additional properties can be specified
7397 and then used in remember templates.")
7399 (defun org-add-link-type (type &optional follow export)
7400 "Add TYPE to the list of `org-link-types'.
7401 Re-compute all regular expressions depending on `org-link-types'
7403 FOLLOW and EXPORT are two functions.
7405 FOLLOW should take the link path as the single argument and do whatever
7406 is necessary to follow the link, for example find a file or display
7407 a mail message.
7409 EXPORT should format the link path for export to one of the export formats.
7410 It should be a function accepting three arguments:
7412 path the path of the link, the text after the prefix (like \"http:\")
7413 desc the description of the link, if any, nil if there was no description
7414 format the export format, a symbol like `html' or `latex'.
7416 The function may use the FORMAT information to return different values
7417 depending on the format. The return value will be put literally into
7418 the exported file.
7419 Org-mode has a built-in default for exporting links. If you are happy with
7420 this default, there is no need to define an export function for the link
7421 type. For a simple example of an export function, see `org-bbdb.el'."
7422 (add-to-list 'org-link-types type t)
7423 (org-make-link-regexps)
7424 (if (assoc type org-link-protocols)
7425 (setcdr (assoc type org-link-protocols) (list follow export))
7426 (push (list type follow export) org-link-protocols)))
7428 (defvar org-agenda-buffer-name)
7430 ;;;###autoload
7431 (defun org-store-link (arg)
7432 "\\<org-mode-map>Store an org-link to the current location.
7433 This link is added to `org-stored-links' and can later be inserted
7434 into an org-buffer with \\[org-insert-link].
7436 For some link types, a prefix arg is interpreted:
7437 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7438 For file links, arg negates `org-context-in-file-links'."
7439 (interactive "P")
7440 (org-load-modules-maybe)
7441 (setq org-store-link-plist nil) ; reset
7442 (let ((outline-regexp (org-get-limited-outline-regexp))
7443 link cpltxt desc description search txt custom-id)
7444 (cond
7446 ((run-hook-with-args-until-success 'org-store-link-functions)
7447 (setq link (plist-get org-store-link-plist :link)
7448 desc (or (plist-get org-store-link-plist :description) link)))
7450 ((equal (buffer-name) "*Org Edit Src Example*")
7451 (let (label gc)
7452 (while (or (not label)
7453 (save-excursion
7454 (save-restriction
7455 (widen)
7456 (goto-char (point-min))
7457 (re-search-forward
7458 (regexp-quote (format org-coderef-label-format label))
7459 nil t))))
7460 (when label (message "Label exists already") (sit-for 2))
7461 (setq label (read-string "Code line label: " label)))
7462 (end-of-line 1)
7463 (setq link (format org-coderef-label-format label))
7464 (setq gc (- 79 (length link)))
7465 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7466 (insert link)
7467 (setq link (concat "(" label ")") desc nil)))
7469 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7470 ;; We are in the agenda, link to referenced location
7471 (let ((m (or (get-text-property (point) 'org-hd-marker)
7472 (get-text-property (point) 'org-marker))))
7473 (when m
7474 (org-with-point-at m
7475 (call-interactively 'org-store-link)))))
7477 ((eq major-mode 'calendar-mode)
7478 (let ((cd (calendar-cursor-to-date)))
7479 (setq link
7480 (format-time-string
7481 (car org-time-stamp-formats)
7482 (apply 'encode-time
7483 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7484 nil nil nil))))
7485 (org-store-link-props :type "calendar" :date cd)))
7487 ((eq major-mode 'w3-mode)
7488 (setq cpltxt (if (and (buffer-name)
7489 (not (string-match "Untitled" (buffer-name))))
7490 (buffer-name)
7491 (url-view-url t))
7492 link (org-make-link (url-view-url t)))
7493 (org-store-link-props :type "w3" :url (url-view-url t)))
7495 ((eq major-mode 'w3m-mode)
7496 (setq cpltxt (or w3m-current-title w3m-current-url)
7497 link (org-make-link w3m-current-url))
7498 (org-store-link-props :type "w3m" :url (url-view-url t)))
7500 ((setq search (run-hook-with-args-until-success
7501 'org-create-file-search-functions))
7502 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7503 "::" search))
7504 (setq cpltxt (or description link)))
7506 ((eq major-mode 'image-mode)
7507 (setq cpltxt (concat "file:"
7508 (abbreviate-file-name buffer-file-name))
7509 link (org-make-link cpltxt))
7510 (org-store-link-props :type "image" :file buffer-file-name))
7512 ((eq major-mode 'dired-mode)
7513 ;; link to the file in the current line
7514 (setq cpltxt (concat "file:"
7515 (abbreviate-file-name
7516 (expand-file-name
7517 (dired-get-filename nil t))))
7518 link (org-make-link cpltxt)))
7520 ((and buffer-file-name (org-mode-p))
7521 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7522 (cond
7523 ((org-in-regexp "<<\\(.*?\\)>>")
7524 (setq cpltxt
7525 (concat "file:"
7526 (abbreviate-file-name buffer-file-name)
7527 "::" (match-string 1))
7528 link (org-make-link cpltxt)))
7529 ((and (featurep 'org-id)
7530 (or (eq org-link-to-org-use-id t)
7531 (and (eq org-link-to-org-use-id 'create-if-interactive)
7532 (interactive-p))
7533 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7534 (interactive-p)
7535 (not custom-id))
7536 (and org-link-to-org-use-id
7537 (condition-case nil
7538 (org-entry-get nil "ID")
7539 (error nil)))))
7540 ;; We can make a link using the ID.
7541 (setq link (condition-case nil
7542 (prog1 (org-id-store-link)
7543 (setq desc (plist-get org-store-link-plist
7544 :description)))
7545 (error
7546 ;; probably before first headline, link to file only
7547 (concat "file:"
7548 (abbreviate-file-name buffer-file-name))))))
7550 ;; Just link to current headline
7551 (setq cpltxt (concat "file:"
7552 (abbreviate-file-name buffer-file-name)))
7553 ;; Add a context search string
7554 (when (org-xor org-context-in-file-links arg)
7555 (setq txt (cond
7556 ((org-on-heading-p) nil)
7557 ((org-region-active-p)
7558 (buffer-substring (region-beginning) (region-end)))
7559 (t nil)))
7560 (when (or (null txt) (string-match "\\S-" txt))
7561 (setq cpltxt
7562 (concat cpltxt "::"
7563 (condition-case nil
7564 (org-make-org-heading-search-string txt)
7565 (error "")))
7566 desc (or (nth 4 (ignore-errors
7567 (org-heading-components))) "NONE"))))
7568 (if (string-match "::\\'" cpltxt)
7569 (setq cpltxt (substring cpltxt 0 -2)))
7570 (setq link (org-make-link cpltxt)))))
7572 ((buffer-file-name (buffer-base-buffer))
7573 ;; Just link to this file here.
7574 (setq cpltxt (concat "file:"
7575 (abbreviate-file-name
7576 (buffer-file-name (buffer-base-buffer)))))
7577 ;; Add a context string
7578 (when (org-xor org-context-in-file-links arg)
7579 (setq txt (if (org-region-active-p)
7580 (buffer-substring (region-beginning) (region-end))
7581 (buffer-substring (point-at-bol) (point-at-eol))))
7582 ;; Only use search option if there is some text.
7583 (when (string-match "\\S-" txt)
7584 (setq cpltxt
7585 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7586 desc "NONE")))
7587 (setq link (org-make-link cpltxt)))
7589 ((interactive-p)
7590 (error "Cannot link to a buffer which is not visiting a file"))
7592 (t (setq link nil)))
7594 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7595 (setq link (or link cpltxt)
7596 desc (or desc cpltxt))
7597 (if (equal desc "NONE") (setq desc nil))
7599 (if (and (or (interactive-p) executing-kbd-macro) link)
7600 (progn
7601 (setq org-stored-links
7602 (cons (list link desc) org-stored-links))
7603 (message "Stored: %s" (or desc link))
7604 (when custom-id
7605 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7606 "::#" custom-id))
7607 (setq org-stored-links
7608 (cons (list link desc) org-stored-links))))
7609 (and link (org-make-link-string link desc)))))
7611 (defun org-store-link-props (&rest plist)
7612 "Store link properties, extract names and addresses."
7613 (let (x adr)
7614 (when (setq x (plist-get plist :from))
7615 (setq adr (mail-extract-address-components x))
7616 (setq plist (plist-put plist :fromname (car adr)))
7617 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7618 (when (setq x (plist-get plist :to))
7619 (setq adr (mail-extract-address-components x))
7620 (setq plist (plist-put plist :toname (car adr)))
7621 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7622 (let ((from (plist-get plist :from))
7623 (to (plist-get plist :to)))
7624 (when (and from to org-from-is-user-regexp)
7625 (setq plist
7626 (plist-put plist :fromto
7627 (if (string-match org-from-is-user-regexp from)
7628 (concat "to %t")
7629 (concat "from %f"))))))
7630 (setq org-store-link-plist plist))
7632 (defun org-add-link-props (&rest plist)
7633 "Add these properties to the link property list."
7634 (let (key value)
7635 (while plist
7636 (setq key (pop plist) value (pop plist))
7637 (setq org-store-link-plist
7638 (plist-put org-store-link-plist key value)))))
7640 (defun org-email-link-description (&optional fmt)
7641 "Return the description part of an email link.
7642 This takes information from `org-store-link-plist' and formats it
7643 according to FMT (default from `org-email-link-description-format')."
7644 (setq fmt (or fmt org-email-link-description-format))
7645 (let* ((p org-store-link-plist)
7646 (to (plist-get p :toaddress))
7647 (from (plist-get p :fromaddress))
7648 (table
7649 (list
7650 (cons "%c" (plist-get p :fromto))
7651 (cons "%F" (plist-get p :from))
7652 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7653 (cons "%T" (plist-get p :to))
7654 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7655 (cons "%s" (plist-get p :subject))
7656 (cons "%m" (plist-get p :message-id)))))
7657 (when (string-match "%c" fmt)
7658 ;; Check if the user wrote this message
7659 (if (and org-from-is-user-regexp from to
7660 (save-match-data (string-match org-from-is-user-regexp from)))
7661 (setq fmt (replace-match "to %t" t t fmt))
7662 (setq fmt (replace-match "from %f" t t fmt))))
7663 (org-replace-escapes fmt table)))
7665 (defun org-make-org-heading-search-string (&optional string heading)
7666 "Make search string for STRING or current headline."
7667 (interactive)
7668 (let ((s (or string (org-get-heading))))
7669 (unless (and string (not heading))
7670 ;; We are using a headline, clean up garbage in there.
7671 (if (string-match org-todo-regexp s)
7672 (setq s (replace-match "" t t s)))
7673 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7674 (setq s (replace-match "" t t s)))
7675 (setq s (org-trim s))
7676 (if (string-match (concat "^\\(" org-quote-string "\\|"
7677 org-comment-string "\\)") s)
7678 (setq s (replace-match "" t t s)))
7679 (while (string-match org-ts-regexp s)
7680 (setq s (replace-match "" t t s))))
7681 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7682 (setq s (replace-match " " t t s)))
7683 (or string (setq s (concat "*" s))) ; Add * for headlines
7684 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7686 (defun org-make-link (&rest strings)
7687 "Concatenate STRINGS."
7688 (apply 'concat strings))
7690 (defun org-make-link-string (link &optional description)
7691 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7692 (unless (string-match "\\S-" link)
7693 (error "Empty link"))
7694 (when (stringp description)
7695 ;; Remove brackets from the description, they are fatal.
7696 (while (string-match "\\[" description)
7697 (setq description (replace-match "{" t t description)))
7698 (while (string-match "\\]" description)
7699 (setq description (replace-match "}" t t description))))
7700 (when (equal (org-link-escape link) description)
7701 ;; No description needed, it is identical
7702 (setq description nil))
7703 (when (and (not description)
7704 (not (equal link (org-link-escape link))))
7705 (setq description (org-extract-attributes link)))
7706 (concat "[[" (org-link-escape link) "]"
7707 (if description (concat "[" description "]") "")
7708 "]"))
7710 (defconst org-link-escape-chars
7711 '((?\ . "%20")
7712 (?\[ . "%5B")
7713 (?\] . "%5D")
7714 (?\340 . "%E0") ; `a
7715 (?\342 . "%E2") ; ^a
7716 (?\347 . "%E7") ; ,c
7717 (?\350 . "%E8") ; `e
7718 (?\351 . "%E9") ; 'e
7719 (?\352 . "%EA") ; ^e
7720 (?\356 . "%EE") ; ^i
7721 (?\364 . "%F4") ; ^o
7722 (?\371 . "%F9") ; `u
7723 (?\373 . "%FB") ; ^u
7724 (?\; . "%3B")
7725 (?? . "%3F")
7726 (?= . "%3D")
7727 (?+ . "%2B")
7729 "Association list of escapes for some characters problematic in links.
7730 This is the list that is used for internal purposes.")
7732 (defvar org-url-encoding-use-url-hexify nil)
7734 (defconst org-link-escape-chars-browser
7735 '((?\ . "%20")) ; 32 for the SPC char
7736 "Association list of escapes for some characters problematic in links.
7737 This is the list that is used before handing over to the browser.")
7739 (defun org-link-escape (text &optional table)
7740 "Escape characters in TEXT that are problematic for links."
7741 (if org-url-encoding-use-url-hexify
7742 (url-hexify-string text)
7743 (setq table (or table org-link-escape-chars))
7744 (when text
7745 (let ((re (mapconcat (lambda (x) (regexp-quote
7746 (char-to-string (car x))))
7747 table "\\|")))
7748 (while (string-match re text)
7749 (setq text
7750 (replace-match
7751 (cdr (assoc (string-to-char (match-string 0 text))
7752 table))
7753 t t text)))
7754 text))))
7756 (defun org-link-unescape (text &optional table)
7757 "Reverse the action of `org-link-escape'."
7758 (if org-url-encoding-use-url-hexify
7759 (url-unhex-string text)
7760 (setq table (or table org-link-escape-chars))
7761 (when text
7762 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7763 table "\\|")))
7764 (while (string-match re text)
7765 (setq text
7766 (replace-match
7767 (char-to-string (car (rassoc (match-string 0 text) table)))
7768 t t text)))
7769 text))))
7771 (defun org-xor (a b)
7772 "Exclusive or."
7773 (if a (not b) b))
7775 (defun org-fixup-message-id-for-http (s)
7776 "Replace special characters in a message id, so it can be used in an http query."
7777 (while (string-match "<" s)
7778 (setq s (replace-match "%3C" t t s)))
7779 (while (string-match ">" s)
7780 (setq s (replace-match "%3E" t t s)))
7781 (while (string-match "@" s)
7782 (setq s (replace-match "%40" t t s)))
7785 ;;;###autoload
7786 (defun org-insert-link-global ()
7787 "Insert a link like Org-mode does.
7788 This command can be called in any mode to insert a link in Org-mode syntax."
7789 (interactive)
7790 (org-load-modules-maybe)
7791 (org-run-like-in-org-mode 'org-insert-link))
7793 (defun org-insert-link (&optional complete-file link-location)
7794 "Insert a link. At the prompt, enter the link.
7796 Completion can be used to insert any of the link protocol prefixes like
7797 http or ftp in use.
7799 The history can be used to select a link previously stored with
7800 `org-store-link'. When the empty string is entered (i.e. if you just
7801 press RET at the prompt), the link defaults to the most recently
7802 stored link. As SPC triggers completion in the minibuffer, you need to
7803 use M-SPC or C-q SPC to force the insertion of a space character.
7805 You will also be prompted for a description, and if one is given, it will
7806 be displayed in the buffer instead of the link.
7808 If there is already a link at point, this command will allow you to edit link
7809 and description parts.
7811 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7812 be selected using completion. The path to the file will be relative to the
7813 current directory if the file is in the current directory or a subdirectory.
7814 Otherwise, the link will be the absolute path as completed in the minibuffer
7815 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7816 option `org-link-file-path-type'.
7818 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7819 the current directory or below.
7821 With three \\[universal-argument] prefixes, negate the meaning of
7822 `org-keep-stored-link-after-insertion'.
7824 If `org-make-link-description-function' is non-nil, this function will be
7825 called with the link target, and the result will be the default
7826 link description.
7828 If the LINK-LOCATION parameter is non-nil, this value will be
7829 used as the link location instead of reading one interactively."
7830 (interactive "P")
7831 (let* ((wcf (current-window-configuration))
7832 (region (if (org-region-active-p)
7833 (buffer-substring (region-beginning) (region-end))))
7834 (remove (and region (list (region-beginning) (region-end))))
7835 (desc region)
7836 tmphist ; byte-compile incorrectly complains about this
7837 (link link-location)
7838 entry file all-prefixes)
7839 (cond
7840 (link-location) ; specified by arg, just use it.
7841 ((org-in-regexp org-bracket-link-regexp 1)
7842 ;; We do have a link at point, and we are going to edit it.
7843 (setq remove (list (match-beginning 0) (match-end 0)))
7844 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7845 (setq link (read-string "Link: "
7846 (org-link-unescape
7847 (org-match-string-no-properties 1)))))
7848 ((or (org-in-regexp org-angle-link-re)
7849 (org-in-regexp org-plain-link-re))
7850 ;; Convert to bracket link
7851 (setq remove (list (match-beginning 0) (match-end 0))
7852 link (read-string "Link: "
7853 (org-remove-angle-brackets (match-string 0)))))
7854 ((member complete-file '((4) (16)))
7855 ;; Completing read for file names.
7856 (setq link (org-file-complete-link complete-file)))
7858 ;; Read link, with completion for stored links.
7859 (with-output-to-temp-buffer "*Org Links*"
7860 (princ "Insert a link.
7861 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7862 (when org-stored-links
7863 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7864 (princ (mapconcat
7865 (lambda (x)
7866 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7867 (reverse org-stored-links) "\n"))))
7868 (let ((cw (selected-window)))
7869 (select-window (get-buffer-window "*Org Links*"))
7870 (setq truncate-lines t)
7871 (unless (pos-visible-in-window-p (point-max))
7872 (org-fit-window-to-buffer))
7873 (and (window-live-p cw) (select-window cw)))
7874 ;; Fake a link history, containing the stored links.
7875 (setq tmphist (append (mapcar 'car org-stored-links)
7876 org-insert-link-history))
7877 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7878 (mapcar 'car org-link-abbrev-alist)
7879 org-link-types))
7880 (unwind-protect
7881 (progn
7882 (setq link
7883 (let ((org-completion-use-ido nil)
7884 (org-completion-use-iswitchb nil))
7885 (org-completing-read
7886 "Link: "
7887 (append
7888 (mapcar (lambda (x) (list (concat x ":")))
7889 all-prefixes)
7890 (mapcar 'car org-stored-links))
7891 nil nil nil
7892 'tmphist
7893 (car (car org-stored-links)))))
7894 (if (or (member link all-prefixes)
7895 (and (equal ":" (substring link -1))
7896 (member (substring link 0 -1) all-prefixes)
7897 (setq link (substring link 0 -1))))
7898 (setq link (org-link-try-special-completion link))))
7899 (set-window-configuration wcf)
7900 (kill-buffer "*Org Links*"))
7901 (setq entry (assoc link org-stored-links))
7902 (or entry (push link org-insert-link-history))
7903 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7904 (not org-keep-stored-link-after-insertion))
7905 (setq org-stored-links (delq (assoc link org-stored-links)
7906 org-stored-links)))
7907 (setq desc (or desc (nth 1 entry)))))
7909 (if (string-match org-plain-link-re link)
7910 ;; URL-like link, normalize the use of angular brackets.
7911 (setq link (org-make-link (org-remove-angle-brackets link))))
7913 ;; Check if we are linking to the current file with a search option
7914 ;; If yes, simplify the link by using only the search option.
7915 (when (and buffer-file-name
7916 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7917 (let* ((path (match-string 1 link))
7918 (case-fold-search nil)
7919 (search (match-string 2 link)))
7920 (save-match-data
7921 (if (equal (file-truename buffer-file-name) (file-truename path))
7922 ;; We are linking to this same file, with a search option
7923 (setq link search)))))
7925 ;; Check if we can/should use a relative path. If yes, simplify the link
7926 (when (string-match "^file:\\(.*\\)" link)
7927 (let* ((path (match-string 1 link))
7928 (origpath path)
7929 (case-fold-search nil))
7930 (cond
7931 ((or (eq org-link-file-path-type 'absolute)
7932 (equal complete-file '(16)))
7933 (setq path (abbreviate-file-name (expand-file-name path))))
7934 ((eq org-link-file-path-type 'noabbrev)
7935 (setq path (expand-file-name path)))
7936 ((eq org-link-file-path-type 'relative)
7937 (setq path (file-relative-name path)))
7939 (save-match-data
7940 (if (string-match (concat "^" (regexp-quote
7941 (file-name-as-directory
7942 (expand-file-name "."))))
7943 (expand-file-name path))
7944 ;; We are linking a file with relative path name.
7945 (setq path (substring (expand-file-name path)
7946 (match-end 0)))
7947 (setq path (abbreviate-file-name (expand-file-name path)))))))
7948 (setq link (concat "file:" path))
7949 (if (equal desc origpath)
7950 (setq desc path))))
7952 (if org-make-link-description-function
7953 (setq desc (funcall org-make-link-description-function link desc)))
7955 (setq desc (read-string "Description: " desc))
7956 (unless (string-match "\\S-" desc) (setq desc nil))
7957 (if remove (apply 'delete-region remove))
7958 (insert (org-make-link-string link desc))))
7960 (defun org-link-try-special-completion (type)
7961 "If there is completion support for link type TYPE, offer it."
7962 (let ((fun (intern (concat "org-" type "-complete-link"))))
7963 (if (functionp fun)
7964 (funcall fun)
7965 (read-string "Link (no completion support): " (concat type ":")))))
7967 (defun org-file-complete-link (&optional arg)
7968 "Create a file link using completion."
7969 (let (file link)
7970 (setq file (read-file-name "File: "))
7971 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7972 (pwd1 (file-name-as-directory (abbreviate-file-name
7973 (expand-file-name ".")))))
7974 (cond
7975 ((equal arg '(16))
7976 (setq link (org-make-link
7977 "file:"
7978 (abbreviate-file-name (expand-file-name file)))))
7979 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7980 (setq link (org-make-link "file:" (match-string 1 file))))
7981 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7982 (expand-file-name file))
7983 (setq link (org-make-link
7984 "file:" (match-string 1 (expand-file-name file)))))
7985 (t (setq link (org-make-link "file:" file)))))
7986 link))
7988 (defun org-completing-read (&rest args)
7989 "Completing-read with SPACE being a normal character."
7990 (let ((minibuffer-local-completion-map
7991 (copy-keymap minibuffer-local-completion-map)))
7992 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7993 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7994 (apply 'org-icompleting-read args)))
7996 (defun org-completing-read-no-i (&rest args)
7997 (let (org-completion-use-ido org-completion-use-iswitchb)
7998 (apply 'org-completing-read args)))
8000 (defun org-iswitchb-completing-read (prompt choices &rest args)
8001 "Use iswitch as a completing-read replacement to choose from choices.
8002 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8003 from."
8004 (let* ((iswitchb-use-virtual-buffers nil)
8005 (iswitchb-make-buflist-hook
8006 (lambda ()
8007 (setq iswitchb-temp-buflist choices))))
8008 (iswitchb-read-buffer prompt)))
8010 (defun org-icompleting-read (&rest args)
8011 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8012 (org-without-partial-completion
8013 (if (and org-completion-use-ido
8014 (fboundp 'ido-completing-read)
8015 (boundp 'ido-mode) ido-mode
8016 (listp (second args)))
8017 (let ((ido-enter-matching-directory nil))
8018 (apply 'ido-completing-read (concat (car args))
8019 (if (consp (car (nth 1 args)))
8020 (mapcar (lambda (x) (car x)) (nth 1 args))
8021 (nth 1 args))
8022 (cddr args)))
8023 (if (and org-completion-use-iswitchb
8024 (boundp 'iswitchb-mode) iswitchb-mode
8025 (listp (second args)))
8026 (apply 'org-iswitchb-completing-read (concat (car args))
8027 (if (consp (car (nth 1 args)))
8028 (mapcar (lambda (x) (car x)) (nth 1 args))
8029 (nth 1 args))
8030 (cddr args))
8031 (apply 'completing-read args)))))
8033 (defun org-extract-attributes (s)
8034 "Extract the attributes cookie from a string and set as text property."
8035 (let (a attr (start 0) key value)
8036 (save-match-data
8037 (when (string-match "{{\\([^}]+\\)}}$" s)
8038 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8039 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8040 (setq key (match-string 1 a) value (match-string 2 a)
8041 start (match-end 0)
8042 attr (plist-put attr (intern key) value))))
8043 (org-add-props s nil 'org-attr attr))
8046 (defun org-extract-attributes-from-string (tag)
8047 (let (key value attr)
8048 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8049 (setq key (match-string 1 tag) value (match-string 2 tag)
8050 tag (replace-match "" t t tag)
8051 attr (plist-put attr (intern key) value)))
8052 (cons tag attr)))
8054 (defun org-attributes-to-string (plist)
8055 "Format a property list into an HTML attribute list."
8056 (let ((s "") key value)
8057 (while plist
8058 (setq key (pop plist) value (pop plist))
8059 (and value
8060 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8063 ;;; Opening/following a link
8065 (defvar org-link-search-failed nil)
8067 (defun org-next-link ()
8068 "Move forward to the next link.
8069 If the link is in hidden text, expose it."
8070 (interactive)
8071 (when (and org-link-search-failed (eq this-command last-command))
8072 (goto-char (point-min))
8073 (message "Link search wrapped back to beginning of buffer"))
8074 (setq org-link-search-failed nil)
8075 (let* ((pos (point))
8076 (ct (org-context))
8077 (a (assoc :link ct)))
8078 (if a (goto-char (nth 2 a)))
8079 (if (re-search-forward org-any-link-re nil t)
8080 (progn
8081 (goto-char (match-beginning 0))
8082 (if (org-invisible-p) (org-show-context)))
8083 (goto-char pos)
8084 (setq org-link-search-failed t)
8085 (error "No further link found"))))
8087 (defun org-previous-link ()
8088 "Move backward to the previous link.
8089 If the link is in hidden text, expose it."
8090 (interactive)
8091 (when (and org-link-search-failed (eq this-command last-command))
8092 (goto-char (point-max))
8093 (message "Link search wrapped back to end of buffer"))
8094 (setq org-link-search-failed nil)
8095 (let* ((pos (point))
8096 (ct (org-context))
8097 (a (assoc :link ct)))
8098 (if a (goto-char (nth 1 a)))
8099 (if (re-search-backward org-any-link-re nil t)
8100 (progn
8101 (goto-char (match-beginning 0))
8102 (if (org-invisible-p) (org-show-context)))
8103 (goto-char pos)
8104 (setq org-link-search-failed t)
8105 (error "No further link found"))))
8107 (defun org-translate-link (s)
8108 "Translate a link string if a translation function has been defined."
8109 (if (and org-link-translation-function
8110 (fboundp org-link-translation-function)
8111 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8112 (progn
8113 (setq s (funcall org-link-translation-function
8114 (match-string 1) (match-string 2)))
8115 (concat (car s) ":" (cdr s)))
8118 (defun org-translate-link-from-planner (type path)
8119 "Translate a link from Emacs Planner syntax so that Org can follow it.
8120 This is still an experimental function, your mileage may vary."
8121 (cond
8122 ((member type '("http" "https" "news" "ftp"))
8123 ;; standard Internet links are the same.
8124 nil)
8125 ((and (equal type "irc") (string-match "^//" path))
8126 ;; Planner has two / at the beginning of an irc link, we have 1.
8127 ;; We should have zero, actually....
8128 (setq path (substring path 1)))
8129 ((and (equal type "lisp") (string-match "^/" path))
8130 ;; Planner has a slash, we do not.
8131 (setq type "elisp" path (substring path 1)))
8132 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8133 ;; A typical message link. Planner has the id after the fina slash,
8134 ;; we separate it with a hash mark
8135 (setq path (concat (match-string 1 path) "#"
8136 (org-remove-angle-brackets (match-string 2 path)))))
8138 (cons type path))
8140 (defun org-find-file-at-mouse (ev)
8141 "Open file link or URL at mouse."
8142 (interactive "e")
8143 (mouse-set-point ev)
8144 (org-open-at-point 'in-emacs))
8146 (defun org-open-at-mouse (ev)
8147 "Open file link or URL at mouse."
8148 (interactive "e")
8149 (mouse-set-point ev)
8150 (if (eq major-mode 'org-agenda-mode)
8151 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8152 (org-open-at-point))
8154 (defvar org-window-config-before-follow-link nil
8155 "The window configuration before following a link.
8156 This is saved in case the need arises to restore it.")
8158 (defvar org-open-link-marker (make-marker)
8159 "Marker pointing to the location where `org-open-at-point; was called.")
8161 ;;;###autoload
8162 (defun org-open-at-point-global ()
8163 "Follow a link like Org-mode does.
8164 This command can be called in any mode to follow a link that has
8165 Org-mode syntax."
8166 (interactive)
8167 (org-run-like-in-org-mode 'org-open-at-point))
8169 ;;;###autoload
8170 (defun org-open-link-from-string (s &optional arg reference-buffer)
8171 "Open a link in the string S, as if it was in Org-mode."
8172 (interactive "sLink: \nP")
8173 (let ((reference-buffer (or reference-buffer (current-buffer))))
8174 (with-temp-buffer
8175 (let ((org-inhibit-startup t))
8176 (org-mode)
8177 (insert s)
8178 (goto-char (point-min))
8179 (org-open-at-point arg reference-buffer)))))
8181 (defun org-open-at-point (&optional in-emacs reference-buffer)
8182 "Open link at or after point.
8183 If there is no link at point, this function will search forward up to
8184 the end of the current line.
8185 Normally, files will be opened by an appropriate application. If the
8186 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8187 With a double prefix argument, try to open outside of Emacs, in the
8188 application the system uses for this file type."
8189 (interactive "P")
8190 (org-load-modules-maybe)
8191 (move-marker org-open-link-marker (point))
8192 (setq org-window-config-before-follow-link (current-window-configuration))
8193 (org-remove-occur-highlights nil nil t)
8194 (cond
8195 ((and (org-on-heading-p)
8196 (not (org-in-regexp
8197 (concat org-plain-link-re "\\|"
8198 org-bracket-link-regexp "\\|"
8199 org-angle-link-re "\\|"
8200 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8201 (or (org-offer-links-in-entry in-emacs)
8202 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8203 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8204 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8205 (org-footnote-action))
8207 (let (type path link line search (pos (point)))
8208 (catch 'match
8209 (save-excursion
8210 (skip-chars-forward "^]\n\r")
8211 (when (org-in-regexp org-bracket-link-regexp)
8212 (setq link (org-extract-attributes
8213 (org-link-unescape (org-match-string-no-properties 1))))
8214 (while (string-match " *\n *" link)
8215 (setq link (replace-match " " t t link)))
8216 (setq link (org-link-expand-abbrev link))
8217 (cond
8218 ((or (file-name-absolute-p link)
8219 (string-match "^\\.\\.?/" link))
8220 (setq type "file" path link))
8221 ((string-match org-link-re-with-space3 link)
8222 (setq type (match-string 1 link) path (match-string 2 link)))
8223 (t (setq type "thisfile" path link)))
8224 (throw 'match t)))
8226 (when (get-text-property (point) 'org-linked-text)
8227 (setq type "thisfile"
8228 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8229 (1+ (point)) (point))
8230 path (buffer-substring
8231 (previous-single-property-change pos 'org-linked-text)
8232 (next-single-property-change pos 'org-linked-text)))
8233 (throw 'match t))
8235 (save-excursion
8236 (when (or (org-in-regexp org-angle-link-re)
8237 (org-in-regexp org-plain-link-re))
8238 (setq type (match-string 1) path (match-string 2))
8239 (throw 'match t)))
8240 (save-excursion
8241 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8242 (setq type "tags"
8243 path (match-string 1))
8244 (while (string-match ":" path)
8245 (setq path (replace-match "+" t t path)))
8246 (throw 'match t)))
8247 (when (org-in-regexp "<\\([^><\n]+\\)>")
8248 (setq type "tree-match"
8249 path (match-string 1))
8250 (throw 'match t)))
8251 (unless path
8252 (error "No link found"))
8254 ;; switch back to reference buffer
8255 ;; needed when if called in a temporary buffer through
8256 ;; org-open-link-from-string
8257 (with-current-buffer (or reference-buffer (current-buffer))
8259 ;; Remove any trailing spaces in path
8260 (if (string-match " +\\'" path)
8261 (setq path (replace-match "" t t path)))
8262 (if (and org-link-translation-function
8263 (fboundp org-link-translation-function))
8264 ;; Check if we need to translate the link
8265 (let ((tmp (funcall org-link-translation-function type path)))
8266 (setq type (car tmp) path (cdr tmp))))
8268 (cond
8270 ((assoc type org-link-protocols)
8271 (funcall (nth 1 (assoc type org-link-protocols)) path))
8273 ((equal type "mailto")
8274 (let ((cmd (car org-link-mailto-program))
8275 (args (cdr org-link-mailto-program)) args1
8276 (address path) (subject "") a)
8277 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8278 (setq address (match-string 1 path)
8279 subject (org-link-escape (match-string 2 path))))
8280 (while args
8281 (cond
8282 ((not (stringp (car args))) (push (pop args) args1))
8283 (t (setq a (pop args))
8284 (if (string-match "%a" a)
8285 (setq a (replace-match address t t a)))
8286 (if (string-match "%s" a)
8287 (setq a (replace-match subject t t a)))
8288 (push a args1))))
8289 (apply cmd (nreverse args1))))
8291 ((member type '("http" "https" "ftp" "news"))
8292 (browse-url (concat type ":" (org-link-escape
8293 path org-link-escape-chars-browser))))
8295 ((member type '("message"))
8296 (browse-url (concat type ":" path)))
8298 ((string= type "tags")
8299 (org-tags-view in-emacs path))
8300 ((string= type "thisfile")
8301 (if in-emacs
8302 (switch-to-buffer-other-window
8303 (org-get-buffer-for-internal-link (current-buffer)))
8304 (org-mark-ring-push))
8305 (let ((cmd `(org-link-search
8306 ,path
8307 ,(cond ((equal in-emacs '(4)) 'occur)
8308 ((equal in-emacs '(16)) 'org-occur)
8309 (t nil))
8310 ,pos)))
8311 (condition-case nil (eval cmd)
8312 (error (progn (widen) (eval cmd))))))
8314 ((string= type "tree-match")
8315 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8317 ((string= type "file")
8318 (if (string-match "::\\([0-9]+\\)\\'" path)
8319 (setq line (string-to-number (match-string 1 path))
8320 path (substring path 0 (match-beginning 0)))
8321 (if (string-match "::\\(.+\\)\\'" path)
8322 (setq search (match-string 1 path)
8323 path (substring path 0 (match-beginning 0)))))
8324 (if (string-match "[*?{]" (file-name-nondirectory path))
8325 (dired path)
8326 (org-open-file path in-emacs line search)))
8328 ((string= type "news")
8329 (require 'org-gnus)
8330 (org-gnus-follow-link path))
8332 ((string= type "shell")
8333 (let ((cmd path))
8334 (if (or (not org-confirm-shell-link-function)
8335 (funcall org-confirm-shell-link-function
8336 (format "Execute \"%s\" in shell? "
8337 (org-add-props cmd nil
8338 'face 'org-warning))))
8339 (progn
8340 (message "Executing %s" cmd)
8341 (shell-command cmd))
8342 (error "Abort"))))
8344 ((string= type "elisp")
8345 (let ((cmd path))
8346 (if (or (not org-confirm-elisp-link-function)
8347 (funcall org-confirm-elisp-link-function
8348 (format "Execute \"%s\" as elisp? "
8349 (org-add-props cmd nil
8350 'face 'org-warning))))
8351 (message "%s => %s" cmd
8352 (if (equal (string-to-char cmd) ?\()
8353 (eval (read cmd))
8354 (call-interactively (read cmd))))
8355 (error "Abort"))))
8358 (browse-url-at-point)))))))
8359 (move-marker org-open-link-marker nil)
8360 (run-hook-with-args 'org-follow-link-hook))
8362 (defun org-offer-links-in-entry (&optional nth zero)
8363 "Offer links in the curren entry and follow the selected link.
8364 If there is only one link, follow it immediately as well.
8365 If NTH is an integer, immediately pick the NTH link found.
8366 If ZERO is a string, check also this string for a link, and if
8367 there is one, offer it as link number zero."
8368 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8369 "\\(" org-angle-link-re "\\)\\|"
8370 "\\(" org-plain-link-re "\\)"))
8371 (cnt ?0)
8372 (in-emacs (if (integerp nth) nil nth))
8373 have-zero end links link c)
8374 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8375 (push (match-string 0 zero) links)
8376 (setq cnt (1- cnt) have-zero t))
8377 (save-excursion
8378 (org-back-to-heading t)
8379 (setq end (save-excursion (outline-next-heading) (point)))
8380 (while (re-search-forward re end t)
8381 (push (match-string 0) links))
8382 (setq links (org-uniquify (reverse links))))
8384 (cond
8385 ((null links)
8386 (message "No links"))
8387 ((equal (length links) 1)
8388 (setq link (car links)))
8389 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8390 (setq link (nth (if have-zero nth (1- nth)) links)))
8391 (t ; we have to select a link
8392 (save-excursion
8393 (save-window-excursion
8394 (delete-other-windows)
8395 (with-output-to-temp-buffer "*Select Link*"
8396 (mapc (lambda (l)
8397 (if (not (string-match org-bracket-link-regexp l))
8398 (princ (format "[%c] %s\n" (incf cnt)
8399 (org-remove-angle-brackets l)))
8400 (if (match-end 3)
8401 (princ (format "[%c] %s (%s)\n" (incf cnt)
8402 (match-string 3 l) (match-string 1 l)))
8403 (princ (format "[%c] %s\n" (incf cnt)
8404 (match-string 1 l))))))
8405 links))
8406 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8407 (message "Select link to open:")
8408 (setq c (read-char-exclusive))
8409 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8410 (when (equal c ?q) (error "Abort"))
8411 (setq nth (- c ?0))
8412 (if have-zero (setq nth (1+ nth)))
8413 (unless (and (integerp nth) (>= (length links) nth))
8414 (error "Invalid link selection"))
8415 (setq link (nth (1- nth) links))))
8416 (if link
8417 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8418 nil)))
8420 ;;;; Time estimates
8422 (defun org-get-effort (&optional pom)
8423 "Get the effort estimate for the current entry."
8424 (org-entry-get pom org-effort-property))
8426 ;;; File search
8428 (defvar org-create-file-search-functions nil
8429 "List of functions to construct the right search string for a file link.
8430 These functions are called in turn with point at the location to
8431 which the link should point.
8433 A function in the hook should first test if it would like to
8434 handle this file type, for example by checking the major-mode or
8435 the file extension. If it decides not to handle this file, it
8436 should just return nil to give other functions a chance. If it
8437 does handle the file, it must return the search string to be used
8438 when following the link. The search string will be part of the
8439 file link, given after a double colon, and `org-open-at-point'
8440 will automatically search for it. If special measures must be
8441 taken to make the search successful, another function should be
8442 added to the companion hook `org-execute-file-search-functions',
8443 which see.
8445 A function in this hook may also use `setq' to set the variable
8446 `description' to provide a suggestion for the descriptive text to
8447 be used for this link when it gets inserted into an Org-mode
8448 buffer with \\[org-insert-link].")
8450 (defvar org-execute-file-search-functions nil
8451 "List of functions to execute a file search triggered by a link.
8453 Functions added to this hook must accept a single argument, the
8454 search string that was part of the file link, the part after the
8455 double colon. The function must first check if it would like to
8456 handle this search, for example by checking the major-mode or the
8457 file extension. If it decides not to handle this search, it
8458 should just return nil to give other functions a chance. If it
8459 does handle the search, it must return a non-nil value to keep
8460 other functions from trying.
8462 Each function can access the current prefix argument through the
8463 variable `current-prefix-argument'. Note that a single prefix is
8464 used to force opening a link in Emacs, so it may be good to only
8465 use a numeric or double prefix to guide the search function.
8467 In case this is needed, a function in this hook can also restore
8468 the window configuration before `org-open-at-point' was called using:
8470 (set-window-configuration org-window-config-before-follow-link)")
8472 (defun org-link-search (s &optional type avoid-pos)
8473 "Search for a link search option.
8474 If S is surrounded by forward slashes, it is interpreted as a
8475 regular expression. In org-mode files, this will create an `org-occur'
8476 sparse tree. In ordinary files, `occur' will be used to list matches.
8477 If the current buffer is in `dired-mode', grep will be used to search
8478 in all files. If AVOID-POS is given, ignore matches near that position."
8479 (let ((case-fold-search t)
8480 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8481 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8482 (append '(("") (" ") ("\t") ("\n"))
8483 org-emphasis-alist)
8484 "\\|") "\\)"))
8485 (pos (point))
8486 (pre nil) (post nil)
8487 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8488 (cond
8489 ;; First check if there are any special
8490 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8491 ;; Now try the builtin stuff
8492 ((and (equal (string-to-char s0) ?#)
8493 (> (length s0) 1)
8494 (save-excursion
8495 (goto-char (point-min))
8496 (and
8497 (re-search-forward
8498 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8499 (setq type 'dedicated
8500 pos (match-beginning 0))))
8501 ;; There is an exact target for this
8502 (goto-char pos)
8503 (org-back-to-heading t)))
8504 ((save-excursion
8505 (goto-char (point-min))
8506 (and
8507 (re-search-forward
8508 (concat "<<" (regexp-quote s0) ">>") nil t)
8509 (setq type 'dedicated
8510 pos (match-beginning 0))))
8511 ;; There is an exact target for this
8512 (goto-char pos))
8513 ((and (string-match "^(\\(.*\\))$" s0)
8514 (save-excursion
8515 (goto-char (point-min))
8516 (and
8517 (re-search-forward
8518 (concat "[^[]" (regexp-quote
8519 (format org-coderef-label-format
8520 (match-string 1 s0))))
8521 nil t)
8522 (setq type 'dedicated
8523 pos (1+ (match-beginning 0))))))
8524 ;; There is a coderef target for this
8525 (goto-char pos))
8526 ((string-match "^/\\(.*\\)/$" s)
8527 ;; A regular expression
8528 (cond
8529 ((org-mode-p)
8530 (org-occur (match-string 1 s)))
8531 ;;((eq major-mode 'dired-mode)
8532 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8533 (t (org-do-occur (match-string 1 s)))))
8535 ;; A normal search strings
8536 (when (equal (string-to-char s) ?*)
8537 ;; Anchor on headlines, post may include tags.
8538 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8539 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8540 s (substring s 1)))
8541 (remove-text-properties
8542 0 (length s)
8543 '(face nil mouse-face nil keymap nil fontified nil) s)
8544 ;; Make a series of regular expressions to find a match
8545 (setq words (org-split-string s "[ \n\r\t]+")
8547 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8548 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8549 "\\)" markers)
8550 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8551 re2a (concat "[ \t\r\n]" re2a_)
8552 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8553 re4 (concat "[^a-zA-Z_]" re4_)
8555 re1 (concat pre re2 post)
8556 re3 (concat pre (if pre re4_ re4) post)
8557 re5 (concat pre ".*" re4)
8558 re2 (concat pre re2)
8559 re2a (concat pre (if pre re2a_ re2a))
8560 re4 (concat pre (if pre re4_ re4))
8561 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8562 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8563 re5 "\\)"
8565 (cond
8566 ((eq type 'org-occur) (org-occur reall))
8567 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8568 (t (goto-char (point-min))
8569 (setq type 'fuzzy)
8570 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8571 (org-search-not-self 1 re1 nil t)
8572 (org-search-not-self 1 re2 nil t)
8573 (org-search-not-self 1 re2a nil t)
8574 (org-search-not-self 1 re3 nil t)
8575 (org-search-not-self 1 re4 nil t)
8576 (org-search-not-self 1 re5 nil t)
8578 (goto-char (match-beginning 1))
8579 (goto-char pos)
8580 (error "No match")))))
8582 ;; Normal string-search
8583 (goto-char (point-min))
8584 (if (search-forward s nil t)
8585 (goto-char (match-beginning 0))
8586 (error "No match"))))
8587 (and (org-mode-p) (org-show-context 'link-search))
8588 type))
8590 (defun org-search-not-self (group &rest args)
8591 "Execute `re-search-forward', but only accept matches that do not
8592 enclose the position of `org-open-link-marker'."
8593 (let ((m org-open-link-marker))
8594 (catch 'exit
8595 (while (apply 're-search-forward args)
8596 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8597 (goto-char (match-end group))
8598 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8599 (> (match-beginning 0) (marker-position m))
8600 (< (match-end 0) (marker-position m)))
8601 (save-match-data
8602 (or (not (org-in-regexp
8603 org-bracket-link-analytic-regexp 1))
8604 (not (match-end 4)) ; no description
8605 (and (<= (match-beginning 4) (point))
8606 (>= (match-end 4) (point))))))
8607 (throw 'exit (point))))))))
8609 (defun org-get-buffer-for-internal-link (buffer)
8610 "Return a buffer to be used for displaying the link target of internal links."
8611 (cond
8612 ((not org-display-internal-link-with-indirect-buffer)
8613 buffer)
8614 ((string-match "(Clone)$" (buffer-name buffer))
8615 (message "Buffer is already a clone, not making another one")
8616 ;; we also do not modify visibility in this case
8617 buffer)
8618 (t ; make a new indirect buffer for displaying the link
8619 (let* ((bn (buffer-name buffer))
8620 (ibn (concat bn "(Clone)"))
8621 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8622 (with-current-buffer ib (org-overview))
8623 ib))))
8625 (defun org-do-occur (regexp &optional cleanup)
8626 "Call the Emacs command `occur'.
8627 If CLEANUP is non-nil, remove the printout of the regular expression
8628 in the *Occur* buffer. This is useful if the regex is long and not useful
8629 to read."
8630 (occur regexp)
8631 (when cleanup
8632 (let ((cwin (selected-window)) win beg end)
8633 (when (setq win (get-buffer-window "*Occur*"))
8634 (select-window win))
8635 (goto-char (point-min))
8636 (when (re-search-forward "match[a-z]+" nil t)
8637 (setq beg (match-end 0))
8638 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8639 (setq end (1- (match-beginning 0)))))
8640 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8641 (goto-char (point-min))
8642 (select-window cwin))))
8644 ;;; The mark ring for links jumps
8646 (defvar org-mark-ring nil
8647 "Mark ring for positions before jumps in Org-mode.")
8648 (defvar org-mark-ring-last-goto nil
8649 "Last position in the mark ring used to go back.")
8650 ;; Fill and close the ring
8651 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8652 (loop for i from 1 to org-mark-ring-length do
8653 (push (make-marker) org-mark-ring))
8654 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8655 org-mark-ring)
8657 (defun org-mark-ring-push (&optional pos buffer)
8658 "Put the current position or POS into the mark ring and rotate it."
8659 (interactive)
8660 (setq pos (or pos (point)))
8661 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8662 (move-marker (car org-mark-ring)
8663 (or pos (point))
8664 (or buffer (current-buffer)))
8665 (message "%s"
8666 (substitute-command-keys
8667 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8669 (defun org-mark-ring-goto (&optional n)
8670 "Jump to the previous position in the mark ring.
8671 With prefix arg N, jump back that many stored positions. When
8672 called several times in succession, walk through the entire ring.
8673 Org-mode commands jumping to a different position in the current file,
8674 or to another Org-mode file, automatically push the old position
8675 onto the ring."
8676 (interactive "p")
8677 (let (p m)
8678 (if (eq last-command this-command)
8679 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8680 (setq p org-mark-ring))
8681 (setq org-mark-ring-last-goto p)
8682 (setq m (car p))
8683 (switch-to-buffer (marker-buffer m))
8684 (goto-char m)
8685 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8687 (defun org-remove-angle-brackets (s)
8688 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8689 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8691 (defun org-add-angle-brackets (s)
8692 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8693 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8695 (defun org-remove-double-quotes (s)
8696 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8697 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8700 ;;; Following specific links
8702 (defun org-follow-timestamp-link ()
8703 (cond
8704 ((org-at-date-range-p t)
8705 (let ((org-agenda-start-on-weekday)
8706 (t1 (match-string 1))
8707 (t2 (match-string 2)))
8708 (setq t1 (time-to-days (org-time-string-to-time t1))
8709 t2 (time-to-days (org-time-string-to-time t2)))
8710 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8711 ((org-at-timestamp-p t)
8712 (org-agenda-list nil (time-to-days (org-time-string-to-time
8713 (substring (match-string 1) 0 10)))
8715 (t (error "This should not happen"))))
8718 ;;; Following file links
8719 (defvar org-wait nil)
8720 (defun org-open-file (path &optional in-emacs line search)
8721 "Open the file at PATH.
8722 First, this expands any special file name abbreviations. Then the
8723 configuration variable `org-file-apps' is checked if it contains an
8724 entry for this file type, and if yes, the corresponding command is launched.
8726 If no application is found, Emacs simply visits the file.
8728 With optional prefix argument IN-EMACS, Emacs will visit the file.
8729 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8730 and o use an external application to visit the file.
8732 Optional LINE specifies a line to go to, optional SEARCH a string to
8733 search for. If LINE or SEARCH is given, the file will always be
8734 opened in Emacs.
8735 If the file does not exist, an error is thrown."
8736 (setq in-emacs (or in-emacs line search))
8737 (let* ((file (if (equal path "")
8738 buffer-file-name
8739 (substitute-in-file-name (expand-file-name path))))
8740 (apps (append org-file-apps (org-default-apps)))
8741 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8742 (dirp (if remp nil (file-directory-p file)))
8743 (file (if (and dirp org-open-directory-means-index-dot-org)
8744 (concat (file-name-as-directory file) "index.org")
8745 file))
8746 (a-m-a-p (assq 'auto-mode apps))
8747 (dfile (downcase file))
8748 (old-buffer (current-buffer))
8749 (old-pos (point))
8750 (old-mode major-mode)
8751 ext cmd)
8752 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8753 (setq ext (match-string 1 dfile))
8754 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8755 (setq ext (match-string 1 dfile))))
8756 (cond
8757 ((equal in-emacs '(16))
8758 (setq cmd (cdr (assoc 'system apps))))
8759 (in-emacs (setq cmd 'emacs))
8761 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8762 (and dirp (cdr (assoc 'directory apps)))
8763 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8764 'string-match)
8765 (cdr (assoc ext apps))
8766 (cdr (assoc t apps))))))
8767 (when (eq cmd 'system)
8768 (setq cmd (cdr (assoc 'system apps))))
8769 (when (eq cmd 'default)
8770 (setq cmd (cdr (assoc t apps))))
8771 (when (eq cmd 'mailcap)
8772 (require 'mailcap)
8773 (mailcap-parse-mailcaps)
8774 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8775 (command (mailcap-mime-info mime-type)))
8776 (if (stringp command)
8777 (setq cmd command)
8778 (setq cmd 'emacs))))
8779 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8780 (not (file-exists-p file))
8781 (not org-open-non-existing-files))
8782 (error "No such file: %s" file))
8783 (cond
8784 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8785 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8786 (while (string-match "['\"]%s['\"]" cmd)
8787 (setq cmd (replace-match "%s" t t cmd)))
8788 (while (string-match "%s" cmd)
8789 (setq cmd (replace-match
8790 (save-match-data
8791 (shell-quote-argument
8792 (convert-standard-filename file)))
8793 t t cmd)))
8794 (save-window-excursion
8795 (start-process-shell-command cmd nil cmd)
8796 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8798 ((or (stringp cmd)
8799 (eq cmd 'emacs))
8800 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8801 (widen)
8802 (if line (org-goto-line line)
8803 (if search (org-link-search search))))
8804 ((consp cmd)
8805 (let ((file (convert-standard-filename file)))
8806 (eval cmd)))
8807 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8808 (and (org-mode-p) (eq old-mode 'org-mode)
8809 (or (not (equal old-buffer (current-buffer)))
8810 (not (equal old-pos (point))))
8811 (org-mark-ring-push old-pos old-buffer))))
8813 (defun org-default-apps ()
8814 "Return the default applications for this operating system."
8815 (cond
8816 ((eq system-type 'darwin)
8817 org-file-apps-defaults-macosx)
8818 ((eq system-type 'windows-nt)
8819 org-file-apps-defaults-windowsnt)
8820 (t org-file-apps-defaults-gnu)))
8822 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8823 "Convert extensions to regular expressions in the cars of LIST.
8824 Also, weed out any non-string entries, because the return value is used
8825 only for regexp matching.
8826 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8827 point to the symbol `emacs', indicating that the file should
8828 be opened in Emacs."
8829 (append
8830 (delq nil
8831 (mapcar (lambda (x)
8832 (if (not (stringp (car x)))
8834 (if (string-match "\\W" (car x))
8836 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8837 list))
8838 (if add-auto-mode
8839 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8841 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8842 (defun org-file-remote-p (file)
8843 "Test whether FILE specifies a location on a remote system.
8844 Return non-nil if the location is indeed remote.
8846 For example, the filename \"/user@host:/foo\" specifies a location
8847 on the system \"/user@host:\"."
8848 (cond ((fboundp 'file-remote-p)
8849 (file-remote-p file))
8850 ((fboundp 'tramp-handle-file-remote-p)
8851 (tramp-handle-file-remote-p file))
8852 ((and (boundp 'ange-ftp-name-format)
8853 (string-match (car ange-ftp-name-format) file))
8855 (t nil)))
8858 ;;;; Refiling
8860 (defun org-get-org-file ()
8861 "Read a filename, with default directory `org-directory'."
8862 (let ((default (or org-default-notes-file remember-data-file)))
8863 (read-file-name (format "File name [%s]: " default)
8864 (file-name-as-directory org-directory)
8865 default)))
8867 (defun org-notes-order-reversed-p ()
8868 "Check if the current file should receive notes in reversed order."
8869 (cond
8870 ((not org-reverse-note-order) nil)
8871 ((eq t org-reverse-note-order) t)
8872 ((not (listp org-reverse-note-order)) nil)
8873 (t (catch 'exit
8874 (let ((all org-reverse-note-order)
8875 entry)
8876 (while (setq entry (pop all))
8877 (if (string-match (car entry) buffer-file-name)
8878 (throw 'exit (cdr entry))))
8879 nil)))))
8881 (defvar org-refile-target-table nil
8882 "The list of refile targets, created by `org-refile'.")
8884 (defvar org-agenda-new-buffers nil
8885 "Buffers created to visit agenda files.")
8887 (defun org-get-refile-targets (&optional default-buffer)
8888 "Produce a table with refile targets."
8889 (let ((case-fold-search nil)
8890 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8891 (entries (or org-refile-targets '((nil . (:level . 1)))))
8892 targets txt re files f desc descre fast-path-p level pos0)
8893 (message "Getting targets...")
8894 (with-current-buffer (or default-buffer (current-buffer))
8895 (while (setq entry (pop entries))
8896 (setq files (car entry) desc (cdr entry))
8897 (setq fast-path-p nil)
8898 (cond
8899 ((null files) (setq files (list (current-buffer))))
8900 ((eq files 'org-agenda-files)
8901 (setq files (org-agenda-files 'unrestricted)))
8902 ((and (symbolp files) (fboundp files))
8903 (setq files (funcall files)))
8904 ((and (symbolp files) (boundp files))
8905 (setq files (symbol-value files))))
8906 (if (stringp files) (setq files (list files)))
8907 (cond
8908 ((eq (car desc) :tag)
8909 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8910 ((eq (car desc) :todo)
8911 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8912 ((eq (car desc) :regexp)
8913 (setq descre (cdr desc)))
8914 ((eq (car desc) :level)
8915 (setq descre (concat "^\\*\\{" (number-to-string
8916 (if org-odd-levels-only
8917 (1- (* 2 (cdr desc)))
8918 (cdr desc)))
8919 "\\}[ \t]")))
8920 ((eq (car desc) :maxlevel)
8921 (setq fast-path-p t)
8922 (setq descre (concat "^\\*\\{1," (number-to-string
8923 (if org-odd-levels-only
8924 (1- (* 2 (cdr desc)))
8925 (cdr desc)))
8926 "\\}[ \t]")))
8927 (t (error "Bad refiling target description %s" desc)))
8928 (while (setq f (pop files))
8929 (with-current-buffer
8930 (if (bufferp f) f (org-get-agenda-file-buffer f))
8931 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8932 (setq f (expand-file-name f))
8933 (if (eq org-refile-use-outline-path 'file)
8934 (push (list (file-name-nondirectory f) f nil nil) targets))
8935 (save-excursion
8936 (save-restriction
8937 (widen)
8938 (goto-char (point-min))
8939 (while (re-search-forward descre nil t)
8940 (goto-char (setq pos0 (point-at-bol)))
8941 (catch 'next
8942 (when org-refile-target-verify-function
8943 (save-match-data
8944 (or (funcall org-refile-target-verify-function)
8945 (throw 'next t))))
8946 (when (looking-at org-complex-heading-regexp)
8947 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8948 txt (org-link-display-format (match-string 4))
8949 re (concat "^" (regexp-quote
8950 (buffer-substring (match-beginning 1)
8951 (match-end 4)))))
8952 (if (match-end 5) (setq re (concat re "[ \t]+"
8953 (regexp-quote
8954 (match-string 5)))))
8955 (setq re (concat re "[ \t]*$"))
8956 (when org-refile-use-outline-path
8957 (setq txt (mapconcat 'org-protect-slash
8958 (append
8959 (if (eq org-refile-use-outline-path 'file)
8960 (list (file-name-nondirectory
8961 (buffer-file-name (buffer-base-buffer))))
8962 (if (eq org-refile-use-outline-path 'full-file-path)
8963 (list (buffer-file-name (buffer-base-buffer)))))
8964 (org-get-outline-path fast-path-p level txt)
8965 (list txt))
8966 "/")))
8967 (push (list txt f re (point)) targets)))
8968 (when (= (point) pos0)
8969 ;; verification function has not moved point
8970 (goto-char (point-at-eol))))))))))
8971 (message "Getting targets...done")
8972 (nreverse targets)))
8974 (defun org-protect-slash (s)
8975 (while (string-match "/" s)
8976 (setq s (replace-match "\\" t t s)))
8979 (defvar org-olpa (make-vector 20 nil))
8981 (defun org-get-outline-path (&optional fastp level heading)
8982 "Return the outline path to the current entry, as a list."
8983 (if fastp
8984 (progn
8985 (if (> level 19)
8986 (error "Outline path failure, more than 19 levels."))
8987 (loop for i from level upto 19 do
8988 (aset org-olpa i nil))
8989 (prog1
8990 (delq nil (append org-olpa nil))
8991 (aset org-olpa level heading)))
8992 (let (rtn)
8993 (save-excursion
8994 (while (org-up-heading-safe)
8995 (when (looking-at org-complex-heading-regexp)
8996 (push (org-match-string-no-properties 4) rtn)))
8997 rtn))))
8999 (defvar org-refile-history nil
9000 "History for refiling operations.")
9002 (defvar org-after-refile-insert-hook nil
9003 "Hook run after `org-refile' has inserted its stuff at the new location.
9004 Note that this is still *before* the stuff will be removed from
9005 the *old* location.")
9007 (defun org-refile (&optional goto default-buffer rfloc)
9008 "Move the entry at point to another heading.
9009 The list of target headings is compiled using the information in
9010 `org-refile-targets', which see. This list is created before each use
9011 and will therefore always be up-to-date.
9013 At the target location, the entry is filed as a subitem of the target heading.
9014 Depending on `org-reverse-note-order', the new subitem will either be the
9015 first or the last subitem.
9017 If there is an active region, all entries in that region will be moved.
9018 However, the region must fulfil the requirement that the first heading
9019 is the first one sets the top-level of the moved text - at most siblings
9020 below it are allowed.
9022 With prefix arg GOTO, the command will only visit the target location,
9023 not actually move anything.
9024 With a double prefix `C-u C-u', go to the location where the last refiling
9025 operation has put the subtree.
9026 With a prefix argument of `2', refile to the running clock.
9028 RFLOC can be a refile location obtained in a different way.
9030 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9031 (interactive "P")
9032 (let* ((cbuf (current-buffer))
9033 (regionp (org-region-active-p))
9034 (region-start (and regionp (region-beginning)))
9035 (region-end (and regionp (region-end)))
9036 (region-length (and regionp (- region-end region-start)))
9037 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9038 pos it nbuf file re level reversed)
9039 (when regionp
9040 (goto-char region-start)
9041 (or (bolp) (goto-char (point-at-bol)))
9042 (setq region-start (point))
9043 (unless (org-kill-is-subtree-p
9044 (buffer-substring region-start region-end))
9045 (error "The region is not a (sequence of) subtree(s)")))
9046 (if (equal goto '(16))
9047 (org-refile-goto-last-stored)
9048 (when (or
9049 (and (equal goto 2)
9050 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9051 (prog1
9052 (setq it (list (or org-clock-heading "running clock")
9053 (buffer-file-name
9054 (marker-buffer org-clock-hd-marker))
9056 (marker-position org-clock-hd-marker)))
9057 (setq goto nil)))
9058 (setq it (or rfloc
9059 (save-excursion
9060 (org-refile-get-location
9061 (if goto "Goto: " "Refile to: ") default-buffer
9062 org-refile-allow-creating-parent-nodes)))))
9063 (setq file (nth 1 it)
9064 re (nth 2 it)
9065 pos (nth 3 it))
9066 (if (and (not goto)
9068 (equal (buffer-file-name) file)
9069 (if regionp
9070 (and (>= pos region-start)
9071 (<= pos region-end))
9072 (and (>= pos (point))
9073 (< pos (save-excursion
9074 (org-end-of-subtree t t))))))
9075 (error "Cannot refile to position inside the tree or region"))
9077 (setq nbuf (or (find-buffer-visiting file)
9078 (find-file-noselect file)))
9079 (if goto
9080 (progn
9081 (switch-to-buffer nbuf)
9082 (goto-char pos)
9083 (org-show-context 'org-goto))
9084 (if regionp
9085 (progn
9086 (org-kill-new (buffer-substring region-start region-end))
9087 (org-save-markers-in-region region-start region-end))
9088 (org-copy-subtree 1 nil t))
9089 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9090 (find-file-noselect file)))
9091 (setq reversed (org-notes-order-reversed-p))
9092 (save-excursion
9093 (save-restriction
9094 (widen)
9095 (if pos
9096 (progn
9097 (goto-char pos)
9098 (looking-at outline-regexp)
9099 (setq level (org-get-valid-level (funcall outline-level) 1))
9100 (goto-char
9101 (if reversed
9102 (or (outline-next-heading) (point-max))
9103 (or (save-excursion (org-get-next-sibling))
9104 (org-end-of-subtree t t)
9105 (point-max)))))
9106 (setq level 1)
9107 (if (not reversed)
9108 (goto-char (point-max))
9109 (goto-char (point-min))
9110 (or (outline-next-heading) (goto-char (point-max)))))
9111 (if (not (bolp)) (newline))
9112 (bookmark-set "org-refile-last-stored")
9113 (org-paste-subtree level)
9114 (if (fboundp 'deactivate-mark) (deactivate-mark))
9115 (run-hooks 'org-after-refile-insert-hook))))
9116 (if regionp
9117 (delete-region (point) (+ (point) region-length))
9118 (org-cut-subtree))
9119 (when (featurep 'org-inlinetask)
9120 (org-inlinetask-remove-END-maybe))
9121 (setq org-markers-to-move nil)
9122 (message "Refiled to \"%s\"" (car it))))))
9123 (org-reveal))
9125 (defun org-refile-goto-last-stored ()
9126 "Go to the location where the last refile was stored."
9127 (interactive)
9128 (bookmark-jump "org-refile-last-stored")
9129 (message "This is the location of the last refile"))
9131 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9132 "Prompt the user for a refile location, using PROMPT."
9133 (let ((org-refile-targets org-refile-targets)
9134 (org-refile-use-outline-path org-refile-use-outline-path))
9135 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9136 (unless org-refile-target-table
9137 (error "No refile targets"))
9138 (let* ((cbuf (current-buffer))
9139 (partial-completion-mode nil)
9140 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9141 (cfunc (if (and org-refile-use-outline-path
9142 org-outline-path-complete-in-steps)
9143 'org-olpath-completing-read
9144 'org-icompleting-read))
9145 (extra (if org-refile-use-outline-path "/" ""))
9146 (filename (and cfn (expand-file-name cfn)))
9147 (tbl (mapcar
9148 (lambda (x)
9149 (if (and (not (member org-refile-use-outline-path
9150 '(file full-file-path)))
9151 (not (equal filename (nth 1 x))))
9152 (cons (concat (car x) extra " ("
9153 (file-name-nondirectory (nth 1 x)) ")")
9154 (cdr x))
9155 (cons (concat (car x) extra) (cdr x))))
9156 org-refile-target-table))
9157 (completion-ignore-case t)
9158 pa answ parent-target child parent old-hist)
9159 (setq old-hist org-refile-history)
9160 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9161 nil 'org-refile-history))
9162 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9163 (if pa
9164 (progn
9165 (when (or (not org-refile-history)
9166 (not (eq old-hist org-refile-history))
9167 (not (equal (car pa) (car org-refile-history))))
9168 (setq org-refile-history
9169 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9170 org-refile-history
9171 (cdr org-refile-history))))
9172 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9173 (pop org-refile-history)))
9175 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9176 (setq parent (match-string 1 answ)
9177 child (match-string 2 answ))
9178 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9179 (when (and parent-target
9180 (or (eq new-nodes t)
9181 (and (eq new-nodes 'confirm)
9182 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9183 (org-refile-new-child parent-target child))))))
9185 (defun org-refile-new-child (parent-target child)
9186 "Use refile target PARENT-TARGET to add new CHILD below it."
9187 (unless parent-target
9188 (error "Cannot find parent for new node"))
9189 (let ((file (nth 1 parent-target))
9190 (pos (nth 3 parent-target))
9191 level)
9192 (with-current-buffer (or (find-buffer-visiting file)
9193 (find-file-noselect file))
9194 (save-excursion
9195 (save-restriction
9196 (widen)
9197 (if pos
9198 (goto-char pos)
9199 (goto-char (point-max))
9200 (if (not (bolp)) (newline)))
9201 (when (looking-at outline-regexp)
9202 (setq level (funcall outline-level))
9203 (org-end-of-subtree t t))
9204 (org-back-over-empty-lines)
9205 (insert "\n" (make-string
9206 (if pos (org-get-valid-level level 1) 1) ?*)
9207 " " child "\n")
9208 (beginning-of-line 0)
9209 (list (concat (car parent-target) "/" child) file "" (point)))))))
9211 (defun org-olpath-completing-read (prompt collection &rest args)
9212 "Read an outline path like a file name."
9213 (let ((thetable collection)
9214 (org-completion-use-ido nil) ; does not work with ido.
9215 (org-completion-use-iswitchb nil)) ; or iswitchb
9216 (apply
9217 'org-icompleting-read prompt
9218 (lambda (string predicate &optional flag)
9219 (let (rtn r f (l (length string)))
9220 (cond
9221 ((eq flag nil)
9222 ;; try completion
9223 (try-completion string thetable))
9224 ((eq flag t)
9225 ;; all-completions
9226 (setq rtn (all-completions string thetable predicate))
9227 (mapcar
9228 (lambda (x)
9229 (setq r (substring x l))
9230 (if (string-match " ([^)]*)$" x)
9231 (setq f (match-string 0 x))
9232 (setq f ""))
9233 (if (string-match "/" r)
9234 (concat string (substring r 0 (match-end 0)) f)
9236 rtn))
9237 ((eq flag 'lambda)
9238 ;; exact match?
9239 (assoc string thetable)))
9241 args)))
9243 ;;;; Dynamic blocks
9245 (defun org-find-dblock (name)
9246 "Find the first dynamic block with name NAME in the buffer.
9247 If not found, stay at current position and return nil."
9248 (let (pos)
9249 (save-excursion
9250 (goto-char (point-min))
9251 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9252 nil t)
9253 (match-beginning 0))))
9254 (if pos (goto-char pos))
9255 pos))
9257 (defconst org-dblock-start-re
9258 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9259 "Matches the startline of a dynamic block, with parameters.")
9261 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9262 "Matches the end of a dynamic block.")
9264 (defun org-create-dblock (plist)
9265 "Create a dynamic block section, with parameters taken from PLIST.
9266 PLIST must contain a :name entry which is used as name of the block."
9267 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9268 (end-of-line 1)
9269 (newline))
9270 (let ((col (current-column))
9271 (name (plist-get plist :name)))
9272 (insert "#+BEGIN: " name)
9273 (while plist
9274 (if (eq (car plist) :name)
9275 (setq plist (cddr plist))
9276 (insert " " (prin1-to-string (pop plist)))))
9277 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9278 (beginning-of-line -2)))
9280 (defun org-prepare-dblock ()
9281 "Prepare dynamic block for refresh.
9282 This empties the block, puts the cursor at the insert position and returns
9283 the property list including an extra property :name with the block name."
9284 (unless (looking-at org-dblock-start-re)
9285 (error "Not at a dynamic block"))
9286 (let* ((begdel (1+ (match-end 0)))
9287 (name (org-no-properties (match-string 1)))
9288 (params (append (list :name name)
9289 (read (concat "(" (match-string 3) ")")))))
9290 (save-excursion
9291 (beginning-of-line 1)
9292 (skip-chars-forward " \t")
9293 (setq params (plist-put params :indentation-column (current-column))))
9294 (unless (re-search-forward org-dblock-end-re nil t)
9295 (error "Dynamic block not terminated"))
9296 (setq params
9297 (append params
9298 (list :content (buffer-substring
9299 begdel (match-beginning 0)))))
9300 (delete-region begdel (match-beginning 0))
9301 (goto-char begdel)
9302 (open-line 1)
9303 params))
9305 (defun org-map-dblocks (&optional command)
9306 "Apply COMMAND to all dynamic blocks in the current buffer.
9307 If COMMAND is not given, use `org-update-dblock'."
9308 (let ((cmd (or command 'org-update-dblock))
9309 pos)
9310 (save-excursion
9311 (goto-char (point-min))
9312 (while (re-search-forward org-dblock-start-re nil t)
9313 (goto-char (setq pos (match-beginning 0)))
9314 (condition-case nil
9315 (funcall cmd)
9316 (error (message "Error during update of dynamic block")))
9317 (goto-char pos)
9318 (unless (re-search-forward org-dblock-end-re nil t)
9319 (error "Dynamic block not terminated"))))))
9321 (defun org-dblock-update (&optional arg)
9322 "User command for updating dynamic blocks.
9323 Update the dynamic block at point. With prefix ARG, update all dynamic
9324 blocks in the buffer."
9325 (interactive "P")
9326 (if arg
9327 (org-update-all-dblocks)
9328 (or (looking-at org-dblock-start-re)
9329 (org-beginning-of-dblock))
9330 (org-update-dblock)))
9332 (defun org-update-dblock ()
9333 "Update the dynamic block at point
9334 This means to empty the block, parse for parameters and then call
9335 the correct writing function."
9336 (save-window-excursion
9337 (let* ((pos (point))
9338 (line (org-current-line))
9339 (params (org-prepare-dblock))
9340 (name (plist-get params :name))
9341 (indent (plist-get params :indentation-column))
9342 (cmd (intern (concat "org-dblock-write:" name))))
9343 (message "Updating dynamic block `%s' at line %d..." name line)
9344 (funcall cmd params)
9345 (message "Updating dynamic block `%s' at line %d...done" name line)
9346 (goto-char pos)
9347 (when (and indent (> indent 0))
9348 (setq indent (make-string indent ?\ ))
9349 (save-excursion
9350 (org-beginning-of-dblock)
9351 (forward-line 1)
9352 (while (not (looking-at org-dblock-end-re))
9353 (insert indent)
9354 (beginning-of-line 2))
9355 (when (looking-at org-dblock-end-re)
9356 (and (looking-at "[ \t]+")
9357 (replace-match ""))
9358 (insert indent)))))))
9360 (defun org-beginning-of-dblock ()
9361 "Find the beginning of the dynamic block at point.
9362 Error if there is no such block at point."
9363 (let ((pos (point))
9364 beg)
9365 (end-of-line 1)
9366 (if (and (re-search-backward org-dblock-start-re nil t)
9367 (setq beg (match-beginning 0))
9368 (re-search-forward org-dblock-end-re nil t)
9369 (> (match-end 0) pos))
9370 (goto-char beg)
9371 (goto-char pos)
9372 (error "Not in a dynamic block"))))
9374 (defun org-update-all-dblocks ()
9375 "Update all dynamic blocks in the buffer.
9376 This function can be used in a hook."
9377 (when (org-mode-p)
9378 (org-map-dblocks 'org-update-dblock)))
9381 ;;;; Completion
9383 (defconst org-additional-option-like-keywords
9384 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9385 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9386 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "LATEX_CLASS:" "ATTR_LaTeX"
9387 "BEGIN:" "END:"
9388 "ORGTBL" "TBLFM:" "TBLNAME:"
9389 "BEGIN_EXAMPLE" "END_EXAMPLE"
9390 "BEGIN_QUOTE" "END_QUOTE"
9391 "BEGIN_VERSE" "END_VERSE"
9392 "BEGIN_CENTER" "END_CENTER"
9393 "BEGIN_SRC" "END_SRC"
9394 "CATEGORY" "COLUMNS"
9395 "CAPTION" "LABEL"
9396 "SETUPFILE"
9397 "BIND"
9398 "MACRO"))
9400 (defcustom org-structure-template-alist
9402 ("s" "#+begin_src ?\n\n#+end_src"
9403 "<src lang=\"?\">\n\n</src>")
9404 ("e" "#+begin_example\n?\n#+end_example"
9405 "<example>\n?\n</example>")
9406 ("q" "#+begin_quote\n?\n#+end_quote"
9407 "<quote>\n?\n</quote>")
9408 ("v" "#+begin_verse\n?\n#+end_verse"
9409 "<verse>\n?\n/verse>")
9410 ("c" "#+begin_center\n?\n#+end_center"
9411 "<center>\n?\n/center>")
9412 ("l" "#+begin_latex\n?\n#+end_latex"
9413 "<literal style=\"latex\">\n?\n</literal>")
9414 ("L" "#+latex: "
9415 "<literal style=\"latex\">?</literal>")
9416 ("h" "#+begin_html\n?\n#+end_html"
9417 "<literal style=\"html\">\n?\n</literal>")
9418 ("H" "#+html: "
9419 "<literal style=\"html\">?</literal>")
9420 ("a" "#+begin_ascii\n?\n#+end_ascii")
9421 ("A" "#+ascii: ")
9422 ("i" "#+include %file ?"
9423 "<include file=%file markup=\"?\">")
9425 "Structure completion elements.
9426 This is a list of abbreviation keys and values. The value gets inserted
9427 it you type @samp{.} followed by the key and then the completion key,
9428 usually `M-TAB'. %file will be replaced by a file name after prompting
9429 for the file using completion.
9430 There are two templates for each key, the first uses the original Org syntax,
9431 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9432 the default when the /org-mtags.el/ module has been loaded. See also the
9433 variable `org-mtags-prefer-muse-templates'.
9434 This is an experimental feature, it is undecided if it is going to stay in."
9435 :group 'org-completion
9436 :type '(repeat
9437 (string :tag "Key")
9438 (string :tag "Template")
9439 (string :tag "Muse Template")))
9441 (defun org-try-structure-completion ()
9442 "Try to complete a structure template before point.
9443 This looks for strings like \"<e\" on an otherwise empty line and
9444 expands them."
9445 (let ((l (buffer-substring (point-at-bol) (point)))
9447 (when (and (looking-at "[ \t]*$")
9448 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9449 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9450 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9451 (match-beginning 1)) a)
9452 t)))
9454 (defun org-complete-expand-structure-template (start cell)
9455 "Expand a structure template."
9456 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9457 (rpl (nth (if musep 2 1) cell))
9458 (ind ""))
9459 (delete-region start (point))
9460 (when (string-match "\\`#\\+" rpl)
9461 (cond
9462 ((bolp))
9463 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9464 (setq ind (buffer-substring (point-at-bol) (point))))
9465 (t (newline))))
9466 (setq start (point))
9467 (if (string-match "%file" rpl)
9468 (setq rpl (replace-match
9469 (concat
9470 "\""
9471 (save-match-data
9472 (abbreviate-file-name (read-file-name "Include file: ")))
9473 "\"")
9474 t t rpl)))
9475 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9476 (concat "\n" ind)))
9477 (insert rpl)
9478 (if (re-search-backward "\\?" start t) (delete-char 1))))
9481 (defun org-complete (&optional arg)
9482 "Perform completion on word at point.
9483 At the beginning of a headline, this completes TODO keywords as given in
9484 `org-todo-keywords'.
9485 If the current word is preceded by a backslash, completes the TeX symbols
9486 that are supported for HTML support.
9487 If the current word is preceded by \"#+\", completes special words for
9488 setting file options.
9489 In the line after \"#+STARTUP:, complete valid keywords.\"
9490 At all other locations, this simply calls the value of
9491 `org-completion-fallback-command'."
9492 (interactive "P")
9493 (org-without-partial-completion
9494 (catch 'exit
9495 (let* ((a nil)
9496 (end (point))
9497 (beg1 (save-excursion
9498 (skip-chars-backward (org-re "[:alnum:]_@"))
9499 (point)))
9500 (beg (save-excursion
9501 (skip-chars-backward "a-zA-Z0-9_:$")
9502 (point)))
9503 (confirm (lambda (x) (stringp (car x))))
9504 (searchhead (equal (char-before beg) ?*))
9505 (struct
9506 (when (and (member (char-before beg1) '(?. ?<))
9507 (setq a (assoc (buffer-substring beg1 (point))
9508 org-structure-template-alist)))
9509 (org-complete-expand-structure-template (1- beg1) a)
9510 (throw 'exit t)))
9511 (tag (and (equal (char-before beg1) ?:)
9512 (equal (char-after (point-at-bol)) ?*)))
9513 (prop (and (equal (char-before beg1) ?:)
9514 (not (equal (char-after (point-at-bol)) ?*))))
9515 (texp (equal (char-before beg) ?\\))
9516 (link (equal (char-before beg) ?\[))
9517 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9518 beg)
9519 "#+"))
9520 (startup (string-match "^#\\+STARTUP:.*"
9521 (buffer-substring (point-at-bol) (point))))
9522 (completion-ignore-case opt)
9523 (type nil)
9524 (tbl nil)
9525 (table (cond
9526 (opt
9527 (setq type :opt)
9528 (require 'org-exp)
9529 (append
9530 (delq nil
9531 (mapcar
9532 (lambda (x)
9533 (if (string-match
9534 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9535 (cons (match-string 2 x)
9536 (match-string 1 x))))
9537 (org-split-string (org-get-current-options) "\n")))
9538 (mapcar 'list org-additional-option-like-keywords)))
9539 (startup
9540 (setq type :startup)
9541 org-startup-options)
9542 (link (append org-link-abbrev-alist-local
9543 org-link-abbrev-alist))
9544 (texp
9545 (setq type :tex)
9546 org-html-entities)
9547 ((string-match "\\`\\*+[ \t]+\\'"
9548 (buffer-substring (point-at-bol) beg))
9549 (setq type :todo)
9550 (mapcar 'list org-todo-keywords-1))
9551 (searchhead
9552 (setq type :searchhead)
9553 (save-excursion
9554 (goto-char (point-min))
9555 (while (re-search-forward org-todo-line-regexp nil t)
9556 (push (list
9557 (org-make-org-heading-search-string
9558 (match-string 3) t))
9559 tbl)))
9560 tbl)
9561 (tag (setq type :tag beg beg1)
9562 (or org-tag-alist (org-get-buffer-tags)))
9563 (prop (setq type :prop beg beg1)
9564 (mapcar 'list (org-buffer-property-keys nil t t)))
9565 (t (progn
9566 (call-interactively org-completion-fallback-command)
9567 (throw 'exit nil)))))
9568 (pattern (buffer-substring-no-properties beg end))
9569 (completion (try-completion pattern table confirm)))
9570 (cond ((eq completion t)
9571 (if (not (assoc (upcase pattern) table))
9572 (message "Already complete")
9573 (if (and (equal type :opt)
9574 (not (member (car (assoc (upcase pattern) table))
9575 org-additional-option-like-keywords)))
9576 (insert (substring (cdr (assoc (upcase pattern) table))
9577 (length pattern)))
9578 (if (memq type '(:tag :prop)) (insert ":")))))
9579 ((null completion)
9580 (message "Can't find completion for \"%s\"" pattern)
9581 (ding))
9582 ((not (string= pattern completion))
9583 (delete-region beg end)
9584 (if (string-match " +$" completion)
9585 (setq completion (replace-match "" t t completion)))
9586 (insert completion)
9587 (if (get-buffer-window "*Completions*")
9588 (delete-window (get-buffer-window "*Completions*")))
9589 (if (assoc completion table)
9590 (if (eq type :todo) (insert " ")
9591 (if (memq type '(:tag :prop)) (insert ":"))))
9592 (if (and (equal type :opt) (assoc completion table))
9593 (message "%s" (substitute-command-keys
9594 "Press \\[org-complete] again to insert example settings"))))
9596 (message "Making completion list...")
9597 (let ((list (sort (all-completions pattern table confirm)
9598 'string<)))
9599 (with-output-to-temp-buffer "*Completions*"
9600 (condition-case nil
9601 ;; Protection needed for XEmacs and emacs 21
9602 (display-completion-list list pattern)
9603 (error (display-completion-list list)))))
9604 (message "Making completion list...%s" "done")))))))
9606 ;;;; TODO, DEADLINE, Comments
9608 (defun org-toggle-comment ()
9609 "Change the COMMENT state of an entry."
9610 (interactive)
9611 (save-excursion
9612 (org-back-to-heading)
9613 (let (case-fold-search)
9614 (if (looking-at (concat outline-regexp
9615 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9616 (replace-match "" t t nil 1)
9617 (if (looking-at outline-regexp)
9618 (progn
9619 (goto-char (match-end 0))
9620 (insert org-comment-string " ")))))))
9622 (defvar org-last-todo-state-is-todo nil
9623 "This is non-nil when the last TODO state change led to a TODO state.
9624 If the last change removed the TODO tag or switched to DONE, then
9625 this is nil.")
9627 (defvar org-setting-tags nil) ; dynamically skipped
9629 (defun org-parse-local-options (string var)
9630 "Parse STRING for startup setting relevant for variable VAR."
9631 (let ((rtn (symbol-value var))
9632 e opts)
9633 (save-match-data
9634 (if (or (not string) (not (string-match "\\S-" string)))
9636 (setq opts (delq nil (mapcar (lambda (x)
9637 (setq e (assoc x org-startup-options))
9638 (if (eq (nth 1 e) var) e nil))
9639 (org-split-string string "[ \t]+"))))
9640 (if (not opts)
9642 (setq rtn nil)
9643 (while (setq e (pop opts))
9644 (if (not (nth 3 e))
9645 (setq rtn (nth 2 e))
9646 (if (not (listp rtn)) (setq rtn nil))
9647 (push (nth 2 e) rtn)))
9648 rtn)))))
9650 (defvar org-todo-setup-filter-hook nil
9651 "Hook for functions that pre-filter todo specs.
9653 Each function takes a todo spec and returns either `nil' or the spec
9654 transformed into canonical form." )
9656 (defvar org-todo-get-default-hook nil
9657 "Hook for functions that get a default item for todo.
9659 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9660 `nil' or a string to be used for the todo mark." )
9662 (defvar org-agenda-headline-snapshot-before-repeat)
9664 (defun org-todo (&optional arg)
9665 "Change the TODO state of an item.
9666 The state of an item is given by a keyword at the start of the heading,
9667 like
9668 *** TODO Write paper
9669 *** DONE Call mom
9671 The different keywords are specified in the variable `org-todo-keywords'.
9672 By default the available states are \"TODO\" and \"DONE\".
9673 So for this example: when the item starts with TODO, it is changed to DONE.
9674 When it starts with DONE, the DONE is removed. And when neither TODO nor
9675 DONE are present, add TODO at the beginning of the heading.
9677 With C-u prefix arg, use completion to determine the new state.
9678 With numeric prefix arg, switch to that state.
9679 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9680 With a tripple C-u prefix, circumvent any state blocking.
9682 For calling through lisp, arg is also interpreted in the following way:
9683 'none -> empty state
9684 \"\"(empty string) -> switch to empty state
9685 'done -> switch to DONE
9686 'nextset -> switch to the next set of keywords
9687 'previousset -> switch to the previous set of keywords
9688 \"WAITING\" -> switch to the specified keyword, but only if it
9689 really is a member of `org-todo-keywords'."
9690 (interactive "P")
9691 (if (equal arg '(16)) (setq arg 'nextset))
9692 (let ((org-blocker-hook org-blocker-hook)
9693 (case-fold-search nil))
9694 (when (equal arg '(64))
9695 (setq arg nil org-blocker-hook nil))
9696 (when (and org-blocker-hook
9697 (or org-inhibit-blocking
9698 (org-entry-get nil "NOBLOCKING")))
9699 (setq org-blocker-hook nil))
9700 (save-excursion
9701 (catch 'exit
9702 (org-back-to-heading t)
9703 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9704 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9705 (looking-at " *"))
9706 (let* ((match-data (match-data))
9707 (startpos (point-at-bol))
9708 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9709 (org-log-done org-log-done)
9710 (org-log-repeat org-log-repeat)
9711 (org-todo-log-states org-todo-log-states)
9712 (this (match-string 1))
9713 (hl-pos (match-beginning 0))
9714 (head (org-get-todo-sequence-head this))
9715 (ass (assoc head org-todo-kwd-alist))
9716 (interpret (nth 1 ass))
9717 (done-word (nth 3 ass))
9718 (final-done-word (nth 4 ass))
9719 (last-state (or this ""))
9720 (completion-ignore-case t)
9721 (member (member this org-todo-keywords-1))
9722 (tail (cdr member))
9723 (state (cond
9724 ((and org-todo-key-trigger
9725 (or (and (equal arg '(4))
9726 (eq org-use-fast-todo-selection 'prefix))
9727 (and (not arg) org-use-fast-todo-selection
9728 (not (eq org-use-fast-todo-selection
9729 'prefix)))))
9730 ;; Use fast selection
9731 (org-fast-todo-selection))
9732 ((and (equal arg '(4))
9733 (or (not org-use-fast-todo-selection)
9734 (not org-todo-key-trigger)))
9735 ;; Read a state with completion
9736 (org-icompleting-read
9737 "State: " (mapcar (lambda(x) (list x))
9738 org-todo-keywords-1)
9739 nil t))
9740 ((eq arg 'right)
9741 (if this
9742 (if tail (car tail) nil)
9743 (car org-todo-keywords-1)))
9744 ((eq arg 'left)
9745 (if (equal member org-todo-keywords-1)
9747 (if this
9748 (nth (- (length org-todo-keywords-1)
9749 (length tail) 2)
9750 org-todo-keywords-1)
9751 (org-last org-todo-keywords-1))))
9752 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9753 (setq arg nil))) ; hack to fall back to cycling
9754 (arg
9755 ;; user or caller requests a specific state
9756 (cond
9757 ((equal arg "") nil)
9758 ((eq arg 'none) nil)
9759 ((eq arg 'done) (or done-word (car org-done-keywords)))
9760 ((eq arg 'nextset)
9761 (or (car (cdr (member head org-todo-heads)))
9762 (car org-todo-heads)))
9763 ((eq arg 'previousset)
9764 (let ((org-todo-heads (reverse org-todo-heads)))
9765 (or (car (cdr (member head org-todo-heads)))
9766 (car org-todo-heads))))
9767 ((car (member arg org-todo-keywords-1)))
9768 ((stringp arg)
9769 (error "State `%s' not valid in this file" arg))
9770 ((nth (1- (prefix-numeric-value arg))
9771 org-todo-keywords-1))))
9772 ((null member) (or head (car org-todo-keywords-1)))
9773 ((equal this final-done-word) nil) ;; -> make empty
9774 ((null tail) nil) ;; -> first entry
9775 ((memq interpret '(type priority))
9776 (if (eq this-command last-command)
9777 (car tail)
9778 (if (> (length tail) 0)
9779 (or done-word (car org-done-keywords))
9780 nil)))
9782 (car tail))))
9783 (state (or
9784 (run-hook-with-args-until-success
9785 'org-todo-get-default-hook state last-state)
9786 state))
9787 (next (if state (concat " " state " ") " "))
9788 (change-plist (list :type 'todo-state-change :from this :to state
9789 :position startpos))
9790 dolog now-done-p)
9791 (when org-blocker-hook
9792 (setq org-last-todo-state-is-todo
9793 (not (member this org-done-keywords)))
9794 (unless (save-excursion
9795 (save-match-data
9796 (run-hook-with-args-until-failure
9797 'org-blocker-hook change-plist)))
9798 (if (interactive-p)
9799 (error "TODO state change from %s to %s blocked" this state)
9800 ;; fail silently
9801 (message "TODO state change from %s to %s blocked" this state)
9802 (throw 'exit nil))))
9803 (store-match-data match-data)
9804 (replace-match next t t)
9805 (unless (pos-visible-in-window-p hl-pos)
9806 (message "TODO state changed to %s" (org-trim next)))
9807 (unless head
9808 (setq head (org-get-todo-sequence-head state)
9809 ass (assoc head org-todo-kwd-alist)
9810 interpret (nth 1 ass)
9811 done-word (nth 3 ass)
9812 final-done-word (nth 4 ass)))
9813 (when (memq arg '(nextset previousset))
9814 (message "Keyword-Set %d/%d: %s"
9815 (- (length org-todo-sets) -1
9816 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9817 (length org-todo-sets)
9818 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9819 (setq org-last-todo-state-is-todo
9820 (not (member state org-done-keywords)))
9821 (setq now-done-p (and (member state org-done-keywords)
9822 (not (member this org-done-keywords))))
9823 (and logging (org-local-logging logging))
9824 (when (and (or org-todo-log-states org-log-done)
9825 (not (eq org-inhibit-logging t))
9826 (not (memq arg '(nextset previousset))))
9827 ;; we need to look at recording a time and note
9828 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9829 (nth 2 (assoc this org-todo-log-states))))
9830 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9831 (setq dolog 'time))
9832 (when (and state
9833 (member state org-not-done-keywords)
9834 (not (member this org-not-done-keywords)))
9835 ;; This is now a todo state and was not one before
9836 ;; If there was a CLOSED time stamp, get rid of it.
9837 (org-add-planning-info nil nil 'closed))
9838 (when (and now-done-p org-log-done)
9839 ;; It is now done, and it was not done before
9840 (org-add-planning-info 'closed (org-current-time))
9841 (if (and (not dolog) (eq 'note org-log-done))
9842 (org-add-log-setup 'done state this 'findpos 'note)))
9843 (when (and state dolog)
9844 ;; This is a non-nil state, and we need to log it
9845 (org-add-log-setup 'state state this 'findpos dolog)))
9846 ;; Fixup tag positioning
9847 (org-todo-trigger-tag-changes state)
9848 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9849 (when org-provide-todo-statistics
9850 (org-update-parent-todo-statistics))
9851 (run-hooks 'org-after-todo-state-change-hook)
9852 (if (and arg (not (member state org-done-keywords)))
9853 (setq head (org-get-todo-sequence-head state)))
9854 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9855 ;; Do we need to trigger a repeat?
9856 (when now-done-p
9857 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9858 ;; This is for the agenda, take a snapshot of the headline.
9859 (save-match-data
9860 (setq org-agenda-headline-snapshot-before-repeat
9861 (org-get-heading))))
9862 (org-auto-repeat-maybe state))
9863 ;; Fixup cursor location if close to the keyword
9864 (if (and (outline-on-heading-p)
9865 (not (bolp))
9866 (save-excursion (beginning-of-line 1)
9867 (looking-at org-todo-line-regexp))
9868 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9869 (progn
9870 (goto-char (or (match-end 2) (match-end 1)))
9871 (and (looking-at " ") (just-one-space))))
9872 (when org-trigger-hook
9873 (save-excursion
9874 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9876 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9877 "Block turning an entry into a TODO, using the hierarchy.
9878 This checks whether the current task should be blocked from state
9879 changes. Such blocking occurs when:
9881 1. The task has children which are not all in a completed state.
9883 2. A task has a parent with the property :ORDERED:, and there
9884 are siblings prior to the current task with incomplete
9885 status.
9887 3. The parent of the task is blocked because it has siblings that should
9888 be done first, or is child of a block grandparent TODO entry."
9890 (catch 'dont-block
9891 ;; If this is not a todo state change, or if this entry is already DONE,
9892 ;; do not block
9893 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9894 (member (plist-get change-plist :from)
9895 (cons 'done org-done-keywords))
9896 (member (plist-get change-plist :to)
9897 (cons 'todo org-not-done-keywords)))
9898 (throw 'dont-block t))
9899 ;; If this task has children, and any are undone, it's blocked
9900 (save-excursion
9901 (org-back-to-heading t)
9902 (let ((this-level (funcall outline-level)))
9903 (outline-next-heading)
9904 (let ((child-level (funcall outline-level)))
9905 (while (and (not (eobp))
9906 (> child-level this-level))
9907 ;; this todo has children, check whether they are all
9908 ;; completed
9909 (if (and (not (org-entry-is-done-p))
9910 (org-entry-is-todo-p))
9911 (throw 'dont-block nil))
9912 (outline-next-heading)
9913 (setq child-level (funcall outline-level))))))
9914 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9915 ;; any previous siblings are undone, it's blocked
9916 (save-excursion
9917 (org-back-to-heading t)
9918 (let* ((pos (point))
9919 (parent-pos (and (org-up-heading-safe) (point))))
9920 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9921 (when (and (org-entry-get (point) "ORDERED")
9922 (forward-line 1)
9923 (re-search-forward org-not-done-heading-regexp pos t))
9924 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9925 ;; Search further up the hierarchy, to see if an anchestor is blocked
9926 (while t
9927 (goto-char parent-pos)
9928 (if (not (looking-at org-not-done-heading-regexp))
9929 (throw 'dont-block t)) ; do not block, parent is not a TODO
9930 (setq pos (point))
9931 (setq parent-pos (and (org-up-heading-safe) (point)))
9932 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9933 (when (and (org-entry-get (point) "ORDERED")
9934 (forward-line 1)
9935 (re-search-forward org-not-done-heading-regexp pos t))
9936 (throw 'dont-block nil))))))) ; block, older sibling not done.
9938 (defcustom org-track-ordered-property-with-tag nil
9939 "Should the ORDERED property also be shown as a tag?
9940 The ORDERED property decides if an entry should require subtasks to be
9941 completed in sequence. Since a property is not very visible, setting
9942 this option means that toggling the ORDERED property with the command
9943 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9944 not relevant for the behavior, but it makes things more visible.
9946 Note that toggling the tag with tags commands will not change the property
9947 and therefore not influence behavior!
9949 This can be t, meaning the tag ORDERED should be used, It can also be a
9950 string to select a different tag for this task."
9951 :group 'org-todo
9952 :type '(choice
9953 (const :tag "No tracking" nil)
9954 (const :tag "Track with ORDERED tag" t)
9955 (string :tag "Use other tag")))
9957 (defun org-toggle-ordered-property ()
9958 "Toggle the ORDERED property of the current entry.
9959 For better visibility, you can track the value of this property with a tag.
9960 See variable `org-track-ordered-property-with-tag'."
9961 (interactive)
9962 (let* ((t1 org-track-ordered-property-with-tag)
9963 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9964 (save-excursion
9965 (org-back-to-heading)
9966 (if (org-entry-get nil "ORDERED")
9967 (progn
9968 (org-delete-property "ORDERED")
9969 (and tag (org-toggle-tag tag 'off))
9970 (message "Subtasks can be completed in arbitrary order"))
9971 (org-entry-put nil "ORDERED" "t")
9972 (and tag (org-toggle-tag tag 'on))
9973 (message "Subtasks must be completed in sequence")))))
9975 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9976 (defun org-block-todo-from-checkboxes (change-plist)
9977 "Block turning an entry into a TODO, using checkboxes.
9978 This checks whether the current task should be blocked from state
9979 changes because there are uncheckd boxes in this entry."
9980 (catch 'dont-block
9981 ;; If this is not a todo state change, or if this entry is already DONE,
9982 ;; do not block
9983 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9984 (member (plist-get change-plist :from)
9985 (cons 'done org-done-keywords))
9986 (member (plist-get change-plist :to)
9987 (cons 'todo org-not-done-keywords)))
9988 (throw 'dont-block t))
9989 ;; If this task has checkboxes that are not checked, it's blocked
9990 (save-excursion
9991 (org-back-to-heading t)
9992 (let ((beg (point)) end)
9993 (outline-next-heading)
9994 (setq end (point))
9995 (goto-char beg)
9996 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9997 end t)
9998 (progn
9999 (if (boundp 'org-blocked-by-checkboxes)
10000 (setq org-blocked-by-checkboxes t))
10001 (throw 'dont-block nil)))))
10002 t)) ; do not block
10004 (defun org-update-statistics-cookies (all)
10005 "Update the statistics cookie, either from TODO or from checkboxes.
10006 This should be called with the cursor in a line with a statistics cookie."
10007 (interactive "P")
10008 (if all
10009 (progn
10010 (org-update-checkbox-count 'all)
10011 (org-map-entries 'org-update-parent-todo-statistics))
10012 (if (not (org-on-heading-p))
10013 (org-update-checkbox-count)
10014 (let ((pos (move-marker (make-marker) (point)))
10015 end l1 l2)
10016 (ignore-errors (org-back-to-heading t))
10017 (if (not (org-on-heading-p))
10018 (org-update-checkbox-count)
10019 (setq l1 (org-outline-level))
10020 (setq end (save-excursion
10021 (outline-next-heading)
10022 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10023 (point)))
10024 (if (and (save-excursion (re-search-forward
10025 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10026 (not (save-excursion (re-search-forward
10027 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10028 (org-update-checkbox-count)
10029 (if (and l2 (> l2 l1))
10030 (progn
10031 (goto-char end)
10032 (org-update-parent-todo-statistics))
10033 (error "No data for statistics cookie"))))
10034 (goto-char pos)
10035 (move-marker pos nil)))))
10037 (defvar org-entry-property-inherited-from) ;; defined below
10038 (defun org-update-parent-todo-statistics ()
10039 "Update any statistics cookie in the parent of the current headline.
10040 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10041 the entire subtree and this will travel up the hierarchy and update
10042 statistics everywhere."
10043 (interactive)
10044 (let* ((lim 0) prop
10045 (recursive (or (not org-hierarchical-todo-statistics)
10046 (string-match
10047 "\\<recursive\\>"
10048 (or (setq prop (org-entry-get
10049 nil "COOKIE_DATA" 'inherit)) ""))))
10050 (lim (or (and prop (marker-position
10051 org-entry-property-inherited-from))
10052 lim))
10053 (first t)
10054 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10055 level ltoggle l1 new ndel
10056 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10057 (catch 'exit
10058 (save-excursion
10059 (beginning-of-line 1)
10060 (if (org-at-heading-p)
10061 (setq ltoggle (funcall outline-level))
10062 (error "This should not happen"))
10063 (while (and (setq level (org-up-heading-safe))
10064 (or recursive first)
10065 (>= (point) lim))
10066 (setq first nil cookie-present nil)
10067 (unless (and level
10068 (not (string-match
10069 "\\<checkbox\\>"
10070 (downcase
10071 (or (org-entry-get
10072 nil "COOKIE_DATA")
10073 "")))))
10074 (throw 'exit nil))
10075 (while (re-search-forward box-re (point-at-eol) t)
10076 (setq cnt-all 0 cnt-done 0 cookie-present t)
10077 (setq is-percent (match-end 2))
10078 (save-match-data
10079 (unless (outline-next-heading) (throw 'exit nil))
10080 (while (and (looking-at org-complex-heading-regexp)
10081 (> (setq l1 (length (match-string 1))) level))
10082 (setq kwd (and (or recursive (= l1 ltoggle))
10083 (match-string 2)))
10084 (if (or (eq org-provide-todo-statistics 'all-headlines)
10085 (and (listp org-provide-todo-statistics)
10086 (or (member kwd org-provide-todo-statistics)
10087 (member kwd org-done-keywords))))
10088 (setq cnt-all (1+ cnt-all))
10089 (if (eq org-provide-todo-statistics t)
10090 (and kwd (setq cnt-all (1+ cnt-all)))))
10091 (and (member kwd org-done-keywords)
10092 (setq cnt-done (1+ cnt-done)))
10093 (outline-next-heading)))
10094 (setq new
10095 (if is-percent
10096 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10097 (format "[%d/%d]" cnt-done cnt-all))
10098 ndel (- (match-end 0) (match-beginning 0)))
10099 (goto-char (match-beginning 0))
10100 (insert new)
10101 (delete-region (point) (+ (point) ndel)))
10102 (when cookie-present
10103 (run-hook-with-args 'org-after-todo-statistics-hook
10104 cnt-done (- cnt-all cnt-done))))))
10105 (run-hooks 'org-todo-statistics-hook)))
10107 (defvar org-after-todo-statistics-hook nil
10108 "Hook that is called after a TODO statistics cookie has been updated.
10109 Each function is called with two arguments: the number of not-done entries
10110 and the number of done entries.
10112 For example, the following function, when added to this hook, will switch
10113 an entry to DONE when all children are done, and back to TODO when new
10114 entries are set to a TODO status. Note that this hook is only called
10115 when there is a statistics cookie in the headline!
10117 (defun org-summary-todo (n-done n-not-done)
10118 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10119 (let (org-log-done org-log-states) ; turn off logging
10120 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10123 (defvar org-todo-statistics-hook nil
10124 "Hook that is run whenever Org thinks TODO statistics should be updated.
10125 This hook runs even if there is no statisics cookie present, in which case
10126 `org-after-todo-statistics-hook' would not run.")
10128 (defun org-todo-trigger-tag-changes (state)
10129 "Apply the changes defined in `org-todo-state-tags-triggers'."
10130 (let ((l org-todo-state-tags-triggers)
10131 changes)
10132 (when (or (not state) (equal state ""))
10133 (setq changes (append changes (cdr (assoc "" l)))))
10134 (when (and (stringp state) (> (length state) 0))
10135 (setq changes (append changes (cdr (assoc state l)))))
10136 (when (member state org-not-done-keywords)
10137 (setq changes (append changes (cdr (assoc 'todo l)))))
10138 (when (member state org-done-keywords)
10139 (setq changes (append changes (cdr (assoc 'done l)))))
10140 (dolist (c changes)
10141 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10143 (defun org-local-logging (value)
10144 "Get logging settings from a property VALUE."
10145 (let* (words w a)
10146 ;; directly set the variables, they are already local.
10147 (setq org-log-done nil
10148 org-log-repeat nil
10149 org-todo-log-states nil)
10150 (setq words (org-split-string value))
10151 (while (setq w (pop words))
10152 (cond
10153 ((setq a (assoc w org-startup-options))
10154 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10155 (set (nth 1 a) (nth 2 a))))
10156 ((setq a (org-extract-log-state-settings w))
10157 (and (member (car a) org-todo-keywords-1)
10158 (push a org-todo-log-states)))))))
10160 (defun org-get-todo-sequence-head (kwd)
10161 "Return the head of the TODO sequence to which KWD belongs.
10162 If KWD is not set, check if there is a text property remembering the
10163 right sequence."
10164 (let (p)
10165 (cond
10166 ((not kwd)
10167 (or (get-text-property (point-at-bol) 'org-todo-head)
10168 (progn
10169 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10170 nil (point-at-eol)))
10171 (get-text-property p 'org-todo-head))))
10172 ((not (member kwd org-todo-keywords-1))
10173 (car org-todo-keywords-1))
10174 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10176 (defun org-fast-todo-selection ()
10177 "Fast TODO keyword selection with single keys.
10178 Returns the new TODO keyword, or nil if no state change should occur."
10179 (let* ((fulltable org-todo-key-alist)
10180 (done-keywords org-done-keywords) ;; needed for the faces.
10181 (maxlen (apply 'max (mapcar
10182 (lambda (x)
10183 (if (stringp (car x)) (string-width (car x)) 0))
10184 fulltable)))
10185 (expert nil)
10186 (fwidth (+ maxlen 3 1 3))
10187 (ncol (/ (- (window-width) 4) fwidth))
10188 tg cnt e c tbl
10189 groups ingroup)
10190 (save-excursion
10191 (save-window-excursion
10192 (if expert
10193 (set-buffer (get-buffer-create " *Org todo*"))
10194 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10195 (erase-buffer)
10196 (org-set-local 'org-done-keywords done-keywords)
10197 (setq tbl fulltable cnt 0)
10198 (while (setq e (pop tbl))
10199 (cond
10200 ((equal e '(:startgroup))
10201 (push '() groups) (setq ingroup t)
10202 (when (not (= cnt 0))
10203 (setq cnt 0)
10204 (insert "\n"))
10205 (insert "{ "))
10206 ((equal e '(:endgroup))
10207 (setq ingroup nil cnt 0)
10208 (insert "}\n"))
10209 ((equal e '(:newline))
10210 (when (not (= cnt 0))
10211 (setq cnt 0)
10212 (insert "\n")
10213 (setq e (car tbl))
10214 (while (equal (car tbl) '(:newline))
10215 (insert "\n")
10216 (setq tbl (cdr tbl)))))
10218 (setq tg (car e) c (cdr e))
10219 (if ingroup (push tg (car groups)))
10220 (setq tg (org-add-props tg nil 'face
10221 (org-get-todo-face tg)))
10222 (if (and (= cnt 0) (not ingroup)) (insert " "))
10223 (insert "[" c "] " tg (make-string
10224 (- fwidth 4 (length tg)) ?\ ))
10225 (when (= (setq cnt (1+ cnt)) ncol)
10226 (insert "\n")
10227 (if ingroup (insert " "))
10228 (setq cnt 0)))))
10229 (insert "\n")
10230 (goto-char (point-min))
10231 (if (not expert) (org-fit-window-to-buffer))
10232 (message "[a-z..]:Set [SPC]:clear")
10233 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10234 (cond
10235 ((or (= c ?\C-g)
10236 (and (= c ?q) (not (rassoc c fulltable))))
10237 (setq quit-flag t))
10238 ((= c ?\ ) nil)
10239 ((setq e (rassoc c fulltable) tg (car e))
10241 (t (setq quit-flag t)))))))
10243 (defun org-entry-is-todo-p ()
10244 (member (org-get-todo-state) org-not-done-keywords))
10246 (defun org-entry-is-done-p ()
10247 (member (org-get-todo-state) org-done-keywords))
10249 (defun org-get-todo-state ()
10250 (save-excursion
10251 (org-back-to-heading t)
10252 (and (looking-at org-todo-line-regexp)
10253 (match-end 2)
10254 (match-string 2))))
10256 (defun org-at-date-range-p (&optional inactive-ok)
10257 "Is the cursor inside a date range?"
10258 (interactive)
10259 (save-excursion
10260 (catch 'exit
10261 (let ((pos (point)))
10262 (skip-chars-backward "^[<\r\n")
10263 (skip-chars-backward "<[")
10264 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10265 (>= (match-end 0) pos)
10266 (throw 'exit t))
10267 (skip-chars-backward "^<[\r\n")
10268 (skip-chars-backward "<[")
10269 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10270 (>= (match-end 0) pos)
10271 (throw 'exit t)))
10272 nil)))
10274 (defun org-get-repeat (&optional tagline)
10275 "Check if there is a deadline/schedule with repeater in this entry."
10276 (save-match-data
10277 (save-excursion
10278 (org-back-to-heading t)
10279 (and (re-search-forward (if tagline
10280 (concat tagline "\\s-*" org-repeat-re)
10281 org-repeat-re)
10282 (org-entry-end-position) t)
10283 (match-string-no-properties 1)))))
10285 (defvar org-last-changed-timestamp)
10286 (defvar org-last-inserted-timestamp)
10287 (defvar org-log-post-message)
10288 (defvar org-log-note-purpose)
10289 (defvar org-log-note-how)
10290 (defvar org-log-note-extra)
10291 (defun org-auto-repeat-maybe (done-word)
10292 "Check if the current headline contains a repeated deadline/schedule.
10293 If yes, set TODO state back to what it was and change the base date
10294 of repeating deadline/scheduled time stamps to new date.
10295 This function is run automatically after each state change to a DONE state."
10296 ;; last-state is dynamically scoped into this function
10297 (let* ((repeat (org-get-repeat))
10298 (aa (assoc last-state org-todo-kwd-alist))
10299 (interpret (nth 1 aa))
10300 (head (nth 2 aa))
10301 (whata '(("d" . day) ("m" . month) ("y" . year)))
10302 (msg "Entry repeats: ")
10303 (org-log-done nil)
10304 (org-todo-log-states nil)
10305 (nshiftmax 10) (nshift 0)
10306 re type n what ts time)
10307 (when repeat
10308 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10309 (org-todo (if (eq interpret 'type) last-state head))
10310 (org-entry-put nil "LAST_REPEAT" (format-time-string
10311 (org-time-stamp-format t t)))
10312 (when org-log-repeat
10313 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10314 (memq 'org-add-log-note post-command-hook))
10315 ;; OK, we are already setup for some record
10316 (if (eq org-log-repeat 'note)
10317 ;; make sure we take a note, not only a time stamp
10318 (setq org-log-note-how 'note))
10319 ;; Set up for taking a record
10320 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10321 last-state
10322 'findpos org-log-repeat)))
10323 (org-back-to-heading t)
10324 (org-add-planning-info nil nil 'closed)
10325 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10326 org-deadline-time-regexp "\\)\\|\\("
10327 org-ts-regexp "\\)"))
10328 (while (re-search-forward
10329 re (save-excursion (outline-next-heading) (point)) t)
10330 (setq type (if (match-end 1) org-scheduled-string
10331 (if (match-end 3) org-deadline-string "Plain:"))
10332 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10333 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10334 (setq n (string-to-number (match-string 2 ts))
10335 what (match-string 3 ts))
10336 (if (equal what "w") (setq n (* n 7) what "d"))
10337 ;; Preparation, see if we need to modify the start date for the change
10338 (when (match-end 1)
10339 (setq time (save-match-data (org-time-string-to-time ts)))
10340 (cond
10341 ((equal (match-string 1 ts) ".")
10342 ;; Shift starting date to today
10343 (org-timestamp-change
10344 (- (time-to-days (current-time)) (time-to-days time))
10345 'day))
10346 ((equal (match-string 1 ts) "+")
10347 (while (or (= nshift 0)
10348 (<= (time-to-days time) (time-to-days (current-time))))
10349 (when (= (incf nshift) nshiftmax)
10350 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10351 (error "Abort")))
10352 (org-timestamp-change n (cdr (assoc what whata)))
10353 (org-at-timestamp-p t)
10354 (setq ts (match-string 1))
10355 (setq time (save-match-data (org-time-string-to-time ts))))
10356 (org-timestamp-change (- n) (cdr (assoc what whata)))
10357 ;; rematch, so that we have everything in place for the real shift
10358 (org-at-timestamp-p t)
10359 (setq ts (match-string 1))
10360 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10361 (org-timestamp-change n (cdr (assoc what whata)))
10362 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10363 (setq org-log-post-message msg)
10364 (message "%s" msg))))
10366 (defun org-show-todo-tree (arg)
10367 "Make a compact tree which shows all headlines marked with TODO.
10368 The tree will show the lines where the regexp matches, and all higher
10369 headlines above the match.
10370 With a \\[universal-argument] prefix, prompt for a regexp to match.
10371 With a numeric prefix N, construct a sparse tree for the Nth element
10372 of `org-todo-keywords-1'."
10373 (interactive "P")
10374 (let ((case-fold-search nil)
10375 (kwd-re
10376 (cond ((null arg) org-not-done-regexp)
10377 ((equal arg '(4))
10378 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10379 (mapcar 'list org-todo-keywords-1))))
10380 (concat "\\("
10381 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10382 "\\)\\>")))
10383 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10384 (regexp-quote (nth (1- (prefix-numeric-value arg))
10385 org-todo-keywords-1)))
10386 (t (error "Invalid prefix argument: %s" arg)))))
10387 (message "%d TODO entries found"
10388 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10390 (defun org-deadline (&optional remove time)
10391 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10392 With argument REMOVE, remove any deadline from the item.
10393 When TIME is set, it should be an internal time specification, and the
10394 scheduling will use the corresponding date."
10395 (interactive "P")
10396 (let ((old-date (org-entry-get nil "DEADLINE")))
10397 (if remove
10398 (progn
10399 (org-remove-timestamp-with-keyword org-deadline-string)
10400 (message "Item no longer has a deadline."))
10401 (if (org-get-repeat)
10402 (error "Cannot change deadline on task with repeater, please do that by hand")
10403 (org-add-planning-info 'deadline time 'closed)
10404 (when (and old-date org-log-redeadline
10405 (not (equal old-date
10406 (substring org-last-inserted-timestamp 1 -1))))
10407 (org-add-log-setup 'redeadline nil old-date 'findpos
10408 org-log-redeadline))
10409 (message "Deadline on %s" org-last-inserted-timestamp)))))
10411 (defun org-schedule (&optional remove time)
10412 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10413 With argument REMOVE, remove any scheduling date from the item.
10414 When TIME is set, it should be an internal time specification, and the
10415 scheduling will use the corresponding date."
10416 (interactive "P")
10417 (let ((old-date (org-entry-get nil "SCHEDULED")))
10418 (if remove
10419 (progn
10420 (org-remove-timestamp-with-keyword org-scheduled-string)
10421 (message "Item is no longer scheduled."))
10422 (if (org-get-repeat)
10423 (error "Cannot reschedule task with repeater, please do that by hand")
10424 (org-add-planning-info 'scheduled time 'closed)
10425 (when (and old-date org-log-reschedule
10426 (not (equal old-date
10427 (substring org-last-inserted-timestamp 1 -1))))
10428 (org-add-log-setup 'reschedule nil old-date 'findpos
10429 org-log-reschedule))
10430 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10432 (defun org-get-scheduled-time (pom &optional inherit)
10433 "Get the scheduled time as a time tuple, of a format suitable
10434 for calling org-schedule with, or if there is no scheduling,
10435 returns nil."
10436 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10437 (when time
10438 (apply 'encode-time (org-parse-time-string time)))))
10440 (defun org-get-deadline-time (pom &optional inherit)
10441 "Get the deadine as a time tuple, of a format suitable for
10442 calling org-deadlin with, or if there is no scheduling, returns
10443 nil."
10444 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10445 (when time
10446 (apply 'encode-time (org-parse-time-string time)))))
10448 (defun org-remove-timestamp-with-keyword (keyword)
10449 "Remove all time stamps with KEYWORD in the current entry."
10450 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10451 beg)
10452 (save-excursion
10453 (org-back-to-heading t)
10454 (setq beg (point))
10455 (outline-next-heading)
10456 (while (re-search-backward re beg t)
10457 (replace-match "")
10458 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10459 (equal (char-before) ?\ ))
10460 (backward-delete-char 1)
10461 (if (string-match "^[ \t]*$" (buffer-substring
10462 (point-at-bol) (point-at-eol)))
10463 (delete-region (point-at-bol)
10464 (min (point-max) (1+ (point-at-eol))))))))))
10466 (defun org-add-planning-info (what &optional time &rest remove)
10467 "Insert new timestamp with keyword in the line directly after the headline.
10468 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10469 If non is given, the user is prompted for a date.
10470 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10471 be removed."
10472 (interactive)
10473 (let (org-time-was-given org-end-time-was-given ts
10474 end default-time default-input)
10476 (catch 'exit
10477 (when (and (not time) (memq what '(scheduled deadline)))
10478 ;; Try to get a default date/time from existing timestamp
10479 (save-excursion
10480 (org-back-to-heading t)
10481 (setq end (save-excursion (outline-next-heading) (point)))
10482 (when (re-search-forward (if (eq what 'scheduled)
10483 org-scheduled-time-regexp
10484 org-deadline-time-regexp)
10485 end t)
10486 (setq ts (match-string 1)
10487 default-time
10488 (apply 'encode-time (org-parse-time-string ts))
10489 default-input (and ts (org-get-compact-tod ts))))))
10490 (when what
10491 ;; If necessary, get the time from the user
10492 (setq time (or time (org-read-date nil 'to-time nil nil
10493 default-time default-input))))
10495 (when (and org-insert-labeled-timestamps-at-point
10496 (member what '(scheduled deadline)))
10497 (insert
10498 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10499 (org-insert-time-stamp time org-time-was-given
10500 nil nil nil (list org-end-time-was-given))
10501 (setq what nil))
10502 (save-excursion
10503 (save-restriction
10504 (let (col list elt ts buffer-invisibility-spec)
10505 (org-back-to-heading t)
10506 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10507 (goto-char (match-end 1))
10508 (setq col (current-column))
10509 (goto-char (match-end 0))
10510 (if (eobp) (insert "\n") (forward-char 1))
10511 (when (and (not what)
10512 (not (looking-at
10513 (concat "[ \t]*"
10514 org-keyword-time-not-clock-regexp))))
10515 ;; Nothing to add, nothing to remove...... :-)
10516 (throw 'exit nil))
10517 (if (and (not (looking-at outline-regexp))
10518 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10519 "[^\r\n]*"))
10520 (not (equal (match-string 1) org-clock-string)))
10521 (narrow-to-region (match-beginning 0) (match-end 0))
10522 (insert-before-markers "\n")
10523 (backward-char 1)
10524 (narrow-to-region (point) (point))
10525 (and org-adapt-indentation (org-indent-to-column col)))
10526 ;; Check if we have to remove something.
10527 (setq list (cons what remove))
10528 (while list
10529 (setq elt (pop list))
10530 (goto-char (point-min))
10531 (when (or (and (eq elt 'scheduled)
10532 (re-search-forward org-scheduled-time-regexp nil t))
10533 (and (eq elt 'deadline)
10534 (re-search-forward org-deadline-time-regexp nil t))
10535 (and (eq elt 'closed)
10536 (re-search-forward org-closed-time-regexp nil t)))
10537 (replace-match "")
10538 (if (looking-at "--+<[^>]+>") (replace-match ""))
10539 (skip-chars-backward " ")
10540 (if (looking-at " +") (replace-match ""))))
10541 (goto-char (point-max))
10542 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10543 (when what
10544 (insert
10545 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10546 (cond ((eq what 'scheduled) org-scheduled-string)
10547 ((eq what 'deadline) org-deadline-string)
10548 ((eq what 'closed) org-closed-string))
10549 " ")
10550 (setq ts (org-insert-time-stamp
10551 time
10552 (or org-time-was-given
10553 (and (eq what 'closed) org-log-done-with-time))
10554 (eq what 'closed)
10555 nil nil (list org-end-time-was-given)))
10556 (end-of-line 1))
10557 (goto-char (point-min))
10558 (widen)
10559 (if (and (looking-at "[ \t]+\n")
10560 (equal (char-before) ?\n))
10561 (delete-region (1- (point)) (point-at-eol)))
10562 ts))))))
10564 (defvar org-log-note-marker (make-marker))
10565 (defvar org-log-note-purpose nil)
10566 (defvar org-log-note-state nil)
10567 (defvar org-log-note-previous-state nil)
10568 (defvar org-log-note-how nil)
10569 (defvar org-log-note-extra nil)
10570 (defvar org-log-note-window-configuration nil)
10571 (defvar org-log-note-return-to (make-marker))
10572 (defvar org-log-post-message nil
10573 "Message to be displayed after a log note has been stored.
10574 The auto-repeater uses this.")
10576 (defun org-add-note ()
10577 "Add a note to the current entry.
10578 This is done in the same way as adding a state change note."
10579 (interactive)
10580 (org-add-log-setup 'note nil nil 'findpos nil))
10582 (defvar org-property-end-re)
10583 (defun org-add-log-setup (&optional purpose state prev-state
10584 findpos how &optional extra)
10585 "Set up the post command hook to take a note.
10586 If this is about to TODO state change, the new state is expected in STATE.
10587 When FINDPOS is non-nil, find the correct position for the note in
10588 the current entry. If not, assume that it can be inserted at point.
10589 HOW is an indicator what kind of note should be created.
10590 EXTRA is additional text that will be inserted into the notes buffer."
10591 (let* ((org-log-into-drawer (org-log-into-drawer))
10592 (drawer (cond ((stringp org-log-into-drawer)
10593 org-log-into-drawer)
10594 (org-log-into-drawer "LOGBOOK")
10595 (t nil))))
10596 (save-restriction
10597 (save-excursion
10598 (when findpos
10599 (org-back-to-heading t)
10600 (narrow-to-region (point) (save-excursion
10601 (outline-next-heading) (point)))
10602 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10603 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10604 "[^\r\n]*\\)?"))
10605 (goto-char (match-end 0))
10606 (cond
10607 (drawer
10608 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10609 nil t)
10610 (progn
10611 (goto-char (match-end 0))
10612 (or org-log-states-order-reversed
10613 (and (re-search-forward org-property-end-re nil t)
10614 (goto-char (1- (match-beginning 0))))))
10615 (insert "\n:" drawer ":\n:END:")
10616 (beginning-of-line 0)
10617 (org-indent-line-function)
10618 (beginning-of-line 2)
10619 (org-indent-line-function)
10620 (end-of-line 0)))
10621 ((and org-log-state-notes-insert-after-drawers
10622 (save-excursion
10623 (forward-line) (looking-at org-drawer-regexp)))
10624 (forward-line)
10625 (while (looking-at org-drawer-regexp)
10626 (goto-char (match-end 0))
10627 (re-search-forward org-property-end-re (point-max) t)
10628 (forward-line))
10629 (forward-line -1)))
10630 (unless org-log-states-order-reversed
10631 (and (= (char-after) ?\n) (forward-char 1))
10632 (org-skip-over-state-notes)
10633 (skip-chars-backward " \t\n\r")))
10634 (move-marker org-log-note-marker (point))
10635 (setq org-log-note-purpose purpose
10636 org-log-note-state state
10637 org-log-note-previous-state prev-state
10638 org-log-note-how how
10639 org-log-note-extra extra)
10640 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10642 (defun org-skip-over-state-notes ()
10643 "Skip past the list of State notes in an entry."
10644 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10645 (while (looking-at "[ \t]*- State")
10646 (condition-case nil
10647 (org-next-item)
10648 (error (org-end-of-item)))))
10650 (defun org-add-log-note (&optional purpose)
10651 "Pop up a window for taking a note, and add this note later at point."
10652 (remove-hook 'post-command-hook 'org-add-log-note)
10653 (setq org-log-note-window-configuration (current-window-configuration))
10654 (delete-other-windows)
10655 (move-marker org-log-note-return-to (point))
10656 (switch-to-buffer (marker-buffer org-log-note-marker))
10657 (goto-char org-log-note-marker)
10658 (org-switch-to-buffer-other-window "*Org Note*")
10659 (erase-buffer)
10660 (if (memq org-log-note-how '(time state))
10661 (let (current-prefix-arg) (org-store-log-note))
10662 (let ((org-inhibit-startup t)) (org-mode))
10663 (insert (format "# Insert note for %s.
10664 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10665 (cond
10666 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10667 ((eq org-log-note-purpose 'done) "closed todo item")
10668 ((eq org-log-note-purpose 'state)
10669 (format "state change from \"%s\" to \"%s\""
10670 (or org-log-note-previous-state "")
10671 (or org-log-note-state "")))
10672 ((eq org-log-note-purpose 'reschedule)
10673 "rescheduling")
10674 ((eq org-log-note-purpose 'redeadline)
10675 "changing deadline")
10676 ((eq org-log-note-purpose 'note)
10677 "this entry")
10678 (t (error "This should not happen")))))
10679 (if org-log-note-extra (insert org-log-note-extra))
10680 (org-set-local 'org-finish-function 'org-store-log-note)))
10682 (defvar org-note-abort nil) ; dynamically scoped
10683 (defun org-store-log-note ()
10684 "Finish taking a log note, and insert it to where it belongs."
10685 (let ((txt (buffer-string))
10686 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10687 lines ind)
10688 (kill-buffer (current-buffer))
10689 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10690 (setq txt (replace-match "" t t txt)))
10691 (if (string-match "\\s-+\\'" txt)
10692 (setq txt (replace-match "" t t txt)))
10693 (setq lines (org-split-string txt "\n"))
10694 (when (and note (string-match "\\S-" note))
10695 (setq note
10696 (org-replace-escapes
10697 note
10698 (list (cons "%u" (user-login-name))
10699 (cons "%U" user-full-name)
10700 (cons "%t" (format-time-string
10701 (org-time-stamp-format 'long 'inactive)
10702 (current-time)))
10703 (cons "%s" (if org-log-note-state
10704 (concat "\"" org-log-note-state "\"")
10705 ""))
10706 (cons "%S" (if org-log-note-previous-state
10707 (concat "\"" org-log-note-previous-state "\"")
10708 "\"\"")))))
10709 (if lines (setq note (concat note " \\\\")))
10710 (push note lines))
10711 (when (or current-prefix-arg org-note-abort)
10712 (when org-log-into-drawer
10713 (org-remove-empty-drawer-at
10714 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10715 org-log-note-marker))
10716 (setq lines nil))
10717 (when lines
10718 (with-current-buffer (marker-buffer org-log-note-marker)
10719 (save-excursion
10720 (goto-char org-log-note-marker)
10721 (move-marker org-log-note-marker nil)
10722 (end-of-line 1)
10723 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10724 (insert "- " (pop lines))
10725 (org-indent-line-function)
10726 (beginning-of-line 1)
10727 (looking-at "[ \t]*")
10728 (setq ind (concat (match-string 0) " "))
10729 (end-of-line 1)
10730 (while lines (insert "\n" ind (pop lines)))
10731 (message "Note stored")
10732 (org-back-to-heading t)
10733 (org-cycle-hide-drawers 'children)))))
10734 (set-window-configuration org-log-note-window-configuration)
10735 (with-current-buffer (marker-buffer org-log-note-return-to)
10736 (goto-char org-log-note-return-to))
10737 (move-marker org-log-note-return-to nil)
10738 (and org-log-post-message (message "%s" org-log-post-message)))
10740 (defun org-remove-empty-drawer-at (drawer pos)
10741 "Remove an emptyr DARWER drawer at position POS.
10742 POS may also be a marker."
10743 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10744 (save-excursion
10745 (save-restriction
10746 (widen)
10747 (goto-char pos)
10748 (if (org-in-regexp
10749 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10750 (replace-match ""))))))
10752 (defun org-sparse-tree (&optional arg)
10753 "Create a sparse tree, prompt for the details.
10754 This command can create sparse trees. You first need to select the type
10755 of match used to create the tree:
10757 t Show entries with a specific TODO keyword.
10758 m Show entries selected by a tags/property match.
10759 p Enter a property name and its value (both with completion on existing
10760 names/values) and show entries with that property.
10761 / Show entries matching a regular expression (`r' can be used as well)
10762 d Show deadlines due within `org-deadline-warning-days'.
10763 b Show deadlines and scheduled items before a date.
10764 a Show deadlines and scheduled items after a date."
10765 (interactive "P")
10766 (let (ans kwd value)
10767 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10768 (setq ans (read-char-exclusive))
10769 (cond
10770 ((equal ans ?d)
10771 (call-interactively 'org-check-deadlines))
10772 ((equal ans ?b)
10773 (call-interactively 'org-check-before-date))
10774 ((equal ans ?a)
10775 (call-interactively 'org-check-after-date))
10776 ((equal ans ?t)
10777 (org-show-todo-tree '(4)))
10778 ((member ans '(?T ?m))
10779 (call-interactively 'org-match-sparse-tree))
10780 ((member ans '(?p ?P))
10781 (setq kwd (org-icompleting-read "Property: "
10782 (mapcar 'list (org-buffer-property-keys))))
10783 (setq value (org-icompleting-read "Value: "
10784 (mapcar 'list (org-property-values kwd))))
10785 (unless (string-match "\\`{.*}\\'" value)
10786 (setq value (concat "\"" value "\"")))
10787 (org-match-sparse-tree arg (concat kwd "=" value)))
10788 ((member ans '(?r ?R ?/))
10789 (call-interactively 'org-occur))
10790 (t (error "No such sparse tree command \"%c\"" ans)))))
10792 (defvar org-occur-highlights nil
10793 "List of overlays used for occur matches.")
10794 (make-variable-buffer-local 'org-occur-highlights)
10795 (defvar org-occur-parameters nil
10796 "Parameters of the active org-occur calls.
10797 This is a list, each call to org-occur pushes as cons cell,
10798 containing the regular expression and the callback, onto the list.
10799 The list can contain several entries if `org-occur' has been called
10800 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10801 will only contain one set of parameters. When the highlights are
10802 removed (for example with `C-c C-c', or with the next edit (depending
10803 on `org-remove-highlights-with-change'), this variable is emptied
10804 as well.")
10805 (make-variable-buffer-local 'org-occur-parameters)
10807 (defun org-occur (regexp &optional keep-previous callback)
10808 "Make a compact tree which shows all matches of REGEXP.
10809 The tree will show the lines where the regexp matches, and all higher
10810 headlines above the match. It will also show the heading after the match,
10811 to make sure editing the matching entry is easy.
10812 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10813 call to `org-occur' will be kept, to allow stacking of calls to this
10814 command.
10815 If CALLBACK is non-nil, it is a function which is called to confirm
10816 that the match should indeed be shown."
10817 (interactive "sRegexp: \nP")
10818 (when (equal regexp "")
10819 (error "Regexp cannot be empty"))
10820 (unless keep-previous
10821 (org-remove-occur-highlights nil nil t))
10822 (push (cons regexp callback) org-occur-parameters)
10823 (let ((cnt 0))
10824 (save-excursion
10825 (goto-char (point-min))
10826 (if (or (not keep-previous) ; do not want to keep
10827 (not org-occur-highlights)) ; no previous matches
10828 ;; hide everything
10829 (org-overview))
10830 (while (re-search-forward regexp nil t)
10831 (when (or (not callback)
10832 (save-match-data (funcall callback)))
10833 (setq cnt (1+ cnt))
10834 (when org-highlight-sparse-tree-matches
10835 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10836 (org-show-context 'occur-tree))))
10837 (when org-remove-highlights-with-change
10838 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10839 nil 'local))
10840 (unless org-sparse-tree-open-archived-trees
10841 (org-hide-archived-subtrees (point-min) (point-max)))
10842 (run-hooks 'org-occur-hook)
10843 (if (interactive-p)
10844 (message "%d match(es) for regexp %s" cnt regexp))
10845 cnt))
10847 (defun org-show-context (&optional key)
10848 "Make sure point and context and visible.
10849 How much context is shown depends upon the variables
10850 `org-show-hierarchy-above', `org-show-following-heading'. and
10851 `org-show-siblings'."
10852 (let ((heading-p (org-on-heading-p t))
10853 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10854 (following-p (org-get-alist-option org-show-following-heading key))
10855 (entry-p (org-get-alist-option org-show-entry-below key))
10856 (siblings-p (org-get-alist-option org-show-siblings key)))
10857 (catch 'exit
10858 ;; Show heading or entry text
10859 (if (and heading-p (not entry-p))
10860 (org-flag-heading nil) ; only show the heading
10861 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10862 (org-show-hidden-entry))) ; show entire entry
10863 (when following-p
10864 ;; Show next sibling, or heading below text
10865 (save-excursion
10866 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10867 (org-flag-heading nil))))
10868 (when siblings-p (org-show-siblings))
10869 (when hierarchy-p
10870 ;; show all higher headings, possibly with siblings
10871 (save-excursion
10872 (while (and (condition-case nil
10873 (progn (org-up-heading-all 1) t)
10874 (error nil))
10875 (not (bobp)))
10876 (org-flag-heading nil)
10877 (when siblings-p (org-show-siblings))))))))
10879 (defun org-reveal (&optional siblings)
10880 "Show current entry, hierarchy above it, and the following headline.
10881 This can be used to show a consistent set of context around locations
10882 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10883 not t for the search context.
10885 With optional argument SIBLINGS, on each level of the hierarchy all
10886 siblings are shown. This repairs the tree structure to what it would
10887 look like when opened with hierarchical calls to `org-cycle'."
10888 (interactive "P")
10889 (let ((org-show-hierarchy-above t)
10890 (org-show-following-heading t)
10891 (org-show-siblings (if siblings t org-show-siblings)))
10892 (org-show-context nil)))
10894 (defun org-highlight-new-match (beg end)
10895 "Highlight from BEG to END and mark the highlight is an occur headline."
10896 (let ((ov (org-make-overlay beg end)))
10897 (org-overlay-put ov 'face 'secondary-selection)
10898 (push ov org-occur-highlights)))
10900 (defun org-remove-occur-highlights (&optional beg end noremove)
10901 "Remove the occur highlights from the buffer.
10902 BEG and END are ignored. If NOREMOVE is nil, remove this function
10903 from the `before-change-functions' in the current buffer."
10904 (interactive)
10905 (unless org-inhibit-highlight-removal
10906 (mapc 'org-delete-overlay org-occur-highlights)
10907 (setq org-occur-highlights nil)
10908 (setq org-occur-parameters nil)
10909 (unless noremove
10910 (remove-hook 'before-change-functions
10911 'org-remove-occur-highlights 'local))))
10913 ;;;; Priorities
10915 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10916 "Regular expression matching the priority indicator.")
10918 (defvar org-remove-priority-next-time nil)
10920 (defun org-priority-up ()
10921 "Increase the priority of the current item."
10922 (interactive)
10923 (org-priority 'up))
10925 (defun org-priority-down ()
10926 "Decrease the priority of the current item."
10927 (interactive)
10928 (org-priority 'down))
10930 (defun org-priority (&optional action)
10931 "Change the priority of an item by ARG.
10932 ACTION can be `set', `up', `down', or a character."
10933 (interactive)
10934 (unless org-enable-priority-commands
10935 (error "Priority commands are disabled"))
10936 (setq action (or action 'set))
10937 (let (current new news have remove)
10938 (save-excursion
10939 (org-back-to-heading t)
10940 (if (looking-at org-priority-regexp)
10941 (setq current (string-to-char (match-string 2))
10942 have t)
10943 (setq current org-default-priority))
10944 (cond
10945 ((eq action 'remove)
10946 (setq remove t new ?\ ))
10947 ((or (eq action 'set)
10948 (if (featurep 'xemacs) (characterp action) (integerp action)))
10949 (if (not (eq action 'set))
10950 (setq new action)
10951 (message "Priority %c-%c, SPC to remove: "
10952 org-highest-priority org-lowest-priority)
10953 (setq new (read-char-exclusive)))
10954 (if (and (= (upcase org-highest-priority) org-highest-priority)
10955 (= (upcase org-lowest-priority) org-lowest-priority))
10956 (setq new (upcase new)))
10957 (cond ((equal new ?\ ) (setq remove t))
10958 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10959 (error "Priority must be between `%c' and `%c'"
10960 org-highest-priority org-lowest-priority))))
10961 ((eq action 'up)
10962 (if (and (not have) (eq last-command this-command))
10963 (setq new org-lowest-priority)
10964 (setq new (if (and org-priority-start-cycle-with-default (not have))
10965 org-default-priority (1- current)))))
10966 ((eq action 'down)
10967 (if (and (not have) (eq last-command this-command))
10968 (setq new org-highest-priority)
10969 (setq new (if (and org-priority-start-cycle-with-default (not have))
10970 org-default-priority (1+ current)))))
10971 (t (error "Invalid action")))
10972 (if (or (< (upcase new) org-highest-priority)
10973 (> (upcase new) org-lowest-priority))
10974 (setq remove t))
10975 (setq news (format "%c" new))
10976 (if have
10977 (if remove
10978 (replace-match "" t t nil 1)
10979 (replace-match news t t nil 2))
10980 (if remove
10981 (error "No priority cookie found in line")
10982 (let ((case-fold-search nil))
10983 (looking-at org-todo-line-regexp))
10984 (if (match-end 2)
10985 (progn
10986 (goto-char (match-end 2))
10987 (insert " [#" news "]"))
10988 (goto-char (match-beginning 3))
10989 (insert "[#" news "] "))))
10990 (org-preserve-lc (org-set-tags nil 'align)))
10991 (if remove
10992 (message "Priority removed")
10993 (message "Priority of current item set to %s" news))))
10995 (defun org-get-priority (s)
10996 "Find priority cookie and return priority."
10997 (save-match-data
10998 (if (not (string-match org-priority-regexp s))
10999 (* 1000 (- org-lowest-priority org-default-priority))
11000 (* 1000 (- org-lowest-priority
11001 (string-to-char (match-string 2 s)))))))
11003 ;;;; Tags
11005 (defvar org-agenda-archives-mode)
11006 (defvar org-map-continue-from nil
11007 "Position from where mapping should continue.
11008 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
11010 (defvar org-scanner-tags nil
11011 "The current tag list while the tags scanner is running.")
11012 (defvar org-trust-scanner-tags nil
11013 "Should `org-get-tags-at' use the tags fro the scanner.
11014 This is for internal dynamical scoping only.
11015 When this is non-nil, the function `org-get-tags-at' will return the value
11016 of `org-scanner-tags' instead of building the list by itself. This
11017 can lead to large speed-ups when the tags scanner is used in a file with
11018 many entries, and when the list of tags is retrieved, for example to
11019 obtain a list of properties. Building the tags list for each entry in such
11020 a file becomes an N^2 operation - but with this variable set, it scales
11021 as N.")
11023 (defun org-scan-tags (action matcher &optional todo-only)
11024 "Scan headline tags with inheritance and produce output ACTION.
11026 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11027 or `agenda' to produce an entry list for an agenda view. It can also be
11028 a Lisp form or a function that should be called at each matched headline, in
11029 this case the return value is a list of all return values from these calls.
11031 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11032 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11033 only lines with a TODO keyword are included in the output."
11034 (require 'org-agenda)
11035 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11036 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11037 (org-re
11038 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11039 (props (list 'face 'default
11040 'done-face 'org-agenda-done
11041 'undone-face 'default
11042 'mouse-face 'highlight
11043 'org-not-done-regexp org-not-done-regexp
11044 'org-todo-regexp org-todo-regexp
11045 'help-echo
11046 (format "mouse-2 or RET jump to org file %s"
11047 (abbreviate-file-name
11048 (or (buffer-file-name (buffer-base-buffer))
11049 (buffer-name (buffer-base-buffer)))))))
11050 (case-fold-search nil)
11051 (org-map-continue-from nil)
11052 lspos tags tags-list
11053 (tags-alist (list (cons 0 org-file-tags)))
11054 (llast 0) rtn rtn1 level category i txt
11055 todo marker entry priority)
11056 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11057 (setq action (list 'lambda nil action)))
11058 (save-excursion
11059 (goto-char (point-min))
11060 (when (eq action 'sparse-tree)
11061 (org-overview)
11062 (org-remove-occur-highlights))
11063 (while (re-search-forward re nil t)
11064 (catch :skip
11065 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11066 tags (if (match-end 4) (org-match-string-no-properties 4)))
11067 (goto-char (setq lspos (match-beginning 0)))
11068 (setq level (org-reduced-level (funcall outline-level))
11069 category (org-get-category))
11070 (setq i llast llast level)
11071 ;; remove tag lists from same and sublevels
11072 (while (>= i level)
11073 (when (setq entry (assoc i tags-alist))
11074 (setq tags-alist (delete entry tags-alist)))
11075 (setq i (1- i)))
11076 ;; add the next tags
11077 (when tags
11078 (setq tags (org-split-string tags ":")
11079 tags-alist
11080 (cons (cons level tags) tags-alist)))
11081 ;; compile tags for current headline
11082 (setq tags-list
11083 (if org-use-tag-inheritance
11084 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11085 tags)
11086 org-scanner-tags tags-list)
11087 (when org-use-tag-inheritance
11088 (setcdr (car tags-alist)
11089 (mapcar (lambda (x)
11090 (setq x (copy-sequence x))
11091 (org-add-prop-inherited x))
11092 (cdar tags-alist))))
11093 (when (and tags org-use-tag-inheritance
11094 (or (not (eq t org-use-tag-inheritance))
11095 org-tags-exclude-from-inheritance))
11096 ;; selective inheritance, remove uninherited ones
11097 (setcdr (car tags-alist)
11098 (org-remove-uniherited-tags (cdar tags-alist))))
11099 (when (and (or (not todo-only)
11100 (and (member todo org-not-done-keywords)
11101 (or (not org-agenda-tags-todo-honor-ignore-options)
11102 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11103 (let ((case-fold-search t)) (eval matcher))
11105 (not (member org-archive-tag tags-list))
11106 ;; we have an archive tag, should we use this anyway?
11107 (or (not org-agenda-skip-archived-trees)
11108 (and (eq action 'agenda) org-agenda-archives-mode))))
11109 (unless (eq action 'sparse-tree) (org-agenda-skip))
11111 ;; select this headline
11113 (cond
11114 ((eq action 'sparse-tree)
11115 (and org-highlight-sparse-tree-matches
11116 (org-get-heading) (match-end 0)
11117 (org-highlight-new-match
11118 (match-beginning 0) (match-beginning 1)))
11119 (org-show-context 'tags-tree))
11120 ((eq action 'agenda)
11121 (setq txt (org-format-agenda-item
11123 (concat
11124 (if (eq org-tags-match-list-sublevels 'indented)
11125 (make-string (1- level) ?.) "")
11126 (org-get-heading))
11127 category
11128 tags-list
11130 priority (org-get-priority txt))
11131 (goto-char lspos)
11132 (setq marker (org-agenda-new-marker))
11133 (org-add-props txt props
11134 'org-marker marker 'org-hd-marker marker 'org-category category
11135 'todo-state todo
11136 'priority priority 'type "tagsmatch")
11137 (push txt rtn))
11138 ((functionp action)
11139 (setq org-map-continue-from nil)
11140 (save-excursion
11141 (setq rtn1 (funcall action))
11142 (push rtn1 rtn)))
11143 (t (error "Invalid action")))
11145 ;; if we are to skip sublevels, jump to end of subtree
11146 (unless org-tags-match-list-sublevels
11147 (org-end-of-subtree t)
11148 (backward-char 1))))
11149 ;; Get the correct position from where to continue
11150 (if org-map-continue-from
11151 (goto-char org-map-continue-from)
11152 (and (= (point) lspos) (end-of-line 1)))))
11153 (when (and (eq action 'sparse-tree)
11154 (not org-sparse-tree-open-archived-trees))
11155 (org-hide-archived-subtrees (point-min) (point-max)))
11156 (nreverse rtn)))
11158 (defun org-remove-uniherited-tags (tags)
11159 "Remove all tags that are not inherited from the list TAGS."
11160 (cond
11161 ((eq org-use-tag-inheritance t)
11162 (if org-tags-exclude-from-inheritance
11163 (org-delete-all org-tags-exclude-from-inheritance tags)
11164 tags))
11165 ((not org-use-tag-inheritance) nil)
11166 ((stringp org-use-tag-inheritance)
11167 (delq nil (mapcar
11168 (lambda (x)
11169 (if (and (string-match org-use-tag-inheritance x)
11170 (not (member x org-tags-exclude-from-inheritance)))
11171 x nil))
11172 tags)))
11173 ((listp org-use-tag-inheritance)
11174 (delq nil (mapcar
11175 (lambda (x)
11176 (if (member x org-use-tag-inheritance) x nil))
11177 tags)))))
11179 (defvar todo-only) ;; dynamically scoped
11181 (defun org-match-sparse-tree (&optional todo-only match)
11182 "Create a sparse tree according to tags string MATCH.
11183 MATCH can contain positive and negative selection of tags, like
11184 \"+WORK+URGENT-WITHBOSS\".
11185 If optional argument TODO-ONLY is non-nil, only select lines that are
11186 also TODO lines."
11187 (interactive "P")
11188 (org-prepare-agenda-buffers (list (current-buffer)))
11189 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11191 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11193 (defvar org-cached-props nil)
11194 (defun org-cached-entry-get (pom property)
11195 (if (or (eq t org-use-property-inheritance)
11196 (and (stringp org-use-property-inheritance)
11197 (string-match org-use-property-inheritance property))
11198 (and (listp org-use-property-inheritance)
11199 (member property org-use-property-inheritance)))
11200 ;; Caching is not possible, check it directly
11201 (org-entry-get pom property 'inherit)
11202 ;; Get all properties, so that we can do complicated checks easily
11203 (cdr (assoc property (or org-cached-props
11204 (setq org-cached-props
11205 (org-entry-properties pom)))))))
11207 (defun org-global-tags-completion-table (&optional files)
11208 "Return the list of all tags in all agenda buffer/files."
11209 (save-excursion
11210 (org-uniquify
11211 (delq nil
11212 (apply 'append
11213 (mapcar
11214 (lambda (file)
11215 (set-buffer (find-file-noselect file))
11216 (append (org-get-buffer-tags)
11217 (mapcar (lambda (x) (if (stringp (car-safe x))
11218 (list (car-safe x)) nil))
11219 org-tag-alist)))
11220 (if (and files (car files))
11221 files
11222 (org-agenda-files))))))))
11224 (defun org-make-tags-matcher (match)
11225 "Create the TAGS//TODO matcher form for the selection string MATCH."
11226 ;; todo-only is scoped dynamically into this function, and the function
11227 ;; may change it if the matcher asks for it.
11228 (unless match
11229 ;; Get a new match request, with completion
11230 (let ((org-last-tags-completion-table
11231 (org-global-tags-completion-table)))
11232 (setq match (org-completing-read-no-i
11233 "Match: " 'org-tags-completion-function nil nil nil
11234 'org-tags-history))))
11236 ;; Parse the string and create a lisp form
11237 (let ((match0 match)
11238 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11239 minus tag mm
11240 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11241 orterms term orlist re-p str-p level-p level-op time-p
11242 prop-p pn pv po cat-p gv rest)
11243 (if (string-match "/+" match)
11244 ;; match contains also a todo-matching request
11245 (progn
11246 (setq tagsmatch (substring match 0 (match-beginning 0))
11247 todomatch (substring match (match-end 0)))
11248 (if (string-match "^!" todomatch)
11249 (setq todo-only t todomatch (substring todomatch 1)))
11250 (if (string-match "^\\s-*$" todomatch)
11251 (setq todomatch nil)))
11252 ;; only matching tags
11253 (setq tagsmatch match todomatch nil))
11255 ;; Make the tags matcher
11256 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11257 (setq tagsmatcher t)
11258 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11259 (while (setq term (pop orterms))
11260 (while (and (equal (substring term -1) "\\") orterms)
11261 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11262 (while (string-match re term)
11263 (setq rest (substring term (match-end 0))
11264 minus (and (match-end 1)
11265 (equal (match-string 1 term) "-"))
11266 tag (match-string 2 term)
11267 re-p (equal (string-to-char tag) ?{)
11268 level-p (match-end 4)
11269 prop-p (match-end 5)
11270 mm (cond
11271 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11272 (level-p
11273 (setq level-op (org-op-to-function (match-string 3 term)))
11274 `(,level-op level ,(string-to-number
11275 (match-string 4 term))))
11276 (prop-p
11277 (setq pn (match-string 5 term)
11278 po (match-string 6 term)
11279 pv (match-string 7 term)
11280 cat-p (equal pn "CATEGORY")
11281 re-p (equal (string-to-char pv) ?{)
11282 str-p (equal (string-to-char pv) ?\")
11283 time-p (save-match-data
11284 (string-match "^\"[[<].*[]>]\"$" pv))
11285 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11286 (if time-p (setq pv (org-matcher-time pv)))
11287 (setq po (org-op-to-function po (if time-p 'time str-p)))
11288 (cond
11289 ((equal pn "CATEGORY")
11290 (setq gv '(get-text-property (point) 'org-category)))
11291 ((equal pn "TODO")
11292 (setq gv 'todo))
11294 (setq gv `(org-cached-entry-get nil ,pn))))
11295 (if re-p
11296 (if (eq po 'org<>)
11297 `(not (string-match ,pv (or ,gv "")))
11298 `(string-match ,pv (or ,gv "")))
11299 (if str-p
11300 `(,po (or ,gv "") ,pv)
11301 `(,po (string-to-number (or ,gv ""))
11302 ,(string-to-number pv) ))))
11303 (t `(member ,tag tags-list)))
11304 mm (if minus (list 'not mm) mm)
11305 term rest)
11306 (push mm tagsmatcher))
11307 (push (if (> (length tagsmatcher) 1)
11308 (cons 'and tagsmatcher)
11309 (car tagsmatcher))
11310 orlist)
11311 (setq tagsmatcher nil))
11312 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11313 (setq tagsmatcher
11314 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11315 ;; Make the todo matcher
11316 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11317 (setq todomatcher t)
11318 (setq orterms (org-split-string todomatch "|") orlist nil)
11319 (while (setq term (pop orterms))
11320 (while (string-match re term)
11321 (setq minus (and (match-end 1)
11322 (equal (match-string 1 term) "-"))
11323 kwd (match-string 2 term)
11324 re-p (equal (string-to-char kwd) ?{)
11325 term (substring term (match-end 0))
11326 mm (if re-p
11327 `(string-match ,(substring kwd 1 -1) todo)
11328 (list 'equal 'todo kwd))
11329 mm (if minus (list 'not mm) mm))
11330 (push mm todomatcher))
11331 (push (if (> (length todomatcher) 1)
11332 (cons 'and todomatcher)
11333 (car todomatcher))
11334 orlist)
11335 (setq todomatcher nil))
11336 (setq todomatcher (if (> (length orlist) 1)
11337 (cons 'or orlist) (car orlist))))
11339 ;; Return the string and lisp forms of the matcher
11340 (setq matcher (if todomatcher
11341 (list 'and tagsmatcher todomatcher)
11342 tagsmatcher))
11343 (cons match0 matcher)))
11345 (defun org-op-to-function (op &optional stringp)
11346 "Turn an operator into the appropriate function."
11347 (setq op
11348 (cond
11349 ((equal op "<" ) '(< string< org-time<))
11350 ((equal op ">" ) '(> org-string> org-time>))
11351 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11352 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11353 ((member op '("=" "==")) '(= string= org-time=))
11354 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11355 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11357 (defun org<> (a b) (not (= a b)))
11358 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11359 (defun org-string>= (a b) (not (string< a b)))
11360 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11361 (defun org-string<> (a b) (not (string= a b)))
11362 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11363 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11364 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11365 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11366 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11367 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11368 (defun org-2ft (s)
11369 "Convert S to a floating point time.
11370 If S is already a number, just return it. If it is a string, parse
11371 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11372 (cond
11373 ((numberp s) s)
11374 ((stringp s)
11375 (condition-case nil
11376 (float-time (apply 'encode-time (org-parse-time-string s)))
11377 (error 0.)))
11378 (t 0.)))
11380 (defun org-time-today ()
11381 "Time in seconds today at 0:00.
11382 Returns the float number of seconds since the beginning of the
11383 epoch to the beginning of today (00:00)."
11384 (float-time (apply 'encode-time
11385 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11387 (defun org-matcher-time (s)
11388 "Interpret a time comparison value."
11389 (save-match-data
11390 (cond
11391 ((string= s "<now>") (float-time))
11392 ((string= s "<today>") (org-time-today))
11393 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11394 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11395 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11396 (+ (org-time-today)
11397 (* (string-to-number (match-string 1 s))
11398 (cdr (assoc (match-string 2 s)
11399 '(("d" . 86400.0) ("w" . 604800.0)
11400 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11401 (t (org-2ft s)))))
11403 (defun org-match-any-p (re list)
11404 "Does re match any element of list?"
11405 (setq list (mapcar (lambda (x) (string-match re x)) list))
11406 (delq nil list))
11408 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11409 (defvar org-tags-overlay (org-make-overlay 1 1))
11410 (org-detach-overlay org-tags-overlay)
11412 (defun org-get-local-tags-at (&optional pos)
11413 "Get a list of tags defined in the current headline."
11414 (org-get-tags-at pos 'local))
11416 (defun org-get-local-tags ()
11417 "Get a list of tags defined in the current headline."
11418 (org-get-tags-at nil 'local))
11420 (defun org-get-tags-at (&optional pos local)
11421 "Get a list of all headline tags applicable at POS.
11422 POS defaults to point. If tags are inherited, the list contains
11423 the targets in the same sequence as the headlines appear, i.e.
11424 the tags of the current headline come last.
11425 When LOCAL is non-nil, only return tags from the current headline,
11426 ignore inherited ones."
11427 (interactive)
11428 (if (and org-trust-scanner-tags
11429 (or (not pos) (equal pos (point)))
11430 (not local))
11431 org-scanner-tags
11432 (let (tags ltags lastpos parent)
11433 (save-excursion
11434 (save-restriction
11435 (widen)
11436 (goto-char (or pos (point)))
11437 (save-match-data
11438 (catch 'done
11439 (condition-case nil
11440 (progn
11441 (org-back-to-heading t)
11442 (while (not (equal lastpos (point)))
11443 (setq lastpos (point))
11444 (when (looking-at
11445 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11446 (setq ltags (org-split-string
11447 (org-match-string-no-properties 1) ":"))
11448 (when parent
11449 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11450 (setq tags (append
11451 (if parent
11452 (org-remove-uniherited-tags ltags)
11453 ltags)
11454 tags)))
11455 (or org-use-tag-inheritance (throw 'done t))
11456 (if local (throw 'done t))
11457 (or (org-up-heading-safe) (error nil))
11458 (setq parent t)))
11459 (error nil)))))
11460 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11462 (defun org-add-prop-inherited (s)
11463 (add-text-properties 0 (length s) '(inherited t) s)
11466 (defun org-toggle-tag (tag &optional onoff)
11467 "Toggle the tag TAG for the current line.
11468 If ONOFF is `on' or `off', don't toggle but set to this state."
11469 (let (res current)
11470 (save-excursion
11471 (org-back-to-heading t)
11472 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11473 (point-at-eol) t)
11474 (progn
11475 (setq current (match-string 1))
11476 (replace-match ""))
11477 (setq current ""))
11478 (setq current (nreverse (org-split-string current ":")))
11479 (cond
11480 ((eq onoff 'on)
11481 (setq res t)
11482 (or (member tag current) (push tag current)))
11483 ((eq onoff 'off)
11484 (or (not (member tag current)) (setq current (delete tag current))))
11485 (t (if (member tag current)
11486 (setq current (delete tag current))
11487 (setq res t)
11488 (push tag current))))
11489 (end-of-line 1)
11490 (if current
11491 (progn
11492 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11493 (org-set-tags nil t))
11494 (delete-horizontal-space))
11495 (run-hooks 'org-after-tags-change-hook))
11496 res))
11498 (defun org-align-tags-here (to-col)
11499 ;; Assumes that this is a headline
11500 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11501 (beginning-of-line 1)
11502 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11503 (< pos (match-beginning 2)))
11504 (progn
11505 (setq tags-l (- (match-end 2) (match-beginning 2)))
11506 (goto-char (match-beginning 1))
11507 (insert " ")
11508 (delete-region (point) (1+ (match-beginning 2)))
11509 (setq ncol (max (1+ (current-column))
11510 (1+ col)
11511 (if (> to-col 0)
11512 to-col
11513 (- (abs to-col) tags-l))))
11514 (setq p (point))
11515 (insert (make-string (- ncol (current-column)) ?\ ))
11516 (setq ncol (current-column))
11517 (when indent-tabs-mode (tabify p (point-at-eol)))
11518 (org-move-to-column (min ncol col) t))
11519 (goto-char pos))))
11521 (defun org-set-tags-command (&optional arg just-align)
11522 "Call the set-tags command for the current entry."
11523 (interactive "P")
11524 (if (org-on-heading-p)
11525 (org-set-tags arg just-align)
11526 (save-excursion
11527 (org-back-to-heading t)
11528 (org-set-tags arg just-align))))
11530 (defun org-set-tags-to (data)
11531 "Set the tags of the current entry to DATA, replacing the current tags.
11532 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11533 If DATA is nil or the empty string, any tags will be removed."
11534 (interactive "sTags: ")
11535 (setq data
11536 (cond
11537 ((eq data nil) "")
11538 ((equal data "") "")
11539 ((stringp data)
11540 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11541 ":"))
11542 ((listp data)
11543 (concat ":" (mapconcat 'identity data ":") ":"))
11544 (t nil)))
11545 (when data
11546 (save-excursion
11547 (org-back-to-heading t)
11548 (when (looking-at org-complex-heading-regexp)
11549 (if (match-end 5)
11550 (progn
11551 (goto-char (match-beginning 5))
11552 (insert data)
11553 (delete-region (point) (point-at-eol))
11554 (org-set-tags nil 'align))
11555 (goto-char (point-at-eol))
11556 (insert " " data)
11557 (org-set-tags nil 'align)))
11558 (beginning-of-line 1)
11559 (if (looking-at ".*?\\([ \t]+\\)$")
11560 (delete-region (match-beginning 1) (match-end 1))))))
11562 (defun org-set-tags (&optional arg just-align)
11563 "Set the tags for the current headline.
11564 With prefix ARG, realign all tags in headings in the current buffer."
11565 (interactive "P")
11566 (let* ((re (concat "^" outline-regexp))
11567 (current (org-get-tags-string))
11568 (col (current-column))
11569 (org-setting-tags t)
11570 table current-tags inherited-tags ; computed below when needed
11571 tags p0 c0 c1 rpl)
11572 (if arg
11573 (save-excursion
11574 (goto-char (point-min))
11575 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11576 (while (re-search-forward re nil t)
11577 (org-set-tags nil t)
11578 (end-of-line 1)))
11579 (message "All tags realigned to column %d" org-tags-column))
11580 (if just-align
11581 (setq tags current)
11582 ;; Get a new set of tags from the user
11583 (save-excursion
11584 (setq table (append org-tag-persistent-alist
11585 (or org-tag-alist (org-get-buffer-tags)))
11586 org-last-tags-completion-table table
11587 current-tags (org-split-string current ":")
11588 inherited-tags (nreverse
11589 (nthcdr (length current-tags)
11590 (nreverse (org-get-tags-at))))
11591 tags
11592 (if (or (eq t org-use-fast-tag-selection)
11593 (and org-use-fast-tag-selection
11594 (delq nil (mapcar 'cdr table))))
11595 (org-fast-tag-selection
11596 current-tags inherited-tags table
11597 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11598 (let ((org-add-colon-after-tag-completion t))
11599 (org-trim
11600 (org-without-partial-completion
11601 (org-icompleting-read "Tags: " 'org-tags-completion-function
11602 nil nil current 'org-tags-history)))))))
11603 (while (string-match "[-+&]+" tags)
11604 ;; No boolean logic, just a list
11605 (setq tags (replace-match ":" t t tags))))
11607 (if org-tags-sort-function
11608 (setq tags (mapconcat 'identity
11609 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11610 org-tags-sort-function) ":")))
11612 (if (string-match "\\`[\t ]*\\'" tags)
11613 (setq tags "")
11614 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11615 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11617 ;; Insert new tags at the correct column
11618 (beginning-of-line 1)
11619 (cond
11620 ((and (equal current "") (equal tags "")))
11621 ((re-search-forward
11622 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11623 (point-at-eol) t)
11624 (if (equal tags "")
11625 (setq rpl "")
11626 (goto-char (match-beginning 0))
11627 (setq c0 (current-column) p0 (point)
11628 c1 (max (1+ c0) (if (> org-tags-column 0)
11629 org-tags-column
11630 (- (- org-tags-column) (length tags))))
11631 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11632 (replace-match rpl t t)
11633 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11634 tags)
11635 (t (error "Tags alignment failed")))
11636 (org-move-to-column col)
11637 (unless just-align
11638 (run-hooks 'org-after-tags-change-hook)))))
11640 (defun org-change-tag-in-region (beg end tag off)
11641 "Add or remove TAG for each entry in the region.
11642 This works in the agenda, and also in an org-mode buffer."
11643 (interactive
11644 (list (region-beginning) (region-end)
11645 (let ((org-last-tags-completion-table
11646 (if (org-mode-p)
11647 (org-get-buffer-tags)
11648 (org-global-tags-completion-table))))
11649 (org-icompleting-read
11650 "Tag: " 'org-tags-completion-function nil nil nil
11651 'org-tags-history))
11652 (progn
11653 (message "[s]et or [r]emove? ")
11654 (equal (read-char-exclusive) ?r))))
11655 (if (fboundp 'deactivate-mark) (deactivate-mark))
11656 (let ((agendap (equal major-mode 'org-agenda-mode))
11657 l1 l2 m buf pos newhead (cnt 0))
11658 (goto-char end)
11659 (setq l2 (1- (org-current-line)))
11660 (goto-char beg)
11661 (setq l1 (org-current-line))
11662 (loop for l from l1 to l2 do
11663 (org-goto-line l)
11664 (setq m (get-text-property (point) 'org-hd-marker))
11665 (when (or (and (org-mode-p) (org-on-heading-p))
11666 (and agendap m))
11667 (setq buf (if agendap (marker-buffer m) (current-buffer))
11668 pos (if agendap m (point)))
11669 (with-current-buffer buf
11670 (save-excursion
11671 (save-restriction
11672 (goto-char pos)
11673 (setq cnt (1+ cnt))
11674 (org-toggle-tag tag (if off 'off 'on))
11675 (setq newhead (org-get-heading)))))
11676 (and agendap (org-agenda-change-all-lines newhead m))))
11677 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11679 (defun org-tags-completion-function (string predicate &optional flag)
11680 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11681 (confirm (lambda (x) (stringp (car x)))))
11682 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11683 (setq s1 (match-string 1 string)
11684 s2 (match-string 2 string))
11685 (setq s1 "" s2 string))
11686 (cond
11687 ((eq flag nil)
11688 ;; try completion
11689 (setq rtn (try-completion s2 ctable confirm))
11690 (if (stringp rtn)
11691 (setq rtn
11692 (concat s1 s2 (substring rtn (length s2))
11693 (if (and org-add-colon-after-tag-completion
11694 (assoc rtn ctable))
11695 ":" ""))))
11696 rtn)
11697 ((eq flag t)
11698 ;; all-completions
11699 (all-completions s2 ctable confirm)
11701 ((eq flag 'lambda)
11702 ;; exact match?
11703 (assoc s2 ctable)))
11706 (defun org-fast-tag-insert (kwd tags face &optional end)
11707 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11708 (insert (format "%-12s" (concat kwd ":"))
11709 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11710 (or end "")))
11712 (defun org-fast-tag-show-exit (flag)
11713 (save-excursion
11714 (org-goto-line 3)
11715 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11716 (replace-match ""))
11717 (when flag
11718 (end-of-line 1)
11719 (org-move-to-column (- (window-width) 19) t)
11720 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11722 (defun org-set-current-tags-overlay (current prefix)
11723 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11724 (if (featurep 'xemacs)
11725 (org-overlay-display org-tags-overlay (concat prefix s)
11726 'secondary-selection)
11727 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11728 (org-overlay-display org-tags-overlay (concat prefix s)))))
11730 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11731 "Fast tag selection with single keys.
11732 CURRENT is the current list of tags in the headline, INHERITED is the
11733 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11734 possibly with grouping information. TODO-TABLE is a similar table with
11735 TODO keywords, should these have keys assigned to them.
11736 If the keys are nil, a-z are automatically assigned.
11737 Returns the new tags string, or nil to not change the current settings."
11738 (let* ((fulltable (append table todo-table))
11739 (maxlen (apply 'max (mapcar
11740 (lambda (x)
11741 (if (stringp (car x)) (string-width (car x)) 0))
11742 fulltable)))
11743 (buf (current-buffer))
11744 (expert (eq org-fast-tag-selection-single-key 'expert))
11745 (buffer-tags nil)
11746 (fwidth (+ maxlen 3 1 3))
11747 (ncol (/ (- (window-width) 4) fwidth))
11748 (i-face 'org-done)
11749 (c-face 'org-todo)
11750 tg cnt e c char c1 c2 ntable tbl rtn
11751 ov-start ov-end ov-prefix
11752 (exit-after-next org-fast-tag-selection-single-key)
11753 (done-keywords org-done-keywords)
11754 groups ingroup)
11755 (save-excursion
11756 (beginning-of-line 1)
11757 (if (looking-at
11758 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11759 (setq ov-start (match-beginning 1)
11760 ov-end (match-end 1)
11761 ov-prefix "")
11762 (setq ov-start (1- (point-at-eol))
11763 ov-end (1+ ov-start))
11764 (skip-chars-forward "^\n\r")
11765 (setq ov-prefix
11766 (concat
11767 (buffer-substring (1- (point)) (point))
11768 (if (> (current-column) org-tags-column)
11770 (make-string (- org-tags-column (current-column)) ?\ ))))))
11771 (org-move-overlay org-tags-overlay ov-start ov-end)
11772 (save-window-excursion
11773 (if expert
11774 (set-buffer (get-buffer-create " *Org tags*"))
11775 (delete-other-windows)
11776 (split-window-vertically)
11777 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11778 (erase-buffer)
11779 (org-set-local 'org-done-keywords done-keywords)
11780 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11781 (org-fast-tag-insert "Current" current c-face "\n\n")
11782 (org-fast-tag-show-exit exit-after-next)
11783 (org-set-current-tags-overlay current ov-prefix)
11784 (setq tbl fulltable char ?a cnt 0)
11785 (while (setq e (pop tbl))
11786 (cond
11787 ((equal (car e) :startgroup)
11788 (push '() groups) (setq ingroup t)
11789 (when (not (= cnt 0))
11790 (setq cnt 0)
11791 (insert "\n"))
11792 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11793 ((equal (car e) :endgroup)
11794 (setq ingroup nil cnt 0)
11795 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11796 ((equal e '(:newline))
11797 (when (not (= cnt 0))
11798 (setq cnt 0)
11799 (insert "\n")
11800 (setq e (car tbl))
11801 (while (equal (car tbl) '(:newline))
11802 (insert "\n")
11803 (setq tbl (cdr tbl)))))
11805 (setq tg (copy-sequence (car e)) c2 nil)
11806 (if (cdr e)
11807 (setq c (cdr e))
11808 ;; automatically assign a character.
11809 (setq c1 (string-to-char
11810 (downcase (substring
11811 tg (if (= (string-to-char tg) ?@) 1 0)))))
11812 (if (or (rassoc c1 ntable) (rassoc c1 table))
11813 (while (or (rassoc char ntable) (rassoc char table))
11814 (setq char (1+ char)))
11815 (setq c2 c1))
11816 (setq c (or c2 char)))
11817 (if ingroup (push tg (car groups)))
11818 (setq tg (org-add-props tg nil 'face
11819 (cond
11820 ((not (assoc tg table))
11821 (org-get-todo-face tg))
11822 ((member tg current) c-face)
11823 ((member tg inherited) i-face)
11824 (t nil))))
11825 (if (and (= cnt 0) (not ingroup)) (insert " "))
11826 (insert "[" c "] " tg (make-string
11827 (- fwidth 4 (length tg)) ?\ ))
11828 (push (cons tg c) ntable)
11829 (when (= (setq cnt (1+ cnt)) ncol)
11830 (insert "\n")
11831 (if ingroup (insert " "))
11832 (setq cnt 0)))))
11833 (setq ntable (nreverse ntable))
11834 (insert "\n")
11835 (goto-char (point-min))
11836 (if (not expert) (org-fit-window-to-buffer))
11837 (setq rtn
11838 (catch 'exit
11839 (while t
11840 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11841 (if (not groups) "no " "")
11842 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11843 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11844 (cond
11845 ((= c ?\r) (throw 'exit t))
11846 ((= c ?!)
11847 (setq groups (not groups))
11848 (goto-char (point-min))
11849 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11850 ((= c ?\C-c)
11851 (if (not expert)
11852 (org-fast-tag-show-exit
11853 (setq exit-after-next (not exit-after-next)))
11854 (setq expert nil)
11855 (delete-other-windows)
11856 (split-window-vertically)
11857 (org-switch-to-buffer-other-window " *Org tags*")
11858 (org-fit-window-to-buffer)))
11859 ((or (= c ?\C-g)
11860 (and (= c ?q) (not (rassoc c ntable))))
11861 (org-detach-overlay org-tags-overlay)
11862 (setq quit-flag t))
11863 ((= c ?\ )
11864 (setq current nil)
11865 (if exit-after-next (setq exit-after-next 'now)))
11866 ((= c ?\t)
11867 (condition-case nil
11868 (setq tg (org-icompleting-read
11869 "Tag: "
11870 (or buffer-tags
11871 (with-current-buffer buf
11872 (org-get-buffer-tags)))))
11873 (quit (setq tg "")))
11874 (when (string-match "\\S-" tg)
11875 (add-to-list 'buffer-tags (list tg))
11876 (if (member tg current)
11877 (setq current (delete tg current))
11878 (push tg current)))
11879 (if exit-after-next (setq exit-after-next 'now)))
11880 ((setq e (rassoc c todo-table) tg (car e))
11881 (with-current-buffer buf
11882 (save-excursion (org-todo tg)))
11883 (if exit-after-next (setq exit-after-next 'now)))
11884 ((setq e (rassoc c ntable) tg (car e))
11885 (if (member tg current)
11886 (setq current (delete tg current))
11887 (loop for g in groups do
11888 (if (member tg g)
11889 (mapc (lambda (x)
11890 (setq current (delete x current)))
11891 g)))
11892 (push tg current))
11893 (if exit-after-next (setq exit-after-next 'now))))
11895 ;; Create a sorted list
11896 (setq current
11897 (sort current
11898 (lambda (a b)
11899 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11900 (if (eq exit-after-next 'now) (throw 'exit t))
11901 (goto-char (point-min))
11902 (beginning-of-line 2)
11903 (delete-region (point) (point-at-eol))
11904 (org-fast-tag-insert "Current" current c-face)
11905 (org-set-current-tags-overlay current ov-prefix)
11906 (while (re-search-forward
11907 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11908 (setq tg (match-string 1))
11909 (add-text-properties
11910 (match-beginning 1) (match-end 1)
11911 (list 'face
11912 (cond
11913 ((member tg current) c-face)
11914 ((member tg inherited) i-face)
11915 (t (get-text-property (match-beginning 1) 'face))))))
11916 (goto-char (point-min)))))
11917 (org-detach-overlay org-tags-overlay)
11918 (if rtn
11919 (mapconcat 'identity current ":")
11920 nil))))
11922 (defun org-get-tags-string ()
11923 "Get the TAGS string in the current headline."
11924 (unless (org-on-heading-p t)
11925 (error "Not on a heading"))
11926 (save-excursion
11927 (beginning-of-line 1)
11928 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11929 (org-match-string-no-properties 1)
11930 "")))
11932 (defun org-get-tags ()
11933 "Get the list of tags specified in the current headline."
11934 (org-split-string (org-get-tags-string) ":"))
11936 (defun org-get-buffer-tags ()
11937 "Get a table of all tags used in the buffer, for completion."
11938 (let (tags)
11939 (save-excursion
11940 (goto-char (point-min))
11941 (while (re-search-forward
11942 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11943 (when (equal (char-after (point-at-bol 0)) ?*)
11944 (mapc (lambda (x) (add-to-list 'tags x))
11945 (org-split-string (org-match-string-no-properties 1) ":")))))
11946 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
11947 (mapcar 'list tags)))
11949 ;;;; The mapping API
11951 ;;;###autoload
11952 (defun org-map-entries (func &optional match scope &rest skip)
11953 "Call FUNC at each headline selected by MATCH in SCOPE.
11955 FUNC is a function or a lisp form. The function will be called without
11956 arguments, with the cursor positioned at the beginning of the headline.
11957 The return values of all calls to the function will be collected and
11958 returned as a list.
11960 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11961 does not need to preserve point. After evaluation, the cursor will be
11962 moved to the end of the line (presumably of the headline of the
11963 processed entry) and search continues from there. Under some
11964 circumstances, this may not produce the wanted results. For example,
11965 if you have removed (e.g. archived) the current (sub)tree it could
11966 mean that the next entry will be skipped entirely. In such cases, you
11967 can specify the position from where search should continue by making
11968 FUNC set the variable `org-map-continue-from' to the desired buffer
11969 position.
11971 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11972 Only headlines that are matched by this query will be considered during
11973 the iteration. When MATCH is nil or t, all headlines will be
11974 visited by the iteration.
11976 SCOPE determines the scope of this command. It can be any of:
11978 nil The current buffer, respecting the restriction if any
11979 tree The subtree started with the entry at point
11980 file The current buffer, without restriction
11981 file-with-archives
11982 The current buffer, and any archives associated with it
11983 agenda All agenda files
11984 agenda-with-archives
11985 All agenda files with any archive files associated with them
11986 \(file1 file2 ...)
11987 If this is a list, all files in the list will be scanned
11989 The remaining args are treated as settings for the skipping facilities of
11990 the scanner. The following items can be given here:
11992 archive skip trees with the archive tag.
11993 comment skip trees with the COMMENT keyword
11994 function or Emacs Lisp form:
11995 will be used as value for `org-agenda-skip-function', so whenever
11996 the function returns t, FUNC will not be called for that
11997 entry and search will continue from the point where the
11998 function leaves it.
12000 If your function needs to retrieve the tags including inherited tags
12001 at the *current* entry, you can use the value of the variable
12002 `org-scanner-tags' which will be much faster than getting the value
12003 with `org-get-tags-at'. If your function gets properties with
12004 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12005 to t around the call to `org-entry-properties' to get the same speedup.
12006 Note that if your function moves around to retrieve tags and properties at
12007 a *different* entry, you cannot use these techniques."
12008 (let* ((org-agenda-archives-mode nil) ; just to make sure
12009 (org-agenda-skip-archived-trees (memq 'archive skip))
12010 (org-agenda-skip-comment-trees (memq 'comment skip))
12011 (org-agenda-skip-function
12012 (car (org-delete-all '(comment archive) skip)))
12013 (org-tags-match-list-sublevels t)
12014 matcher file res
12015 org-todo-keywords-for-agenda
12016 org-done-keywords-for-agenda
12017 org-todo-keyword-alist-for-agenda
12018 org-drawers-for-agenda
12019 org-tag-alist-for-agenda)
12021 (cond
12022 ((eq match t) (setq matcher t))
12023 ((eq match nil) (setq matcher t))
12024 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12026 (save-excursion
12027 (save-restriction
12028 (when (eq scope 'tree)
12029 (org-back-to-heading t)
12030 (org-narrow-to-subtree)
12031 (setq scope nil))
12033 (if (not scope)
12034 (progn
12035 (org-prepare-agenda-buffers
12036 (list (buffer-file-name (current-buffer))))
12037 (setq res (org-scan-tags func matcher)))
12038 ;; Get the right scope
12039 (cond
12040 ((and scope (listp scope) (symbolp (car scope)))
12041 (setq scope (eval scope)))
12042 ((eq scope 'agenda)
12043 (setq scope (org-agenda-files t)))
12044 ((eq scope 'agenda-with-archives)
12045 (setq scope (org-agenda-files t))
12046 (setq scope (org-add-archive-files scope)))
12047 ((eq scope 'file)
12048 (setq scope (list (buffer-file-name))))
12049 ((eq scope 'file-with-archives)
12050 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12051 (org-prepare-agenda-buffers scope)
12052 (while (setq file (pop scope))
12053 (with-current-buffer (org-find-base-buffer-visiting file)
12054 (save-excursion
12055 (save-restriction
12056 (widen)
12057 (goto-char (point-min))
12058 (setq res (append res (org-scan-tags func matcher))))))))))
12059 res))
12061 ;;;; Properties
12063 ;;; Setting and retrieving properties
12065 (defconst org-special-properties
12066 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12067 "TIMESTAMP" "TIMESTAMP_IA")
12068 "The special properties valid in Org-mode.
12070 These are properties that are not defined in the property drawer,
12071 but in some other way.")
12073 (defconst org-default-properties
12074 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12075 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12076 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12077 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12078 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12079 "CLOCK_MODELINE_TOTAL" "STYLE")
12080 "Some properties that are used by Org-mode for various purposes.
12081 Being in this list makes sure that they are offered for completion.")
12083 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12084 "Regular expression matching the first line of a property drawer.")
12086 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12087 "Regular expression matching the first line of a property drawer.")
12089 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12090 "Regular expression matching the first line of a property drawer.")
12092 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12093 "Regular expression matching the first line of a property drawer.")
12095 (defconst org-property-drawer-re
12096 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12097 org-property-end-re "\\)\n?")
12098 "Matches an entire property drawer.")
12100 (defconst org-clock-drawer-re
12101 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12102 org-property-end-re "\\)\n?")
12103 "Matches an entire clock drawer.")
12105 (defun org-property-action ()
12106 "Do an action on properties."
12107 (interactive)
12108 (let (c)
12109 (org-at-property-p)
12110 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12111 (setq c (read-char-exclusive))
12112 (cond
12113 ((equal c ?s)
12114 (call-interactively 'org-set-property))
12115 ((equal c ?d)
12116 (call-interactively 'org-delete-property))
12117 ((equal c ?D)
12118 (call-interactively 'org-delete-property-globally))
12119 ((equal c ?c)
12120 (call-interactively 'org-compute-property-at-point))
12121 (t (error "No such property action %c" c)))))
12123 (defun org-set-effort (&optional value)
12124 "Set the effort property of the current entry.
12125 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12126 allowed value."
12127 (interactive "P")
12128 (if (equal value 0) (setq value 10))
12129 (let* ((completion-ignore-case t)
12130 (prop org-effort-property)
12131 (cur (org-entry-get nil prop))
12132 (allowed (org-property-get-allowed-values nil prop 'table))
12133 (existing (mapcar 'list (org-property-values prop)))
12135 (val (cond
12136 ((stringp value) value)
12137 ((and allowed (integerp value))
12138 (or (car (nth (1- value) allowed))
12139 (car (org-last allowed))))
12140 (allowed
12141 (message "Select 1-9,0, [RET%s]: %s"
12142 (if cur (concat "=" cur) "")
12143 (mapconcat 'car allowed " "))
12144 (setq rpl (read-char-exclusive))
12145 (if (equal rpl ?\r)
12147 (setq rpl (- rpl ?0))
12148 (if (equal rpl 0) (setq rpl 10))
12149 (if (and (> rpl 0) (<= rpl (length allowed)))
12150 (car (nth (1- rpl) allowed))
12151 (org-completing-read "Value: " allowed nil))))
12153 (let (org-completion-use-ido org-completion-use-iswitchb)
12154 (org-completing-read
12155 (concat "Value " (if (and cur (string-match "\\S-" cur))
12156 (concat "[" cur "]") "")
12157 ": ")
12158 existing nil nil "" nil cur))))))
12159 (unless (equal (org-entry-get nil prop) val)
12160 (org-entry-put nil prop val))
12161 (message "%s is now %s" prop val)))
12163 (defun org-at-property-p ()
12164 "Is the cursor in a property line?"
12165 ;; FIXME: Does not check if we are actually in the drawer.
12166 ;; FIXME: also returns true on any drawers.....
12167 ;; This is used by C-c C-c for property action.
12168 (save-excursion
12169 (beginning-of-line 1)
12170 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12172 (defun org-get-property-block (&optional beg end force)
12173 "Return the (beg . end) range of the body of the property drawer.
12174 BEG and END can be beginning and end of subtree, if not given
12175 they will be found.
12176 If the drawer does not exist and FORCE is non-nil, create the drawer."
12177 (catch 'exit
12178 (save-excursion
12179 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12180 (end (or end (progn (outline-next-heading) (point)))))
12181 (goto-char beg)
12182 (if (re-search-forward org-property-start-re end t)
12183 (setq beg (1+ (match-end 0)))
12184 (if force
12185 (save-excursion
12186 (org-insert-property-drawer)
12187 (setq end (progn (outline-next-heading) (point))))
12188 (throw 'exit nil))
12189 (goto-char beg)
12190 (if (re-search-forward org-property-start-re end t)
12191 (setq beg (1+ (match-end 0)))))
12192 (if (re-search-forward org-property-end-re end t)
12193 (setq end (match-beginning 0))
12194 (or force (throw 'exit nil))
12195 (goto-char beg)
12196 (setq end beg)
12197 (org-indent-line-function)
12198 (insert ":END:\n"))
12199 (cons beg end)))))
12201 (defun org-entry-properties (&optional pom which)
12202 "Get all properties of the entry at point-or-marker POM.
12203 This includes the TODO keyword, the tags, time strings for deadline,
12204 scheduled, and clocking, and any additional properties defined in the
12205 entry. The return value is an alist, keys may occur multiple times
12206 if the property key was used several times.
12207 POM may also be nil, in which case the current entry is used.
12208 If WHICH is nil or `all', get all properties. If WHICH is
12209 `special' or `standard', only get that subclass."
12210 (setq which (or which 'all))
12211 (org-with-point-at pom
12212 (let ((clockstr (substring org-clock-string 0 -1))
12213 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12214 beg end range props sum-props key value string clocksum)
12215 (save-excursion
12216 (when (condition-case nil
12217 (and (org-mode-p) (org-back-to-heading t))
12218 (error nil))
12219 (setq beg (point))
12220 (setq sum-props (get-text-property (point) 'org-summaries))
12221 (setq clocksum (get-text-property (point) :org-clock-minutes))
12222 (outline-next-heading)
12223 (setq end (point))
12224 (when (memq which '(all special))
12225 ;; Get the special properties, like TODO and tags
12226 (goto-char beg)
12227 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12228 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12229 (when (looking-at org-priority-regexp)
12230 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12231 (when (and (setq value (org-get-tags-string))
12232 (string-match "\\S-" value))
12233 (push (cons "TAGS" value) props))
12234 (when (setq value (org-get-tags-at))
12235 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12236 props))
12237 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12238 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12239 string (if (equal key clockstr)
12240 (org-no-properties
12241 (org-trim
12242 (buffer-substring
12243 (match-beginning 3) (goto-char (point-at-eol)))))
12244 (substring (org-match-string-no-properties 3) 1 -1)))
12245 (unless key
12246 (if (= (char-after (match-beginning 3)) ?\[)
12247 (setq key "TIMESTAMP_IA")
12248 (setq key "TIMESTAMP")))
12249 (when (or (equal key clockstr) (not (assoc key props)))
12250 (push (cons key string) props)))
12254 (when (memq which '(all standard))
12255 ;; Get the standard properties, like :PROP: ...
12256 (setq range (org-get-property-block beg end))
12257 (when range
12258 (goto-char (car range))
12259 (while (re-search-forward
12260 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12261 (cdr range) t)
12262 (setq key (org-match-string-no-properties 1)
12263 value (org-trim (or (org-match-string-no-properties 2) "")))
12264 (unless (member key excluded)
12265 (push (cons key (or value "")) props)))))
12266 (if clocksum
12267 (push (cons "CLOCKSUM"
12268 (org-columns-number-to-string (/ (float clocksum) 60.)
12269 'add_times))
12270 props))
12271 (unless (assoc "CATEGORY" props)
12272 (setq value (or (org-get-category)
12273 (progn (org-refresh-category-properties)
12274 (org-get-category))))
12275 (push (cons "CATEGORY" value) props))
12276 (append sum-props (nreverse props)))))))
12278 (defun org-entry-get (pom property &optional inherit)
12279 "Get value of PROPERTY for entry at point-or-marker POM.
12280 If INHERIT is non-nil and the entry does not have the property,
12281 then also check higher levels of the hierarchy.
12282 If INHERIT is the symbol `selective', use inheritance only if the setting
12283 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12284 If the property is present but empty, the return value is the empty string.
12285 If the property is not present at all, nil is returned."
12286 (org-with-point-at pom
12287 (if (and inherit (if (eq inherit 'selective)
12288 (org-property-inherit-p property)
12290 (org-entry-get-with-inheritance property)
12291 (if (member property org-special-properties)
12292 ;; We need a special property. Use brute force, get all properties.
12293 (cdr (assoc property (org-entry-properties nil 'special)))
12294 (let ((range (org-get-property-block)))
12295 (if (and range
12296 (goto-char (car range))
12297 (re-search-forward
12298 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12299 (cdr range) t))
12300 ;; Found the property, return it.
12301 (if (match-end 1)
12302 (org-match-string-no-properties 1)
12303 "")))))))
12305 (defun org-property-or-variable-value (var &optional inherit)
12306 "Check if there is a property fixing the value of VAR.
12307 If yes, return this value. If not, return the current value of the variable."
12308 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12309 (if (and prop (stringp prop) (string-match "\\S-" prop))
12310 (read prop)
12311 (symbol-value var))))
12313 (defun org-entry-delete (pom property)
12314 "Delete the property PROPERTY from entry at point-or-marker POM."
12315 (org-with-point-at pom
12316 (if (member property org-special-properties)
12317 nil ; cannot delete these properties.
12318 (let ((range (org-get-property-block)))
12319 (if (and range
12320 (goto-char (car range))
12321 (re-search-forward
12322 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12323 (cdr range) t))
12324 (progn
12325 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12327 nil)))))
12329 ;; Multi-values properties are properties that contain multiple values
12330 ;; These values are assumed to be single words, separated by whitespace.
12331 (defun org-entry-add-to-multivalued-property (pom property value)
12332 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12333 (let* ((old (org-entry-get pom property))
12334 (values (and old (org-split-string old "[ \t]"))))
12335 (setq value (org-entry-protect-space value))
12336 (unless (member value values)
12337 (setq values (cons value values))
12338 (org-entry-put pom property
12339 (mapconcat 'identity values " ")))))
12341 (defun org-entry-remove-from-multivalued-property (pom property value)
12342 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12343 (let* ((old (org-entry-get pom property))
12344 (values (and old (org-split-string old "[ \t]"))))
12345 (setq value (org-entry-protect-space value))
12346 (when (member value values)
12347 (setq values (delete value values))
12348 (org-entry-put pom property
12349 (mapconcat 'identity values " ")))))
12351 (defun org-entry-member-in-multivalued-property (pom property value)
12352 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12353 (let* ((old (org-entry-get pom property))
12354 (values (and old (org-split-string old "[ \t]"))))
12355 (setq value (org-entry-protect-space value))
12356 (member value values)))
12358 (defun org-entry-get-multivalued-property (pom property)
12359 "Return a list of values in a multivalued property."
12360 (let* ((value (org-entry-get pom property))
12361 (values (and value (org-split-string value "[ \t]"))))
12362 (mapcar 'org-entry-restore-space values)))
12364 (defun org-entry-put-multivalued-property (pom property &rest values)
12365 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12366 VALUES should be a list of strings. Spaces will be protected."
12367 (org-entry-put pom property
12368 (mapconcat 'org-entry-protect-space values " "))
12369 (let* ((value (org-entry-get pom property))
12370 (values (and value (org-split-string value "[ \t]"))))
12371 (mapcar 'org-entry-restore-space values)))
12373 (defun org-entry-protect-space (s)
12374 "Protect spaces and newline in string S."
12375 (while (string-match " " s)
12376 (setq s (replace-match "%20" t t s)))
12377 (while (string-match "\n" s)
12378 (setq s (replace-match "%0A" t t s)))
12381 (defun org-entry-restore-space (s)
12382 "Restore spaces and newline in string S."
12383 (while (string-match "%20" s)
12384 (setq s (replace-match " " t t s)))
12385 (while (string-match "%0A" s)
12386 (setq s (replace-match "\n" t t s)))
12389 (defvar org-entry-property-inherited-from (make-marker)
12390 "Marker pointing to the entry from where a property was inherited.
12391 Each call to `org-entry-get-with-inheritance' will set this marker to the
12392 location of the entry where the inheritance search matched. If there was
12393 no match, the marker will point nowhere.
12394 Note that also `org-entry-get' calls this function, if the INHERIT flag
12395 is set.")
12397 (defun org-entry-get-with-inheritance (property)
12398 "Get entry property, and search higher levels if not present."
12399 (move-marker org-entry-property-inherited-from nil)
12400 (let (tmp)
12401 (save-excursion
12402 (save-restriction
12403 (widen)
12404 (catch 'ex
12405 (while t
12406 (when (setq tmp (org-entry-get nil property))
12407 (org-back-to-heading t)
12408 (move-marker org-entry-property-inherited-from (point))
12409 (throw 'ex tmp))
12410 (or (org-up-heading-safe) (throw 'ex nil)))))
12411 (or tmp
12412 (cdr (assoc property org-file-properties))
12413 (cdr (assoc property org-global-properties))
12414 (cdr (assoc property org-global-properties-fixed))))))
12416 (defun org-entry-put (pom property value)
12417 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12418 (org-with-point-at pom
12419 (org-back-to-heading t)
12420 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12421 range)
12422 (cond
12423 ((equal property "TODO")
12424 (when (and (stringp value) (string-match "\\S-" value)
12425 (not (member value org-todo-keywords-1)))
12426 (error "\"%s\" is not a valid TODO state" value))
12427 (if (or (not value)
12428 (not (string-match "\\S-" value)))
12429 (setq value 'none))
12430 (org-todo value)
12431 (org-set-tags nil 'align))
12432 ((equal property "PRIORITY")
12433 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12434 (string-to-char value) ?\ ))
12435 (org-set-tags nil 'align))
12436 ((equal property "SCHEDULED")
12437 (if (re-search-forward org-scheduled-time-regexp end t)
12438 (cond
12439 ((eq value 'earlier) (org-timestamp-change -1 'day))
12440 ((eq value 'later) (org-timestamp-change 1 'day))
12441 (t (call-interactively 'org-schedule)))
12442 (call-interactively 'org-schedule)))
12443 ((equal property "DEADLINE")
12444 (if (re-search-forward org-deadline-time-regexp end t)
12445 (cond
12446 ((eq value 'earlier) (org-timestamp-change -1 'day))
12447 ((eq value 'later) (org-timestamp-change 1 'day))
12448 (t (call-interactively 'org-deadline)))
12449 (call-interactively 'org-deadline)))
12450 ((member property org-special-properties)
12451 (error "The %s property can not yet be set with `org-entry-put'"
12452 property))
12453 (t ; a non-special property
12454 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12455 (setq range (org-get-property-block beg end 'force))
12456 (goto-char (car range))
12457 (if (re-search-forward
12458 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12459 (progn
12460 (delete-region (match-beginning 1) (match-end 1))
12461 (goto-char (match-beginning 1)))
12462 (goto-char (cdr range))
12463 (insert "\n")
12464 (backward-char 1)
12465 (org-indent-line-function)
12466 (insert ":" property ":"))
12467 (and value (insert " " value))
12468 (org-indent-line-function)))))))
12470 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12471 "Get all property keys in the current buffer.
12472 With INCLUDE-SPECIALS, also list the special properties that reflect things
12473 like tags and TODO state.
12474 With INCLUDE-DEFAULTS, also include properties that has special meaning
12475 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12476 With INCLUDE-COLUMNS, also include property names given in COLUMN
12477 formats in the current buffer."
12478 (let (rtn range cfmt s p)
12479 (save-excursion
12480 (save-restriction
12481 (widen)
12482 (goto-char (point-min))
12483 (while (re-search-forward org-property-start-re nil t)
12484 (setq range (org-get-property-block))
12485 (goto-char (car range))
12486 (while (re-search-forward
12487 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12488 (cdr range) t)
12489 (add-to-list 'rtn (org-match-string-no-properties 1)))
12490 (outline-next-heading))))
12492 (when include-specials
12493 (setq rtn (append org-special-properties rtn)))
12495 (when include-defaults
12496 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12497 (add-to-list 'rtn org-effort-property))
12499 (when include-columns
12500 (save-excursion
12501 (save-restriction
12502 (widen)
12503 (goto-char (point-min))
12504 (while (re-search-forward
12505 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12506 nil t)
12507 (setq cfmt (match-string 2) s 0)
12508 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12509 cfmt s)
12510 (setq s (match-end 0)
12511 p (match-string 1 cfmt))
12512 (unless (or (equal p "ITEM")
12513 (member p org-special-properties))
12514 (add-to-list 'rtn (match-string 1 cfmt))))))))
12516 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12518 (defun org-property-values (key)
12519 "Return a list of all values of property KEY."
12520 (save-excursion
12521 (save-restriction
12522 (widen)
12523 (goto-char (point-min))
12524 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12525 values)
12526 (while (re-search-forward re nil t)
12527 (add-to-list 'values (org-trim (match-string 1))))
12528 (delete "" values)))))
12530 (defun org-insert-property-drawer ()
12531 "Insert a property drawer into the current entry."
12532 (interactive)
12533 (org-back-to-heading t)
12534 (looking-at outline-regexp)
12535 (let ((indent (if org-adapt-indentation
12536 (- (match-end 0)(match-beginning 0))
12538 (beg (point))
12539 (re (concat "^[ \t]*" org-keyword-time-regexp))
12540 end hiddenp)
12541 (outline-next-heading)
12542 (setq end (point))
12543 (goto-char beg)
12544 (while (re-search-forward re end t))
12545 (setq hiddenp (org-invisible-p))
12546 (end-of-line 1)
12547 (and (equal (char-after) ?\n) (forward-char 1))
12548 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12549 (if (member (match-string 1) '("CLOCK:" ":END:"))
12550 ;; just skip this line
12551 (beginning-of-line 2)
12552 ;; Drawer start, find the end
12553 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12554 (beginning-of-line 1)))
12555 (org-skip-over-state-notes)
12556 (skip-chars-backward " \t\n\r")
12557 (if (eq (char-before) ?*) (forward-char 1))
12558 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12559 (beginning-of-line 0)
12560 (org-indent-to-column indent)
12561 (beginning-of-line 2)
12562 (org-indent-to-column indent)
12563 (beginning-of-line 0)
12564 (if hiddenp
12565 (save-excursion
12566 (org-back-to-heading t)
12567 (hide-entry))
12568 (org-flag-drawer t))))
12570 (defun org-set-property (property value)
12571 "In the current entry, set PROPERTY to VALUE.
12572 When called interactively, this will prompt for a property name, offering
12573 completion on existing and default properties. And then it will prompt
12574 for a value, offering completion either on allowed values (via an inherited
12575 xxx_ALL property) or on existing values in other instances of this property
12576 in the current file."
12577 (interactive
12578 (let* ((completion-ignore-case t)
12579 (keys (org-buffer-property-keys nil t t))
12580 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12581 (prop (if (member prop0 keys)
12582 prop0
12583 (or (cdr (assoc (downcase prop0)
12584 (mapcar (lambda (x) (cons (downcase x) x))
12585 keys)))
12586 prop0)))
12587 (cur (org-entry-get nil prop))
12588 (allowed (org-property-get-allowed-values nil prop 'table))
12589 (existing (mapcar 'list (org-property-values prop)))
12590 (val (if allowed
12591 (org-completing-read "Value: " allowed nil 'req-match)
12592 (let (org-completion-use-ido org-completion-use-iswitchb)
12593 (org-completing-read
12594 (concat "Value " (if (and cur (string-match "\\S-" cur))
12595 (concat "[" cur "]") "")
12596 ": ")
12597 existing nil nil "" nil cur)))))
12598 (list prop (if (equal val "") cur val))))
12599 (unless (equal (org-entry-get nil property) value)
12600 (org-entry-put nil property value)))
12602 (defun org-delete-property (property)
12603 "In the current entry, delete PROPERTY."
12604 (interactive
12605 (let* ((completion-ignore-case t)
12606 (prop (org-icompleting-read
12607 "Property: " (org-entry-properties nil 'standard))))
12608 (list prop)))
12609 (message "Property %s %s" property
12610 (if (org-entry-delete nil property)
12611 "deleted"
12612 "was not present in the entry")))
12614 (defun org-delete-property-globally (property)
12615 "Remove PROPERTY globally, from all entries."
12616 (interactive
12617 (let* ((completion-ignore-case t)
12618 (prop (org-icompleting-read
12619 "Globally remove property: "
12620 (mapcar 'list (org-buffer-property-keys)))))
12621 (list prop)))
12622 (save-excursion
12623 (save-restriction
12624 (widen)
12625 (goto-char (point-min))
12626 (let ((cnt 0))
12627 (while (re-search-forward
12628 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12629 nil t)
12630 (setq cnt (1+ cnt))
12631 (replace-match ""))
12632 (message "Property \"%s\" removed from %d entries" property cnt)))))
12634 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12636 (defun org-compute-property-at-point ()
12637 "Compute the property at point.
12638 This looks for an enclosing column format, extracts the operator and
12639 then applies it to the property in the column format's scope."
12640 (interactive)
12641 (unless (org-at-property-p)
12642 (error "Not at a property"))
12643 (let ((prop (org-match-string-no-properties 2)))
12644 (org-columns-get-format-and-top-level)
12645 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12646 (error "No operator defined for property %s" prop))
12647 (org-columns-compute prop)))
12649 (defun org-property-get-allowed-values (pom property &optional table)
12650 "Get allowed values for the property PROPERTY.
12651 When TABLE is non-nil, return an alist that can directly be used for
12652 completion."
12653 (let (vals)
12654 (cond
12655 ((equal property "TODO")
12656 (setq vals (org-with-point-at pom
12657 (append org-todo-keywords-1 '("")))))
12658 ((equal property "PRIORITY")
12659 (let ((n org-lowest-priority))
12660 (while (>= n org-highest-priority)
12661 (push (char-to-string n) vals)
12662 (setq n (1- n)))))
12663 ((member property org-special-properties))
12665 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12667 (when (and vals (string-match "\\S-" vals))
12668 (setq vals (car (read-from-string (concat "(" vals ")"))))
12669 (setq vals (mapcar (lambda (x)
12670 (cond ((stringp x) x)
12671 ((numberp x) (number-to-string x))
12672 ((symbolp x) (symbol-name x))
12673 (t "???")))
12674 vals)))))
12675 (if table (mapcar 'list vals) vals)))
12677 (defun org-property-previous-allowed-value (&optional previous)
12678 "Switch to the next allowed value for this property."
12679 (interactive)
12680 (org-property-next-allowed-value t))
12682 (defun org-property-next-allowed-value (&optional previous)
12683 "Switch to the next allowed value for this property."
12684 (interactive)
12685 (unless (org-at-property-p)
12686 (error "Not at a property"))
12687 (let* ((key (match-string 2))
12688 (value (match-string 3))
12689 (allowed (or (org-property-get-allowed-values (point) key)
12690 (and (member value '("[ ]" "[-]" "[X]"))
12691 '("[ ]" "[X]"))))
12692 nval)
12693 (unless allowed
12694 (error "Allowed values for this property have not been defined"))
12695 (if previous (setq allowed (reverse allowed)))
12696 (if (member value allowed)
12697 (setq nval (car (cdr (member value allowed)))))
12698 (setq nval (or nval (car allowed)))
12699 (if (equal nval value)
12700 (error "Only one allowed value for this property"))
12701 (org-at-property-p)
12702 (replace-match (concat " :" key ": " nval) t t)
12703 (org-indent-line-function)
12704 (beginning-of-line 1)
12705 (skip-chars-forward " \t")))
12707 (defun org-find-entry-with-id (ident)
12708 "Locate the entry that contains the ID property with exact value IDENT.
12709 IDENT can be a string, a symbol or a number, this function will search for
12710 the string representation of it.
12711 Return the position where this entry starts, or nil if there is no such entry."
12712 (interactive "sID: ")
12713 (let ((id (cond
12714 ((stringp ident) ident)
12715 ((symbol-name ident) (symbol-name ident))
12716 ((numberp ident) (number-to-string ident))
12717 (t (error "IDENT %s must be a string, symbol or number" ident))))
12718 (case-fold-search nil))
12719 (save-excursion
12720 (save-restriction
12721 (widen)
12722 (goto-char (point-min))
12723 (when (re-search-forward
12724 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12725 nil t)
12726 (org-back-to-heading t)
12727 (point))))))
12729 ;;;; Timestamps
12731 (defvar org-last-changed-timestamp nil)
12732 (defvar org-last-inserted-timestamp nil
12733 "The last time stamp inserted with `org-insert-time-stamp'.")
12734 (defvar org-time-was-given) ; dynamically scoped parameter
12735 (defvar org-end-time-was-given) ; dynamically scoped parameter
12736 (defvar org-ts-what) ; dynamically scoped parameter
12738 (defun org-time-stamp (arg &optional inactive)
12739 "Prompt for a date/time and insert a time stamp.
12740 If the user specifies a time like HH:MM, or if this command is called
12741 with a prefix argument, the time stamp will contain date and time.
12742 Otherwise, only the date will be included. All parts of a date not
12743 specified by the user will be filled in from the current date/time.
12744 So if you press just return without typing anything, the time stamp
12745 will represent the current date/time. If there is already a timestamp
12746 at the cursor, it will be modified."
12747 (interactive "P")
12748 (let* ((ts nil)
12749 (default-time
12750 ;; Default time is either today, or, when entering a range,
12751 ;; the range start.
12752 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12753 (save-excursion
12754 (re-search-backward
12755 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12756 (- (point) 20) t)))
12757 (apply 'encode-time (org-parse-time-string (match-string 1)))
12758 (current-time)))
12759 (default-input (and ts (org-get-compact-tod ts)))
12760 org-time-was-given org-end-time-was-given time)
12761 (cond
12762 ((and (org-at-timestamp-p t)
12763 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12764 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12765 (insert "--")
12766 (setq time (let ((this-command this-command))
12767 (org-read-date arg 'totime nil nil
12768 default-time default-input)))
12769 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12770 ((org-at-timestamp-p t)
12771 (setq time (let ((this-command this-command))
12772 (org-read-date arg 'totime nil nil default-time default-input)))
12773 (when (org-at-timestamp-p t) ; just to get the match data
12774 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12775 (replace-match "")
12776 (setq org-last-changed-timestamp
12777 (org-insert-time-stamp
12778 time (or org-time-was-given arg)
12779 inactive nil nil (list org-end-time-was-given))))
12780 (message "Timestamp updated"))
12782 (setq time (let ((this-command this-command))
12783 (org-read-date arg 'totime nil nil default-time default-input)))
12784 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12785 nil nil (list org-end-time-was-given))))))
12787 ;; FIXME: can we use this for something else, like computing time differences?
12788 (defun org-get-compact-tod (s)
12789 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12790 (let* ((t1 (match-string 1 s))
12791 (h1 (string-to-number (match-string 2 s)))
12792 (m1 (string-to-number (match-string 3 s)))
12793 (t2 (and (match-end 4) (match-string 5 s)))
12794 (h2 (and t2 (string-to-number (match-string 6 s))))
12795 (m2 (and t2 (string-to-number (match-string 7 s))))
12796 dh dm)
12797 (if (not t2)
12799 (setq dh (- h2 h1) dm (- m2 m1))
12800 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12801 (concat t1 "+" (number-to-string dh)
12802 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12804 (defun org-time-stamp-inactive (&optional arg)
12805 "Insert an inactive time stamp.
12806 An inactive time stamp is enclosed in square brackets instead of angle
12807 brackets. It is inactive in the sense that it does not trigger agenda entries,
12808 does not link to the calendar and cannot be changed with the S-cursor keys.
12809 So these are more for recording a certain time/date."
12810 (interactive "P")
12811 (org-time-stamp arg 'inactive))
12813 (defvar org-date-ovl (org-make-overlay 1 1))
12814 (org-overlay-put org-date-ovl 'face 'org-warning)
12815 (org-detach-overlay org-date-ovl)
12817 (defvar org-ans1) ; dynamically scoped parameter
12818 (defvar org-ans2) ; dynamically scoped parameter
12820 (defvar org-plain-time-of-day-regexp) ; defined below
12822 (defvar org-overriding-default-time nil) ; dynamically scoped
12823 (defvar org-read-date-overlay nil)
12824 (defvar org-dcst nil) ; dynamically scoped
12825 (defvar org-read-date-history nil)
12826 (defvar org-read-date-final-answer nil)
12828 (defun org-read-date (&optional with-time to-time from-string prompt
12829 default-time default-input)
12830 "Read a date, possibly a time, and make things smooth for the user.
12831 The prompt will suggest to enter an ISO date, but you can also enter anything
12832 which will at least partially be understood by `parse-time-string'.
12833 Unrecognized parts of the date will default to the current day, month, year,
12834 hour and minute. If this command is called to replace a timestamp at point,
12835 of to enter the second timestamp of a range, the default time is taken from the
12836 existing stamp. For example,
12837 3-2-5 --> 2003-02-05
12838 feb 15 --> currentyear-02-15
12839 sep 12 9 --> 2009-09-12
12840 12:45 --> today 12:45
12841 22 sept 0:34 --> currentyear-09-22 0:34
12842 12 --> currentyear-currentmonth-12
12843 Fri --> nearest Friday (today or later)
12844 etc.
12846 Furthermore you can specify a relative date by giving, as the *first* thing
12847 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12848 change in days weeks, months, years.
12849 With a single plus or minus, the date is relative to today. With a double
12850 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12851 +4d --> four days from today
12852 +4 --> same as above
12853 +2w --> two weeks from today
12854 ++5 --> five days from default date
12856 The function understands only English month and weekday abbreviations,
12857 but this can be configured with the variables `parse-time-months' and
12858 `parse-time-weekdays'.
12860 While prompting, a calendar is popped up - you can also select the
12861 date with the mouse (button 1). The calendar shows a period of three
12862 months. To scroll it to other months, use the keys `>' and `<'.
12863 If you don't like the calendar, turn it off with
12864 \(setq org-read-date-popup-calendar nil)
12866 With optional argument TO-TIME, the date will immediately be converted
12867 to an internal time.
12868 With an optional argument WITH-TIME, the prompt will suggest to also
12869 insert a time. Note that when WITH-TIME is not set, you can still
12870 enter a time, and this function will inform the calling routine about
12871 this change. The calling routine may then choose to change the format
12872 used to insert the time stamp into the buffer to include the time.
12873 With optional argument FROM-STRING, read from this string instead from
12874 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12875 the time/date that is used for everything that is not specified by the
12876 user."
12877 (require 'parse-time)
12878 (let* ((org-time-stamp-rounding-minutes
12879 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12880 (org-dcst org-display-custom-times)
12881 (ct (org-current-time))
12882 (def (or org-overriding-default-time default-time ct))
12883 (defdecode (decode-time def))
12884 (dummy (progn
12885 (when (< (nth 2 defdecode) org-extend-today-until)
12886 (setcar (nthcdr 2 defdecode) -1)
12887 (setcar (nthcdr 1 defdecode) 59)
12888 (setq def (apply 'encode-time defdecode)
12889 defdecode (decode-time def)))))
12890 (calendar-frame-setup nil)
12891 (calendar-move-hook nil)
12892 (calendar-view-diary-initially-flag nil)
12893 (view-diary-entries-initially nil)
12894 (calendar-view-holidays-initially-flag nil)
12895 (view-calendar-holidays-initially nil)
12896 (timestr (format-time-string
12897 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12898 (prompt (concat (if prompt (concat prompt " ") "")
12899 (format "Date+time [%s]: " timestr)))
12900 ans (org-ans0 "") org-ans1 org-ans2 final)
12902 (cond
12903 (from-string (setq ans from-string))
12904 (org-read-date-popup-calendar
12905 (save-excursion
12906 (save-window-excursion
12907 (calendar)
12908 (calendar-forward-day (- (time-to-days def)
12909 (calendar-absolute-from-gregorian
12910 (calendar-current-date))))
12911 (org-eval-in-calendar nil t)
12912 (let* ((old-map (current-local-map))
12913 (map (copy-keymap calendar-mode-map))
12914 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12915 (org-defkey map (kbd "RET") 'org-calendar-select)
12916 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12917 'org-calendar-select-mouse)
12918 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12919 'org-calendar-select-mouse)
12920 (org-defkey minibuffer-local-map [(meta shift left)]
12921 (lambda () (interactive)
12922 (org-eval-in-calendar '(calendar-backward-month 1))))
12923 (org-defkey minibuffer-local-map [(meta shift right)]
12924 (lambda () (interactive)
12925 (org-eval-in-calendar '(calendar-forward-month 1))))
12926 (org-defkey minibuffer-local-map [(meta shift up)]
12927 (lambda () (interactive)
12928 (org-eval-in-calendar '(calendar-backward-year 1))))
12929 (org-defkey minibuffer-local-map [(meta shift down)]
12930 (lambda () (interactive)
12931 (org-eval-in-calendar '(calendar-forward-year 1))))
12932 (org-defkey minibuffer-local-map [?\e (shift left)]
12933 (lambda () (interactive)
12934 (org-eval-in-calendar '(calendar-backward-month 1))))
12935 (org-defkey minibuffer-local-map [?\e (shift right)]
12936 (lambda () (interactive)
12937 (org-eval-in-calendar '(calendar-forward-month 1))))
12938 (org-defkey minibuffer-local-map [?\e (shift up)]
12939 (lambda () (interactive)
12940 (org-eval-in-calendar '(calendar-backward-year 1))))
12941 (org-defkey minibuffer-local-map [?\e (shift down)]
12942 (lambda () (interactive)
12943 (org-eval-in-calendar '(calendar-forward-year 1))))
12944 (org-defkey minibuffer-local-map [(shift up)]
12945 (lambda () (interactive)
12946 (org-eval-in-calendar '(calendar-backward-week 1))))
12947 (org-defkey minibuffer-local-map [(shift down)]
12948 (lambda () (interactive)
12949 (org-eval-in-calendar '(calendar-forward-week 1))))
12950 (org-defkey minibuffer-local-map [(shift left)]
12951 (lambda () (interactive)
12952 (org-eval-in-calendar '(calendar-backward-day 1))))
12953 (org-defkey minibuffer-local-map [(shift right)]
12954 (lambda () (interactive)
12955 (org-eval-in-calendar '(calendar-forward-day 1))))
12956 (org-defkey minibuffer-local-map ">"
12957 (lambda () (interactive)
12958 (org-eval-in-calendar '(scroll-calendar-left 1))))
12959 (org-defkey minibuffer-local-map "<"
12960 (lambda () (interactive)
12961 (org-eval-in-calendar '(scroll-calendar-right 1))))
12962 (run-hooks 'org-read-date-minibuffer-setup-hook)
12963 (unwind-protect
12964 (progn
12965 (use-local-map map)
12966 (add-hook 'post-command-hook 'org-read-date-display)
12967 (setq org-ans0 (read-string prompt default-input
12968 'org-read-date-history nil))
12969 ;; org-ans0: from prompt
12970 ;; org-ans1: from mouse click
12971 ;; org-ans2: from calendar motion
12972 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12973 (remove-hook 'post-command-hook 'org-read-date-display)
12974 (use-local-map old-map)
12975 (when org-read-date-overlay
12976 (org-delete-overlay org-read-date-overlay)
12977 (setq org-read-date-overlay nil)))))))
12979 (t ; Naked prompt only
12980 (unwind-protect
12981 (setq ans (read-string prompt default-input
12982 'org-read-date-history timestr))
12983 (when org-read-date-overlay
12984 (org-delete-overlay org-read-date-overlay)
12985 (setq org-read-date-overlay nil)))))
12987 (setq final (org-read-date-analyze ans def defdecode))
12988 (setq org-read-date-final-answer ans)
12990 (if to-time
12991 (apply 'encode-time final)
12992 (if (and (boundp 'org-time-was-given) org-time-was-given)
12993 (format "%04d-%02d-%02d %02d:%02d"
12994 (nth 5 final) (nth 4 final) (nth 3 final)
12995 (nth 2 final) (nth 1 final))
12996 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12998 (defvar def)
12999 (defvar defdecode)
13000 (defvar with-time)
13001 (defvar org-read-date-analyze-futurep nil)
13002 (defun org-read-date-display ()
13003 "Display the current date prompt interpretation in the minibuffer."
13004 (when org-read-date-display-live
13005 (when org-read-date-overlay
13006 (org-delete-overlay org-read-date-overlay))
13007 (let ((p (point)))
13008 (end-of-line 1)
13009 (while (not (equal (buffer-substring
13010 (max (point-min) (- (point) 4)) (point))
13011 " "))
13012 (insert " "))
13013 (goto-char p))
13014 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13015 " " (or org-ans1 org-ans2)))
13016 (org-end-time-was-given nil)
13017 (f (org-read-date-analyze ans def defdecode))
13018 (fmts (if org-dcst
13019 org-time-stamp-custom-formats
13020 org-time-stamp-formats))
13021 (fmt (if (or with-time
13022 (and (boundp 'org-time-was-given) org-time-was-given))
13023 (cdr fmts)
13024 (car fmts)))
13025 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13026 (when (and org-end-time-was-given
13027 (string-match org-plain-time-of-day-regexp txt))
13028 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13029 org-end-time-was-given
13030 (substring txt (match-end 0)))))
13031 (when org-read-date-analyze-futurep
13032 (setq txt (concat txt " (=>F)")))
13033 (setq org-read-date-overlay
13034 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13035 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13037 (defun org-read-date-analyze (ans def defdecode)
13038 "Analyse the combined answer of the date prompt."
13039 ;; FIXME: cleanup and comment
13040 (let (delta deltan deltaw deltadef year month day
13041 hour minute second wday pm h2 m2 tl wday1
13042 iso-year iso-weekday iso-week iso-year iso-date futurep)
13043 (setq org-read-date-analyze-futurep nil)
13044 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13045 (setq ans "+0"))
13047 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13048 (setq ans (replace-match "" t t ans)
13049 deltan (car delta)
13050 deltaw (nth 1 delta)
13051 deltadef (nth 2 delta)))
13053 ;; Check if there is an iso week date in there
13054 ;; If yes, sore the info and postpone interpreting it until the rest
13055 ;; of the parsing is done
13056 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13057 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13058 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13059 iso-week (string-to-number (match-string 2 ans)))
13060 (setq ans (replace-match "" t t ans)))
13062 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13063 (when (string-match
13064 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13065 (setq year (if (match-end 2)
13066 (string-to-number (match-string 2 ans))
13067 (string-to-number (format-time-string "%Y")))
13068 month (string-to-number (match-string 3 ans))
13069 day (string-to-number (match-string 4 ans)))
13070 (if (< year 100) (setq year (+ 2000 year)))
13071 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13072 t nil ans)))
13073 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13074 ;; If there is a time with am/pm, and *no* time without it, we convert
13075 ;; so that matching will be successful.
13076 (loop for i from 1 to 2 do ; twice, for end time as well
13077 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13078 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13079 (setq hour (string-to-number (match-string 1 ans))
13080 minute (if (match-end 3)
13081 (string-to-number (match-string 3 ans))
13083 pm (equal ?p
13084 (string-to-char (downcase (match-string 4 ans)))))
13085 (if (and (= hour 12) (not pm))
13086 (setq hour 0)
13087 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13088 (setq ans (replace-match (format "%02d:%02d" hour minute)
13089 t t ans))))
13091 ;; Check if a time range is given as a duration
13092 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13093 (setq hour (string-to-number (match-string 1 ans))
13094 h2 (+ hour (string-to-number (match-string 3 ans)))
13095 minute (string-to-number (match-string 2 ans))
13096 m2 (+ minute (if (match-end 5) (string-to-number
13097 (match-string 5 ans))0)))
13098 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13099 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13100 t t ans)))
13102 ;; Check if there is a time range
13103 (when (boundp 'org-end-time-was-given)
13104 (setq org-time-was-given nil)
13105 (when (and (string-match org-plain-time-of-day-regexp ans)
13106 (match-end 8))
13107 (setq org-end-time-was-given (match-string 8 ans))
13108 (setq ans (concat (substring ans 0 (match-beginning 7))
13109 (substring ans (match-end 7))))))
13111 (setq tl (parse-time-string ans)
13112 day (or (nth 3 tl) (nth 3 defdecode))
13113 month (or (nth 4 tl)
13114 (if (and org-read-date-prefer-future
13115 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13116 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13117 (nth 4 defdecode)))
13118 year (or (nth 5 tl)
13119 (if (and org-read-date-prefer-future
13120 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13121 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13122 (nth 5 defdecode)))
13123 hour (or (nth 2 tl) (nth 2 defdecode))
13124 minute (or (nth 1 tl) (nth 1 defdecode))
13125 second (or (nth 0 tl) 0)
13126 wday (nth 6 tl))
13128 (when (and (eq org-read-date-prefer-future 'time)
13129 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13130 (equal day (nth 3 defdecode))
13131 (equal month (nth 4 defdecode))
13132 (equal year (nth 5 defdecode))
13133 (nth 2 tl)
13134 (or (< (nth 2 tl) (nth 2 defdecode))
13135 (and (= (nth 2 tl) (nth 2 defdecode))
13136 (nth 1 tl)
13137 (< (nth 1 tl) (nth 1 defdecode)))))
13138 (setq day (1+ day)
13139 futurep t))
13141 ;; Special date definitions below
13142 (cond
13143 (iso-week
13144 ;; There was an iso week
13145 (setq futurep nil)
13146 (setq year (or iso-year year)
13147 day (or iso-weekday wday 1)
13148 wday nil ; to make sure that the trigger below does not match
13149 iso-date (calendar-gregorian-from-absolute
13150 (calendar-absolute-from-iso
13151 (list iso-week day year))))
13152 ; FIXME: Should we also push ISO weeks into the future?
13153 ; (when (and org-read-date-prefer-future
13154 ; (not iso-year)
13155 ; (< (calendar-absolute-from-gregorian iso-date)
13156 ; (time-to-days (current-time))))
13157 ; (setq year (1+ year)
13158 ; iso-date (calendar-gregorian-from-absolute
13159 ; (calendar-absolute-from-iso
13160 ; (list iso-week day year)))))
13161 (setq month (car iso-date)
13162 year (nth 2 iso-date)
13163 day (nth 1 iso-date)))
13164 (deltan
13165 (setq futurep nil)
13166 (unless deltadef
13167 (let ((now (decode-time (current-time))))
13168 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13169 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13170 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13171 ((equal deltaw "m") (setq month (+ month deltan)))
13172 ((equal deltaw "y") (setq year (+ year deltan)))))
13173 ((and wday (not (nth 3 tl)))
13174 (setq futurep nil)
13175 ;; Weekday was given, but no day, so pick that day in the week
13176 ;; on or after the derived date.
13177 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13178 (unless (equal wday wday1)
13179 (setq day (+ day (% (- wday wday1 -7) 7))))))
13180 (if (and (boundp 'org-time-was-given)
13181 (nth 2 tl))
13182 (setq org-time-was-given t))
13183 (if (< year 100) (setq year (+ 2000 year)))
13184 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13185 (setq org-read-date-analyze-futurep futurep)
13186 (list second minute hour day month year)))
13188 (defvar parse-time-weekdays)
13190 (defun org-read-date-get-relative (s today default)
13191 "Check string S for special relative date string.
13192 TODAY and DEFAULT are internal times, for today and for a default.
13193 Return shift list (N what def-flag)
13194 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13195 N is the number of WHATs to shift.
13196 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13197 the DEFAULT date rather than TODAY."
13198 (when (and
13199 (string-match
13200 (concat
13201 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13202 "\\([0-9]+\\)?"
13203 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13204 "\\([ \t]\\|$\\)") s)
13205 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13206 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13207 (string-to-char (substring (match-string 1 s) -1))
13208 ?+))
13209 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13210 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13211 (what (if (match-end 3) (match-string 3 s) "d"))
13212 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13213 (date (if rel default today))
13214 (wday (nth 6 (decode-time date)))
13215 delta)
13216 (if wday1
13217 (progn
13218 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13219 (if (= dir ?-) (setq delta (- delta 7)))
13220 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13221 (list delta "d" rel))
13222 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13224 (defun org-eval-in-calendar (form &optional keepdate)
13225 "Eval FORM in the calendar window and return to current window.
13226 Also, store the cursor date in variable org-ans2."
13227 (let ((sf (selected-frame))
13228 (sw (selected-window)))
13229 (select-window (get-buffer-window "*Calendar*" t))
13230 (eval form)
13231 (when (and (not keepdate) (calendar-cursor-to-date))
13232 (let* ((date (calendar-cursor-to-date))
13233 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13234 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13235 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13236 (select-window sw)
13237 (org-select-frame-set-input-focus sf)))
13239 (defun org-calendar-select ()
13240 "Return to `org-read-date' with the date currently selected.
13241 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13242 (interactive)
13243 (when (calendar-cursor-to-date)
13244 (let* ((date (calendar-cursor-to-date))
13245 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13246 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13247 (if (active-minibuffer-window) (exit-minibuffer))))
13249 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13250 "Insert a date stamp for the date given by the internal TIME.
13251 WITH-HM means, use the stamp format that includes the time of the day.
13252 INACTIVE means use square brackets instead of angular ones, so that the
13253 stamp will not contribute to the agenda.
13254 PRE and POST are optional strings to be inserted before and after the
13255 stamp.
13256 The command returns the inserted time stamp."
13257 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13258 stamp)
13259 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13260 (insert-before-markers (or pre ""))
13261 (insert-before-markers (setq stamp (format-time-string fmt time)))
13262 (when (listp extra)
13263 (setq extra (car extra))
13264 (if (and (stringp extra)
13265 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13266 (setq extra (format "-%02d:%02d"
13267 (string-to-number (match-string 1 extra))
13268 (string-to-number (match-string 2 extra))))
13269 (setq extra nil)))
13270 (when extra
13271 (backward-char 1)
13272 (insert-before-markers extra)
13273 (forward-char 1))
13274 (insert-before-markers (or post ""))
13275 (setq org-last-inserted-timestamp stamp)))
13277 (defun org-toggle-time-stamp-overlays ()
13278 "Toggle the use of custom time stamp formats."
13279 (interactive)
13280 (setq org-display-custom-times (not org-display-custom-times))
13281 (unless org-display-custom-times
13282 (let ((p (point-min)) (bmp (buffer-modified-p)))
13283 (while (setq p (next-single-property-change p 'display))
13284 (if (and (get-text-property p 'display)
13285 (eq (get-text-property p 'face) 'org-date))
13286 (remove-text-properties
13287 p (setq p (next-single-property-change p 'display))
13288 '(display t))))
13289 (set-buffer-modified-p bmp)))
13290 (if (featurep 'xemacs)
13291 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13292 (org-restart-font-lock)
13293 (setq org-table-may-need-update t)
13294 (if org-display-custom-times
13295 (message "Time stamps are overlayed with custom format")
13296 (message "Time stamp overlays removed")))
13298 (defun org-display-custom-time (beg end)
13299 "Overlay modified time stamp format over timestamp between BEG and END."
13300 (let* ((ts (buffer-substring beg end))
13301 t1 w1 with-hm tf time str w2 (off 0))
13302 (save-match-data
13303 (setq t1 (org-parse-time-string ts t))
13304 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13305 (setq off (- (match-end 0) (match-beginning 0)))))
13306 (setq end (- end off))
13307 (setq w1 (- end beg)
13308 with-hm (and (nth 1 t1) (nth 2 t1))
13309 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13310 time (org-fix-decoded-time t1)
13311 str (org-add-props
13312 (format-time-string
13313 (substring tf 1 -1) (apply 'encode-time time))
13314 nil 'mouse-face 'highlight)
13315 w2 (length str))
13316 (if (not (= w2 w1))
13317 (add-text-properties (1+ beg) (+ 2 beg)
13318 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13319 (if (featurep 'xemacs)
13320 (progn
13321 (put-text-property beg end 'invisible t)
13322 (put-text-property beg end 'end-glyph (make-glyph str)))
13323 (put-text-property beg end 'display str))))
13325 (defun org-translate-time (string)
13326 "Translate all timestamps in STRING to custom format.
13327 But do this only if the variable `org-display-custom-times' is set."
13328 (when org-display-custom-times
13329 (save-match-data
13330 (let* ((start 0)
13331 (re org-ts-regexp-both)
13332 t1 with-hm inactive tf time str beg end)
13333 (while (setq start (string-match re string start))
13334 (setq beg (match-beginning 0)
13335 end (match-end 0)
13336 t1 (save-match-data
13337 (org-parse-time-string (substring string beg end) t))
13338 with-hm (and (nth 1 t1) (nth 2 t1))
13339 inactive (equal (substring string beg (1+ beg)) "[")
13340 tf (funcall (if with-hm 'cdr 'car)
13341 org-time-stamp-custom-formats)
13342 time (org-fix-decoded-time t1)
13343 str (format-time-string
13344 (concat
13345 (if inactive "[" "<") (substring tf 1 -1)
13346 (if inactive "]" ">"))
13347 (apply 'encode-time time))
13348 string (replace-match str t t string)
13349 start (+ start (length str)))))))
13350 string)
13352 (defun org-fix-decoded-time (time)
13353 "Set 0 instead of nil for the first 6 elements of time.
13354 Don't touch the rest."
13355 (let ((n 0))
13356 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13358 (defun org-days-to-time (timestamp-string)
13359 "Difference between TIMESTAMP-STRING and now in days."
13360 (- (time-to-days (org-time-string-to-time timestamp-string))
13361 (time-to-days (current-time))))
13363 (defun org-deadline-close (timestamp-string &optional ndays)
13364 "Is the time in TIMESTAMP-STRING close to the current date?"
13365 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13366 (and (< (org-days-to-time timestamp-string) ndays)
13367 (not (org-entry-is-done-p))))
13369 (defun org-get-wdays (ts)
13370 "Get the deadline lead time appropriate for timestring TS."
13371 (cond
13372 ((<= org-deadline-warning-days 0)
13373 ;; 0 or negative, enforce this value no matter what
13374 (- org-deadline-warning-days))
13375 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13376 ;; lead time is specified.
13377 (floor (* (string-to-number (match-string 1 ts))
13378 (cdr (assoc (match-string 2 ts)
13379 '(("d" . 1) ("w" . 7)
13380 ("m" . 30.4) ("y" . 365.25)))))))
13381 ;; go for the default.
13382 (t org-deadline-warning-days)))
13384 (defun org-calendar-select-mouse (ev)
13385 "Return to `org-read-date' with the date currently selected.
13386 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13387 (interactive "e")
13388 (mouse-set-point ev)
13389 (when (calendar-cursor-to-date)
13390 (let* ((date (calendar-cursor-to-date))
13391 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13392 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13393 (if (active-minibuffer-window) (exit-minibuffer))))
13395 (defun org-check-deadlines (ndays)
13396 "Check if there are any deadlines due or past due.
13397 A deadline is considered due if it happens within `org-deadline-warning-days'
13398 days from today's date. If the deadline appears in an entry marked DONE,
13399 it is not shown. The prefix arg NDAYS can be used to test that many
13400 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13401 (interactive "P")
13402 (let* ((org-warn-days
13403 (cond
13404 ((equal ndays '(4)) 100000)
13405 (ndays (prefix-numeric-value ndays))
13406 (t (abs org-deadline-warning-days))))
13407 (case-fold-search nil)
13408 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13409 (callback
13410 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13412 (message "%d deadlines past-due or due within %d days"
13413 (org-occur regexp nil callback)
13414 org-warn-days)))
13416 (defun org-check-before-date (date)
13417 "Check if there are deadlines or scheduled entries before DATE."
13418 (interactive (list (org-read-date)))
13419 (let ((case-fold-search nil)
13420 (regexp (concat "\\<\\(" org-deadline-string
13421 "\\|" org-scheduled-string
13422 "\\) *<\\([^>]+\\)>"))
13423 (callback
13424 (lambda () (time-less-p
13425 (org-time-string-to-time (match-string 2))
13426 (org-time-string-to-time date)))))
13427 (message "%d entries before %s"
13428 (org-occur regexp nil callback) date)))
13430 (defun org-check-after-date (date)
13431 "Check if there are deadlines or scheduled entries after DATE."
13432 (interactive (list (org-read-date)))
13433 (let ((case-fold-search nil)
13434 (regexp (concat "\\<\\(" org-deadline-string
13435 "\\|" org-scheduled-string
13436 "\\) *<\\([^>]+\\)>"))
13437 (callback
13438 (lambda () (not
13439 (time-less-p
13440 (org-time-string-to-time (match-string 2))
13441 (org-time-string-to-time date))))))
13442 (message "%d entries after %s"
13443 (org-occur regexp nil callback) date)))
13445 (defun org-evaluate-time-range (&optional to-buffer)
13446 "Evaluate a time range by computing the difference between start and end.
13447 Normally the result is just printed in the echo area, but with prefix arg
13448 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13449 If the time range is actually in a table, the result is inserted into the
13450 next column.
13451 For time difference computation, a year is assumed to be exactly 365
13452 days in order to avoid rounding problems."
13453 (interactive "P")
13455 (org-clock-update-time-maybe)
13456 (save-excursion
13457 (unless (org-at-date-range-p t)
13458 (goto-char (point-at-bol))
13459 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13460 (if (not (org-at-date-range-p t))
13461 (error "Not at a time-stamp range, and none found in current line")))
13462 (let* ((ts1 (match-string 1))
13463 (ts2 (match-string 2))
13464 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13465 (match-end (match-end 0))
13466 (time1 (org-time-string-to-time ts1))
13467 (time2 (org-time-string-to-time ts2))
13468 (t1 (org-float-time time1))
13469 (t2 (org-float-time time2))
13470 (diff (abs (- t2 t1)))
13471 (negative (< (- t2 t1) 0))
13472 ;; (ys (floor (* 365 24 60 60)))
13473 (ds (* 24 60 60))
13474 (hs (* 60 60))
13475 (fy "%dy %dd %02d:%02d")
13476 (fy1 "%dy %dd")
13477 (fd "%dd %02d:%02d")
13478 (fd1 "%dd")
13479 (fh "%02d:%02d")
13480 y d h m align)
13481 (if havetime
13482 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13484 d (floor (/ diff ds)) diff (mod diff ds)
13485 h (floor (/ diff hs)) diff (mod diff hs)
13486 m (floor (/ diff 60)))
13487 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13489 d (floor (+ (/ diff ds) 0.5))
13490 h 0 m 0))
13491 (if (not to-buffer)
13492 (message "%s" (org-make-tdiff-string y d h m))
13493 (if (org-at-table-p)
13494 (progn
13495 (goto-char match-end)
13496 (setq align t)
13497 (and (looking-at " *|") (goto-char (match-end 0))))
13498 (goto-char match-end))
13499 (if (looking-at
13500 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13501 (replace-match ""))
13502 (if negative (insert " -"))
13503 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13504 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13505 (insert " " (format fh h m))))
13506 (if align (org-table-align))
13507 (message "Time difference inserted")))))
13509 (defun org-make-tdiff-string (y d h m)
13510 (let ((fmt "")
13511 (l nil))
13512 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13513 l (push y l)))
13514 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13515 l (push d l)))
13516 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13517 l (push h l)))
13518 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13519 l (push m l)))
13520 (apply 'format fmt (nreverse l))))
13522 (defun org-time-string-to-time (s)
13523 (apply 'encode-time (org-parse-time-string s)))
13524 (defun org-time-string-to-seconds (s)
13525 (org-float-time (org-time-string-to-time s)))
13527 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13528 "Convert a time stamp to an absolute day number.
13529 If there is a specifyer for a cyclic time stamp, get the closest date to
13530 DAYNR.
13531 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13532 the variable date is bound by the calendar when this is called."
13533 (cond
13534 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13535 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13536 daynr
13537 (+ daynr 1000)))
13538 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13539 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13540 (time-to-days (current-time))) (match-string 0 s)
13541 prefer show-all))
13542 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13544 (defun org-days-to-iso-week (days)
13545 "Return the iso week number."
13546 (require 'cal-iso)
13547 (car (calendar-iso-from-absolute days)))
13549 (defun org-small-year-to-year (year)
13550 "Convert 2-digit years into 4-digit years.
13551 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13552 The year 2000 cannot be abbreviated. Any year larger than 99
13553 is returned unchanged."
13554 (if (< year 38)
13555 (setq year (+ 2000 year))
13556 (if (< year 100)
13557 (setq year (+ 1900 year))))
13558 year)
13560 (defun org-time-from-absolute (d)
13561 "Return the time corresponding to date D.
13562 D may be an absolute day number, or a calendar-type list (month day year)."
13563 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13564 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13566 (defun org-calendar-holiday ()
13567 "List of holidays, for Diary display in Org-mode."
13568 (require 'holidays)
13569 (let ((hl (funcall
13570 (if (fboundp 'calendar-check-holidays)
13571 'calendar-check-holidays 'check-calendar-holidays) date)))
13572 (if hl (mapconcat 'identity hl "; "))))
13574 (defun org-diary-sexp-entry (sexp entry date)
13575 "Process a SEXP diary ENTRY for DATE."
13576 (require 'diary-lib)
13577 (let ((result (if calendar-debug-sexp
13578 (let ((stack-trace-on-error t))
13579 (eval (car (read-from-string sexp))))
13580 (condition-case nil
13581 (eval (car (read-from-string sexp)))
13582 (error
13583 (beep)
13584 (message "Bad sexp at line %d in %s: %s"
13585 (org-current-line)
13586 (buffer-file-name) sexp)
13587 (sleep-for 2))))))
13588 (cond ((stringp result) result)
13589 ((and (consp result)
13590 (stringp (cdr result))) (cdr result))
13591 (result entry)
13592 (t nil))))
13594 (defun org-diary-to-ical-string (frombuf)
13595 "Get iCalendar entries from diary entries in buffer FROMBUF.
13596 This uses the icalendar.el library."
13597 (let* ((tmpdir (if (featurep 'xemacs)
13598 (temp-directory)
13599 temporary-file-directory))
13600 (tmpfile (make-temp-name
13601 (expand-file-name "orgics" tmpdir)))
13602 buf rtn b e)
13603 (with-current-buffer frombuf
13604 (icalendar-export-region (point-min) (point-max) tmpfile)
13605 (setq buf (find-buffer-visiting tmpfile))
13606 (set-buffer buf)
13607 (goto-char (point-min))
13608 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13609 (setq b (match-beginning 0)))
13610 (goto-char (point-max))
13611 (if (re-search-backward "^END:VEVENT" nil t)
13612 (setq e (match-end 0)))
13613 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13614 (kill-buffer buf)
13615 (delete-file tmpfile)
13616 rtn))
13618 (defun org-closest-date (start current change prefer show-all)
13619 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13620 When PREFER is `past' return a date that is either CURRENT or past.
13621 When PREFER is `future', return a date that is either CURRENT or future.
13622 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13623 ;; Make the proper lists from the dates
13624 (catch 'exit
13625 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13626 dn dw sday cday n1 n2 n0
13627 d m y y1 y2 date1 date2 nmonths nm ny m2)
13629 (setq start (org-date-to-gregorian start)
13630 current (org-date-to-gregorian
13631 (if show-all
13632 current
13633 (time-to-days (current-time))))
13634 sday (calendar-absolute-from-gregorian start)
13635 cday (calendar-absolute-from-gregorian current))
13637 (if (<= cday sday) (throw 'exit sday))
13639 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13640 (setq dn (string-to-number (match-string 1 change))
13641 dw (cdr (assoc (match-string 2 change) a1)))
13642 (error "Invalid change specifyer: %s" change))
13643 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13644 (cond
13645 ((eq dw 'day)
13646 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13647 n2 (+ n1 dn)))
13648 ((eq dw 'year)
13649 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13650 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13651 (setq date1 (list m d y1)
13652 n1 (calendar-absolute-from-gregorian date1)
13653 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13654 n2 (calendar-absolute-from-gregorian date2)))
13655 ((eq dw 'month)
13656 ;; approx number of month between the two dates
13657 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13658 ;; How often does dn fit in there?
13659 (setq d (nth 1 start) m (car start) y (nth 2 start)
13660 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13661 m (+ m nm)
13662 ny (floor (/ m 12))
13663 y (+ y ny)
13664 m (- m (* ny 12)))
13665 (while (> m 12) (setq m (- m 12) y (1+ y)))
13666 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13667 (setq m2 (+ m dn) y2 y)
13668 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13669 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13670 (while (<= n2 cday)
13671 (setq n1 n2 m m2 y y2)
13672 (setq m2 (+ m dn) y2 y)
13673 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13674 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13675 ;; Make sure n1 is the earlier date
13676 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13677 (if show-all
13678 (cond
13679 ((eq prefer 'past) (if (= cday n2) n2 n1))
13680 ((eq prefer 'future) (if (= cday n1) n1 n2))
13681 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13682 (cond
13683 ((eq prefer 'past) (if (= cday n2) n2 n1))
13684 ((eq prefer 'future) (if (= cday n1) n1 n2))
13685 (t (if (= cday n1) n1 n2)))))))
13687 (defun org-date-to-gregorian (date)
13688 "Turn any specification of DATE into a gregorian date for the calendar."
13689 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13690 ((and (listp date) (= (length date) 3)) date)
13691 ((stringp date)
13692 (setq date (org-parse-time-string date))
13693 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13694 ((listp date)
13695 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13697 (defun org-parse-time-string (s &optional nodefault)
13698 "Parse the standard Org-mode time string.
13699 This should be a lot faster than the normal `parse-time-string'.
13700 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13701 hour and minute fields will be nil if not given."
13702 (if (string-match org-ts-regexp0 s)
13703 (list 0
13704 (if (or (match-beginning 8) (not nodefault))
13705 (string-to-number (or (match-string 8 s) "0")))
13706 (if (or (match-beginning 7) (not nodefault))
13707 (string-to-number (or (match-string 7 s) "0")))
13708 (string-to-number (match-string 4 s))
13709 (string-to-number (match-string 3 s))
13710 (string-to-number (match-string 2 s))
13711 nil nil nil)
13712 (error "Not a standard Org-mode time string: %s" s)))
13714 (defun org-timestamp-up (&optional arg)
13715 "Increase the date item at the cursor by one.
13716 If the cursor is on the year, change the year. If it is on the month or
13717 the day, change that.
13718 With prefix ARG, change by that many units."
13719 (interactive "p")
13720 (org-timestamp-change (prefix-numeric-value arg)))
13722 (defun org-timestamp-down (&optional arg)
13723 "Decrease the date item at the cursor by one.
13724 If the cursor is on the year, change the year. If it is on the month or
13725 the day, change that.
13726 With prefix ARG, change by that many units."
13727 (interactive "p")
13728 (org-timestamp-change (- (prefix-numeric-value arg))))
13730 (defun org-timestamp-up-day (&optional arg)
13731 "Increase the date in the time stamp by one day.
13732 With prefix ARG, change that many days."
13733 (interactive "p")
13734 (if (and (not (org-at-timestamp-p t))
13735 (org-on-heading-p))
13736 (org-todo 'up)
13737 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13739 (defun org-timestamp-down-day (&optional arg)
13740 "Decrease the date in the time stamp by one day.
13741 With prefix ARG, change that many days."
13742 (interactive "p")
13743 (if (and (not (org-at-timestamp-p t))
13744 (org-on-heading-p))
13745 (org-todo 'down)
13746 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13748 (defun org-at-timestamp-p (&optional inactive-ok)
13749 "Determine if the cursor is in or at a timestamp."
13750 (interactive)
13751 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13752 (pos (point))
13753 (ans (or (looking-at tsr)
13754 (save-excursion
13755 (skip-chars-backward "^[<\n\r\t")
13756 (if (> (point) (point-min)) (backward-char 1))
13757 (and (looking-at tsr)
13758 (> (- (match-end 0) pos) -1))))))
13759 (and ans
13760 (boundp 'org-ts-what)
13761 (setq org-ts-what
13762 (cond
13763 ((= pos (match-beginning 0)) 'bracket)
13764 ((= pos (1- (match-end 0))) 'bracket)
13765 ((org-pos-in-match-range pos 2) 'year)
13766 ((org-pos-in-match-range pos 3) 'month)
13767 ((org-pos-in-match-range pos 7) 'hour)
13768 ((org-pos-in-match-range pos 8) 'minute)
13769 ((or (org-pos-in-match-range pos 4)
13770 (org-pos-in-match-range pos 5)) 'day)
13771 ((and (> pos (or (match-end 8) (match-end 5)))
13772 (< pos (match-end 0)))
13773 (- pos (or (match-end 8) (match-end 5))))
13774 (t 'day))))
13775 ans))
13777 (defun org-toggle-timestamp-type ()
13778 "Toggle the type (<active> or [inactive]) of a time stamp."
13779 (interactive)
13780 (when (org-at-timestamp-p t)
13781 (let ((beg (match-beginning 0)) (end (match-end 0))
13782 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13783 (save-excursion
13784 (goto-char beg)
13785 (while (re-search-forward "[][<>]" end t)
13786 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13787 t t)))
13788 (message "Timestamp is now %sactive"
13789 (if (equal (char-after beg) ?<) "" "in")))))
13791 (defun org-timestamp-change (n &optional what)
13792 "Change the date in the time stamp at point.
13793 The date will be changed by N times WHAT. WHAT can be `day', `month',
13794 `year', `minute', `second'. If WHAT is not given, the cursor position
13795 in the timestamp determines what will be changed."
13796 (let ((pos (point))
13797 with-hm inactive
13798 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13799 org-ts-what
13800 extra rem
13801 ts time time0)
13802 (if (not (org-at-timestamp-p t))
13803 (error "Not at a timestamp"))
13804 (if (and (not what) (eq org-ts-what 'bracket))
13805 (org-toggle-timestamp-type)
13806 (if (and (not what) (not (eq org-ts-what 'day))
13807 org-display-custom-times
13808 (get-text-property (point) 'display)
13809 (not (get-text-property (1- (point)) 'display)))
13810 (setq org-ts-what 'day))
13811 (setq org-ts-what (or what org-ts-what)
13812 inactive (= (char-after (match-beginning 0)) ?\[)
13813 ts (match-string 0))
13814 (replace-match "")
13815 (if (string-match
13816 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13818 (setq extra (match-string 1 ts)))
13819 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13820 (setq with-hm t))
13821 (setq time0 (org-parse-time-string ts))
13822 (when (and (eq org-ts-what 'minute)
13823 (eq current-prefix-arg nil))
13824 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13825 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13826 (setcar (cdr time0) (+ (nth 1 time0)
13827 (if (> n 0) (- rem) (- dm rem))))))
13828 (setq time
13829 (encode-time (or (car time0) 0)
13830 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13831 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13832 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13833 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13834 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13835 (nthcdr 6 time0)))
13836 (when (and (member org-ts-what '(hour minute))
13837 extra
13838 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13839 (setq extra (org-modify-ts-extra
13840 extra
13841 (if (eq org-ts-what 'hour) 2 5)
13842 n dm)))
13843 (when (integerp org-ts-what)
13844 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13845 (if (eq what 'calendar)
13846 (let ((cal-date (org-get-date-from-calendar)))
13847 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13848 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13849 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13850 (setcar time0 (or (car time0) 0))
13851 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13852 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13853 (setq time (apply 'encode-time time0))))
13854 (setq org-last-changed-timestamp
13855 (org-insert-time-stamp time with-hm inactive nil nil extra))
13856 (org-clock-update-time-maybe)
13857 (goto-char pos)
13858 ;; Try to recenter the calendar window, if any
13859 (if (and org-calendar-follow-timestamp-change
13860 (get-buffer-window "*Calendar*" t)
13861 (memq org-ts-what '(day month year)))
13862 (org-recenter-calendar (time-to-days time))))))
13864 (defun org-modify-ts-extra (s pos n dm)
13865 "Change the different parts of the lead-time and repeat fields in timestamp."
13866 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13867 ng h m new rem)
13868 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13869 (cond
13870 ((or (org-pos-in-match-range pos 2)
13871 (org-pos-in-match-range pos 3))
13872 (setq m (string-to-number (match-string 3 s))
13873 h (string-to-number (match-string 2 s)))
13874 (if (org-pos-in-match-range pos 2)
13875 (setq h (+ h n))
13876 (setq n (* dm (org-no-warnings (signum n))))
13877 (when (not (= 0 (setq rem (% m dm))))
13878 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13879 (setq m (+ m n)))
13880 (if (< m 0) (setq m (+ m 60) h (1- h)))
13881 (if (> m 59) (setq m (- m 60) h (1+ h)))
13882 (setq h (min 24 (max 0 h)))
13883 (setq ng 1 new (format "-%02d:%02d" h m)))
13884 ((org-pos-in-match-range pos 6)
13885 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13886 ((org-pos-in-match-range pos 5)
13887 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13889 ((org-pos-in-match-range pos 9)
13890 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13891 ((org-pos-in-match-range pos 8)
13892 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13894 (when ng
13895 (setq s (concat
13896 (substring s 0 (match-beginning ng))
13898 (substring s (match-end ng))))))
13901 (defun org-recenter-calendar (date)
13902 "If the calendar is visible, recenter it to DATE."
13903 (let* ((win (selected-window))
13904 (cwin (get-buffer-window "*Calendar*" t))
13905 (calendar-move-hook nil))
13906 (when cwin
13907 (select-window cwin)
13908 (calendar-goto-date (if (listp date) date
13909 (calendar-gregorian-from-absolute date)))
13910 (select-window win))))
13912 (defun org-goto-calendar (&optional arg)
13913 "Go to the Emacs calendar at the current date.
13914 If there is a time stamp in the current line, go to that date.
13915 A prefix ARG can be used to force the current date."
13916 (interactive "P")
13917 (let ((tsr org-ts-regexp) diff
13918 (calendar-move-hook nil)
13919 (calendar-view-holidays-initially-flag nil)
13920 (view-calendar-holidays-initially nil)
13921 (calendar-view-diary-initially-flag nil)
13922 (view-diary-entries-initially nil))
13923 (if (or (org-at-timestamp-p)
13924 (save-excursion
13925 (beginning-of-line 1)
13926 (looking-at (concat ".*" tsr))))
13927 (let ((d1 (time-to-days (current-time)))
13928 (d2 (time-to-days
13929 (org-time-string-to-time (match-string 1)))))
13930 (setq diff (- d2 d1))))
13931 (calendar)
13932 (calendar-goto-today)
13933 (if (and diff (not arg)) (calendar-forward-day diff))))
13935 (defun org-get-date-from-calendar ()
13936 "Return a list (month day year) of date at point in calendar."
13937 (with-current-buffer "*Calendar*"
13938 (save-match-data
13939 (calendar-cursor-to-date))))
13941 (defun org-date-from-calendar ()
13942 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13943 If there is already a time stamp at the cursor position, update it."
13944 (interactive)
13945 (if (org-at-timestamp-p t)
13946 (org-timestamp-change 0 'calendar)
13947 (let ((cal-date (org-get-date-from-calendar)))
13948 (org-insert-time-stamp
13949 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13951 (defun org-minutes-to-hh:mm-string (m)
13952 "Compute H:MM from a number of minutes."
13953 (let ((h (/ m 60)))
13954 (setq m (- m (* 60 h)))
13955 (format org-time-clocksum-format h m)))
13957 (defun org-hh:mm-string-to-minutes (s)
13958 "Convert a string H:MM to a number of minutes.
13959 If the string is just a number, interprete it as minutes.
13960 In fact, the first hh:mm or number in the string will be taken,
13961 there can be extra stuff in the string.
13962 If no number is found, the return value is 0."
13963 (cond
13964 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13965 (+ (* (string-to-number (match-string 1 s)) 60)
13966 (string-to-number (match-string 2 s))))
13967 ((string-match "\\([0-9]+\\)" s)
13968 (string-to-number (match-string 1 s)))
13969 (t 0)))
13971 ;;;; Files
13973 (defun org-save-all-org-buffers ()
13974 "Save all Org-mode buffers without user confirmation."
13975 (interactive)
13976 (message "Saving all Org-mode buffers...")
13977 (save-some-buffers t 'org-mode-p)
13978 (when (featurep 'org-id) (org-id-locations-save))
13979 (message "Saving all Org-mode buffers... done"))
13981 (defun org-revert-all-org-buffers ()
13982 "Revert all Org-mode buffers.
13983 Prompt for confirmation when there are unsaved changes.
13984 Be sure you know what you are doing before letting this function
13985 overwrite your changes.
13987 This function is useful in a setup where one tracks org files
13988 with a version control system, to revert on one machine after pulling
13989 changes from another. I believe the procedure must be like this:
13991 1. M-x org-save-all-org-buffers
13992 2. Pull changes from the other machine, resolve conflicts
13993 3. M-x org-revert-all-org-buffers"
13994 (interactive)
13995 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13996 (error "Abort"))
13997 (save-excursion
13998 (save-window-excursion
13999 (mapc
14000 (lambda (b)
14001 (when (and (with-current-buffer b (org-mode-p))
14002 (with-current-buffer b buffer-file-name))
14003 (switch-to-buffer b)
14004 (revert-buffer t 'no-confirm)))
14005 (buffer-list))
14006 (when (and (featurep 'org-id) org-id-track-globally)
14007 (org-id-locations-load)))))
14009 ;;;; Agenda files
14011 ;;;###autoload
14012 (defun org-iswitchb (&optional arg)
14013 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14014 With a prefix argument, restrict available to files.
14015 With two prefix arguments, restrict available buffers to agenda files."
14016 (interactive "P")
14017 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14018 ((equal arg '(16)) (org-buffer-list 'agenda))
14019 (t (org-buffer-list)))))
14020 (switch-to-buffer
14021 (org-icompleting-read "Org buffer: "
14022 (mapcar 'list (mapcar 'buffer-name blist))
14023 nil t))))
14025 ;;;###autoload
14026 (defalias 'org-ido-switchb 'org-iswitchb)
14028 (defun org-buffer-list (&optional predicate exclude-tmp)
14029 "Return a list of Org buffers.
14030 PREDICATE can be `export', `files' or `agenda'.
14032 export restrict the list to Export buffers.
14033 files restrict the list to buffers visiting Org files.
14034 agenda restrict the list to buffers visiting agenda files.
14036 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14037 (let* ((bfn nil)
14038 (agenda-files (and (eq predicate 'agenda)
14039 (mapcar 'file-truename (org-agenda-files t))))
14040 (filter
14041 (cond
14042 ((eq predicate 'files)
14043 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14044 ((eq predicate 'export)
14045 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14046 ((eq predicate 'agenda)
14047 (lambda (b)
14048 (with-current-buffer b
14049 (and (eq major-mode 'org-mode)
14050 (setq bfn (buffer-file-name b))
14051 (member (file-truename bfn) agenda-files)))))
14052 (t (lambda (b) (with-current-buffer b
14053 (or (eq major-mode 'org-mode)
14054 (string-match "\*Org .*Export"
14055 (buffer-name b)))))))))
14056 (delq nil
14057 (mapcar
14058 (lambda(b)
14059 (if (and (funcall filter b)
14060 (or (not exclude-tmp)
14061 (not (string-match "tmp" (buffer-name b)))))
14063 nil))
14064 (buffer-list)))))
14066 (defun org-agenda-files (&optional unrestricted archives)
14067 "Get the list of agenda files.
14068 Optional UNRESTRICTED means return the full list even if a restriction
14069 is currently in place.
14070 When ARCHIVES is t, include all archive files hat are really being
14071 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14072 `org-agenda-archives-mode' is t."
14073 (let ((files
14074 (cond
14075 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14076 ((stringp org-agenda-files) (org-read-agenda-file-list))
14077 ((listp org-agenda-files) org-agenda-files)
14078 (t (error "Invalid value of `org-agenda-files'")))))
14079 (setq files (apply 'append
14080 (mapcar (lambda (f)
14081 (if (file-directory-p f)
14082 (directory-files
14083 f t org-agenda-file-regexp)
14084 (list f)))
14085 files)))
14086 (when org-agenda-skip-unavailable-files
14087 (setq files (delq nil
14088 (mapcar (function
14089 (lambda (file)
14090 (and (file-readable-p file) file)))
14091 files))))
14092 (when (or (eq archives t)
14093 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14094 (setq files (org-add-archive-files files)))
14095 files))
14097 (defun org-edit-agenda-file-list ()
14098 "Edit the list of agenda files.
14099 Depending on setup, this either uses customize to edit the variable
14100 `org-agenda-files', or it visits the file that is holding the list. In the
14101 latter case, the buffer is set up in a way that saving it automatically kills
14102 the buffer and restores the previous window configuration."
14103 (interactive)
14104 (if (stringp org-agenda-files)
14105 (let ((cw (current-window-configuration)))
14106 (find-file org-agenda-files)
14107 (org-set-local 'org-window-configuration cw)
14108 (org-add-hook 'after-save-hook
14109 (lambda ()
14110 (set-window-configuration
14111 (prog1 org-window-configuration
14112 (kill-buffer (current-buffer))))
14113 (org-install-agenda-files-menu)
14114 (message "New agenda file list installed"))
14115 nil 'local)
14116 (message "%s" (substitute-command-keys
14117 "Edit list and finish with \\[save-buffer]")))
14118 (customize-variable 'org-agenda-files)))
14120 (defun org-store-new-agenda-file-list (list)
14121 "Set new value for the agenda file list and save it correctly."
14122 (if (stringp org-agenda-files)
14123 (let ((f org-agenda-files) b)
14124 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14125 (with-temp-file f
14126 (insert (mapconcat 'identity list "\n") "\n")))
14127 (let ((org-mode-hook nil) (org-inhibit-startup t)
14128 (org-insert-mode-line-in-empty-file nil))
14129 (setq org-agenda-files list)
14130 (customize-save-variable 'org-agenda-files org-agenda-files))))
14132 (defun org-read-agenda-file-list ()
14133 "Read the list of agenda files from a file."
14134 (when (file-directory-p org-agenda-files)
14135 (error "`org-agenda-files' cannot be a single directory"))
14136 (when (stringp org-agenda-files)
14137 (with-temp-buffer
14138 (insert-file-contents org-agenda-files)
14139 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14142 ;;;###autoload
14143 (defun org-cycle-agenda-files ()
14144 "Cycle through the files in `org-agenda-files'.
14145 If the current buffer visits an agenda file, find the next one in the list.
14146 If the current buffer does not, find the first agenda file."
14147 (interactive)
14148 (let* ((fs (org-agenda-files t))
14149 (files (append fs (list (car fs))))
14150 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14151 file)
14152 (unless files (error "No agenda files"))
14153 (catch 'exit
14154 (while (setq file (pop files))
14155 (if (equal (file-truename file) tcf)
14156 (when (car files)
14157 (find-file (car files))
14158 (throw 'exit t))))
14159 (find-file (car fs)))
14160 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14162 (defun org-agenda-file-to-front (&optional to-end)
14163 "Move/add the current file to the top of the agenda file list.
14164 If the file is not present in the list, it is added to the front. If it is
14165 present, it is moved there. With optional argument TO-END, add/move to the
14166 end of the list."
14167 (interactive "P")
14168 (let ((org-agenda-skip-unavailable-files nil)
14169 (file-alist (mapcar (lambda (x)
14170 (cons (file-truename x) x))
14171 (org-agenda-files t)))
14172 (ctf (file-truename buffer-file-name))
14173 x had)
14174 (setq x (assoc ctf file-alist) had x)
14176 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14177 (if to-end
14178 (setq file-alist (append (delq x file-alist) (list x)))
14179 (setq file-alist (cons x (delq x file-alist))))
14180 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14181 (org-install-agenda-files-menu)
14182 (message "File %s to %s of agenda file list"
14183 (if had "moved" "added") (if to-end "end" "front"))))
14185 (defun org-remove-file (&optional file)
14186 "Remove current file from the list of files in variable `org-agenda-files'.
14187 These are the files which are being checked for agenda entries.
14188 Optional argument FILE means, use this file instead of the current."
14189 (interactive)
14190 (let* ((org-agenda-skip-unavailable-files nil)
14191 (file (or file buffer-file-name))
14192 (true-file (file-truename file))
14193 (afile (abbreviate-file-name file))
14194 (files (delq nil (mapcar
14195 (lambda (x)
14196 (if (equal true-file
14197 (file-truename x))
14198 nil x))
14199 (org-agenda-files t)))))
14200 (if (not (= (length files) (length (org-agenda-files t))))
14201 (progn
14202 (org-store-new-agenda-file-list files)
14203 (org-install-agenda-files-menu)
14204 (message "Removed file: %s" afile))
14205 (message "File was not in list: %s (not removed)" afile))))
14207 (defun org-file-menu-entry (file)
14208 (vector file (list 'find-file file) t))
14210 (defun org-check-agenda-file (file)
14211 "Make sure FILE exists. If not, ask user what to do."
14212 (when (not (file-exists-p file))
14213 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14214 (abbreviate-file-name file))
14215 (let ((r (downcase (read-char-exclusive))))
14216 (cond
14217 ((equal r ?r)
14218 (org-remove-file file)
14219 (throw 'nextfile t))
14220 (t (error "Abort"))))))
14222 (defun org-get-agenda-file-buffer (file)
14223 "Get a buffer visiting FILE. If the buffer needs to be created, add
14224 it to the list of buffers which might be released later."
14225 (let ((buf (org-find-base-buffer-visiting file)))
14226 (if buf
14227 buf ; just return it
14228 ;; Make a new buffer and remember it
14229 (setq buf (find-file-noselect file))
14230 (if buf (push buf org-agenda-new-buffers))
14231 buf)))
14233 (defun org-release-buffers (blist)
14234 "Release all buffers in list, asking the user for confirmation when needed.
14235 When a buffer is unmodified, it is just killed. When modified, it is saved
14236 \(if the user agrees) and then killed."
14237 (let (buf file)
14238 (while (setq buf (pop blist))
14239 (setq file (buffer-file-name buf))
14240 (when (and (buffer-modified-p buf)
14241 file
14242 (y-or-n-p (format "Save file %s? " file)))
14243 (with-current-buffer buf (save-buffer)))
14244 (kill-buffer buf))))
14246 (defun org-prepare-agenda-buffers (files)
14247 "Create buffers for all agenda files, protect archived trees and comments."
14248 (interactive)
14249 (let ((pa '(:org-archived t))
14250 (pc '(:org-comment t))
14251 (pall '(:org-archived t :org-comment t))
14252 (inhibit-read-only t)
14253 (rea (concat ":" org-archive-tag ":"))
14254 bmp file re)
14255 (save-excursion
14256 (save-restriction
14257 (while (setq file (pop files))
14258 (catch 'nextfile
14259 (if (bufferp file)
14260 (set-buffer file)
14261 (org-check-agenda-file file)
14262 (set-buffer (org-get-agenda-file-buffer file)))
14263 (widen)
14264 (setq bmp (buffer-modified-p))
14265 (org-refresh-category-properties)
14266 (setq org-todo-keywords-for-agenda
14267 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14268 (setq org-done-keywords-for-agenda
14269 (append org-done-keywords-for-agenda org-done-keywords))
14270 (setq org-todo-keyword-alist-for-agenda
14271 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14272 (setq org-drawers-for-agenda
14273 (append org-drawers-for-agenda org-drawers))
14274 (setq org-tag-alist-for-agenda
14275 (append org-tag-alist-for-agenda org-tag-alist))
14277 (save-excursion
14278 (remove-text-properties (point-min) (point-max) pall)
14279 (when org-agenda-skip-archived-trees
14280 (goto-char (point-min))
14281 (while (re-search-forward rea nil t)
14282 (if (org-on-heading-p t)
14283 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14284 (goto-char (point-min))
14285 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14286 (while (re-search-forward re nil t)
14287 (add-text-properties
14288 (match-beginning 0) (org-end-of-subtree t) pc)))
14289 (set-buffer-modified-p bmp)))))
14290 (setq org-todo-keyword-alist-for-agenda
14291 (org-uniquify org-todo-keyword-alist-for-agenda)
14292 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14294 ;;;; Embedded LaTeX
14296 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14297 "Keymap for the minor `org-cdlatex-mode'.")
14299 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14300 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14301 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14302 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14303 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14305 (defvar org-cdlatex-texmathp-advice-is-done nil
14306 "Flag remembering if we have applied the advice to texmathp already.")
14308 (define-minor-mode org-cdlatex-mode
14309 "Toggle the minor `org-cdlatex-mode'.
14310 This mode supports entering LaTeX environment and math in LaTeX fragments
14311 in Org-mode.
14312 \\{org-cdlatex-mode-map}"
14313 nil " OCDL" nil
14314 (when org-cdlatex-mode (require 'cdlatex))
14315 (unless org-cdlatex-texmathp-advice-is-done
14316 (setq org-cdlatex-texmathp-advice-is-done t)
14317 (defadvice texmathp (around org-math-always-on activate)
14318 "Always return t in org-mode buffers.
14319 This is because we want to insert math symbols without dollars even outside
14320 the LaTeX math segments. If Orgmode thinks that point is actually inside
14321 an embedded LaTeX fragment, let texmathp do its job.
14322 \\[org-cdlatex-mode-map]"
14323 (interactive)
14324 (let (p)
14325 (cond
14326 ((not (org-mode-p)) ad-do-it)
14327 ((eq this-command 'cdlatex-math-symbol)
14328 (setq ad-return-value t
14329 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14331 (let ((p (org-inside-LaTeX-fragment-p)))
14332 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14333 (setq ad-return-value t
14334 texmathp-why '("Org-mode embedded math" . 0))
14335 (if p ad-do-it)))))))))
14337 (defun turn-on-org-cdlatex ()
14338 "Unconditionally turn on `org-cdlatex-mode'."
14339 (org-cdlatex-mode 1))
14341 (defun org-inside-LaTeX-fragment-p ()
14342 "Test if point is inside a LaTeX fragment.
14343 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14344 sequence appearing also before point.
14345 Even though the matchers for math are configurable, this function assumes
14346 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14347 delimiters are skipped when they have been removed by customization.
14348 The return value is nil, or a cons cell with the delimiter and
14349 and the position of this delimiter.
14351 This function does a reasonably good job, but can locally be fooled by
14352 for example currency specifications. For example it will assume being in
14353 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14354 fragments that are properly closed, but during editing, we have to live
14355 with the uncertainty caused by missing closing delimiters. This function
14356 looks only before point, not after."
14357 (catch 'exit
14358 (let ((pos (point))
14359 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14360 (lim (progn
14361 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14362 (point)))
14363 dd-on str (start 0) m re)
14364 (goto-char pos)
14365 (when dodollar
14366 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14367 re (nth 1 (assoc "$" org-latex-regexps)))
14368 (while (string-match re str start)
14369 (cond
14370 ((= (match-end 0) (length str))
14371 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14372 ((= (match-end 0) (- (length str) 5))
14373 (throw 'exit nil))
14374 (t (setq start (match-end 0))))))
14375 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14376 (goto-char pos)
14377 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14378 (and (match-beginning 2) (throw 'exit nil))
14379 ;; count $$
14380 (while (re-search-backward "\\$\\$" lim t)
14381 (setq dd-on (not dd-on)))
14382 (goto-char pos)
14383 (if dd-on (cons "$$" m))))))
14386 (defun org-try-cdlatex-tab ()
14387 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14388 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14389 - inside a LaTeX fragment, or
14390 - after the first word in a line, where an abbreviation expansion could
14391 insert a LaTeX environment."
14392 (when org-cdlatex-mode
14393 (cond
14394 ((save-excursion
14395 (skip-chars-backward "a-zA-Z0-9*")
14396 (skip-chars-backward " \t")
14397 (bolp))
14398 (cdlatex-tab) t)
14399 ((org-inside-LaTeX-fragment-p)
14400 (cdlatex-tab) t)
14401 (t nil))))
14403 (defun org-cdlatex-underscore-caret (&optional arg)
14404 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14405 Revert to the normal definition outside of these fragments."
14406 (interactive "P")
14407 (if (org-inside-LaTeX-fragment-p)
14408 (call-interactively 'cdlatex-sub-superscript)
14409 (let (org-cdlatex-mode)
14410 (call-interactively (key-binding (vector last-input-event))))))
14412 (defun org-cdlatex-math-modify (&optional arg)
14413 "Execute `cdlatex-math-modify' in LaTeX fragments.
14414 Revert to the normal definition outside of these fragments."
14415 (interactive "P")
14416 (if (org-inside-LaTeX-fragment-p)
14417 (call-interactively 'cdlatex-math-modify)
14418 (let (org-cdlatex-mode)
14419 (call-interactively (key-binding (vector last-input-event))))))
14421 (defvar org-latex-fragment-image-overlays nil
14422 "List of overlays carrying the images of latex fragments.")
14423 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14425 (defun org-remove-latex-fragment-image-overlays ()
14426 "Remove all overlays with LaTeX fragment images in current buffer."
14427 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14428 (setq org-latex-fragment-image-overlays nil))
14430 (defun org-preview-latex-fragment (&optional subtree)
14431 "Preview the LaTeX fragment at point, or all locally or globally.
14432 If the cursor is in a LaTeX fragment, create the image and overlay
14433 it over the source code. If there is no fragment at point, display
14434 all fragments in the current text, from one headline to the next. With
14435 prefix SUBTREE, display all fragments in the current subtree. With a
14436 double prefix `C-u C-u', or when the cursor is before the first headline,
14437 display all fragments in the buffer.
14438 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14439 (interactive "P")
14440 (org-remove-latex-fragment-image-overlays)
14441 (save-excursion
14442 (save-restriction
14443 (let (beg end at msg)
14444 (cond
14445 ((or (equal subtree '(16))
14446 (not (save-excursion
14447 (re-search-backward (concat "^" outline-regexp) nil t))))
14448 (setq beg (point-min) end (point-max)
14449 msg "Creating images for buffer...%s"))
14450 ((equal subtree '(4))
14451 (org-back-to-heading)
14452 (setq beg (point) end (org-end-of-subtree t)
14453 msg "Creating images for subtree...%s"))
14455 (if (setq at (org-inside-LaTeX-fragment-p))
14456 (goto-char (max (point-min) (- (cdr at) 2)))
14457 (org-back-to-heading))
14458 (setq beg (point) end (progn (outline-next-heading) (point))
14459 msg (if at "Creating image...%s"
14460 "Creating images for entry...%s"))))
14461 (message msg "")
14462 (narrow-to-region beg end)
14463 (goto-char beg)
14464 (org-format-latex
14465 (concat "ltxpng/" (file-name-sans-extension
14466 (file-name-nondirectory
14467 buffer-file-name)))
14468 default-directory 'overlays msg at 'forbuffer)
14469 (message msg "done. Use `C-c C-c' to remove images.")))))
14471 (defvar org-latex-regexps
14472 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14473 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14474 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14475 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14476 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14477 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14478 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14479 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14480 "Regular expressions for matching embedded LaTeX.")
14482 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14483 "Replace LaTeX fragments with links to an image, and produce images.
14484 Some of the options can be changed using the variable
14485 `org-format-latex-options'."
14486 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14487 (let* ((prefixnodir (file-name-nondirectory prefix))
14488 (absprefix (expand-file-name prefix dir))
14489 (todir (file-name-directory absprefix))
14490 (opt org-format-latex-options)
14491 (matchers (plist-get opt :matchers))
14492 (re-list org-latex-regexps)
14493 (cnt 0) txt link beg end re e checkdir
14494 executables-checked
14495 m n block linkfile movefile ov)
14496 ;; Check if there are old images files with this prefix, and remove them
14497 (when (file-directory-p todir)
14498 (mapc 'delete-file
14499 (directory-files
14500 todir 'full
14501 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14502 ;; Check the different regular expressions
14503 (while (setq e (pop re-list))
14504 (setq m (car e) re (nth 1 e) n (nth 2 e)
14505 block (if (nth 3 e) "\n\n" ""))
14506 (when (member m matchers)
14507 (goto-char (point-min))
14508 (while (re-search-forward re nil t)
14509 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14510 (not (get-text-property (match-beginning n)
14511 'org-protected))
14512 (or (not overlays)
14513 (not (eq (get-char-property (match-beginning n)
14514 'org-overlay-type)
14515 'org-latex-overlay))))
14516 (setq txt (match-string n)
14517 beg (match-beginning n) end (match-end n)
14518 cnt (1+ cnt)
14519 linkfile (format "%s_%04d.png" prefix cnt)
14520 movefile (format "%s_%04d.png" absprefix cnt)
14521 link (concat block "[[file:" linkfile "]]" block))
14522 (if msg (message msg cnt))
14523 (goto-char beg)
14524 (unless checkdir ; make sure the directory exists
14525 (setq checkdir t)
14526 (or (file-directory-p todir) (make-directory todir)))
14528 (unless executables-checked
14529 (org-check-external-command
14530 "latex" "needed to convert LaTeX fragments to images")
14531 (org-check-external-command
14532 "dvipng" "needed to convert LaTeX fragments to images")
14533 (setq executables-checked t))
14535 (org-create-formula-image
14536 txt movefile opt forbuffer)
14537 (if overlays
14538 (progn
14539 (mapc (lambda (o)
14540 (if (eq (org-overlay-get o 'org-overlay-type)
14541 'org-latex-overlay)
14542 (org-delete-overlay o)))
14543 (org-overlays-in beg end))
14544 (setq ov (org-make-overlay beg end))
14545 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14546 (if (featurep 'xemacs)
14547 (progn
14548 (org-overlay-put ov 'invisible t)
14549 (org-overlay-put
14550 ov 'end-glyph
14551 (make-glyph (vector 'png :file movefile))))
14552 (org-overlay-put
14553 ov 'display
14554 (list 'image :type 'png :file movefile :ascent 'center)))
14555 (push ov org-latex-fragment-image-overlays)
14556 (goto-char end))
14557 (delete-region beg end)
14558 (insert link))))))))
14560 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14561 ;; This function borrows from Ganesh Swami's latex2png.el
14562 (defun org-create-formula-image (string tofile options buffer)
14563 "This calls dvipng."
14564 (require 'org-latex)
14565 (let* ((tmpdir (if (featurep 'xemacs)
14566 (temp-directory)
14567 temporary-file-directory))
14568 (texfilebase (make-temp-name
14569 (expand-file-name "orgtex" tmpdir)))
14570 (texfile (concat texfilebase ".tex"))
14571 (dvifile (concat texfilebase ".dvi"))
14572 (pngfile (concat texfilebase ".png"))
14573 (fnh (if (featurep 'xemacs)
14574 (font-height (get-face-font 'default))
14575 (face-attribute 'default :height nil)))
14576 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14577 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14578 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14579 "Black"))
14580 (bg (or (plist-get options (if buffer :background :html-background))
14581 "Transparent")))
14582 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14583 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14584 (with-temp-file texfile
14585 (insert org-format-latex-header
14586 (if org-export-latex-packages-alist
14587 (concat "\n"
14588 (mapconcat (lambda(p)
14589 (if (equal "" (car p))
14590 (format "\\usepackage{%s}" (cadr p))
14591 (format "\\usepackage[%s]{%s}"
14592 (car p) (cadr p))))
14593 org-export-latex-packages-alist "\n"))
14595 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14596 (let ((dir default-directory))
14597 (condition-case nil
14598 (progn
14599 (cd tmpdir)
14600 (call-process "latex" nil nil nil texfile))
14601 (error nil))
14602 (cd dir))
14603 (if (not (file-exists-p dvifile))
14604 (progn (message "Failed to create dvi file from %s" texfile) nil)
14605 (condition-case nil
14606 (call-process "dvipng" nil nil nil
14607 "-fg" fg "-bg" bg
14608 "-D" dpi
14609 ;;"-x" scale "-y" scale
14610 "-T" "tight"
14611 "-o" pngfile
14612 dvifile)
14613 (error nil))
14614 (if (not (file-exists-p pngfile))
14615 (progn (message "Failed to create png file from %s" texfile) nil)
14616 ;; Use the requested file name and clean up
14617 (copy-file pngfile tofile 'replace)
14618 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14619 (delete-file (concat texfilebase e)))
14620 pngfile))))
14622 (defun org-dvipng-color (attr)
14623 "Return an rgb color specification for dvipng."
14624 (apply 'format "rgb %s %s %s"
14625 (mapcar 'org-normalize-color
14626 (color-values (face-attribute 'default attr nil)))))
14628 (defun org-normalize-color (value)
14629 "Return string to be used as color value for an RGB component."
14630 (format "%g" (/ value 65535.0)))
14632 ;;;; Key bindings
14634 ;; Make `C-c C-x' a prefix key
14635 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14637 ;; TAB key with modifiers
14638 (org-defkey org-mode-map "\C-i" 'org-cycle)
14639 (org-defkey org-mode-map [(tab)] 'org-cycle)
14640 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14641 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14642 (org-defkey org-mode-map "\M-\t" 'org-complete)
14643 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14644 ;; The following line is necessary under Suse GNU/Linux
14645 (unless (featurep 'xemacs)
14646 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14647 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14648 (define-key org-mode-map [backtab] 'org-shifttab)
14650 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14651 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14652 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14654 ;; Cursor keys with modifiers
14655 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14656 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14657 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14658 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14660 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14661 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14662 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14663 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14665 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14666 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14667 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14668 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14670 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14671 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14673 ;;; Extra keys for tty access.
14674 ;; We only set them when really needed because otherwise the
14675 ;; menus don't show the simple keys
14677 (when (or org-use-extra-keys
14678 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14679 (not window-system))
14680 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14681 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14682 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14683 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14684 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14685 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14686 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14687 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14688 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14689 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14690 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14691 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14692 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14693 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14694 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14695 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14696 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14697 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14698 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14699 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14700 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14701 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14702 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14703 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14704 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14705 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14706 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14707 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14709 ;; All the other keys
14711 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14712 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14713 (if (boundp 'narrow-map)
14714 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14715 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14716 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14717 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14718 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14719 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14720 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14721 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14722 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14723 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14724 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14725 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14726 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14727 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14728 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14729 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14730 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14731 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14732 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14733 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14734 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14735 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14736 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14737 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14738 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14739 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14740 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14741 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14742 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14743 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14744 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14745 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14746 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14747 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14748 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14749 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14750 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14751 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14752 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14753 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14754 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14755 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14756 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14757 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14758 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14759 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14760 (org-defkey org-mode-map "\C-c^" 'org-sort)
14761 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14762 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14763 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14764 (org-defkey org-mode-map "\C-m" 'org-return)
14765 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14766 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14767 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14768 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14769 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14770 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14771 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14772 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14773 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14774 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14775 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14776 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14777 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14778 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14779 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14780 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14781 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14782 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14783 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14784 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14785 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14787 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14788 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14789 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14790 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14792 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14793 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14794 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14795 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14796 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14797 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14798 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14799 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14800 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14801 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14802 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14803 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14804 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14805 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14806 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14808 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14809 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14810 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14811 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14813 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14815 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14817 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14818 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14820 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14823 (when (featurep 'xemacs)
14824 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14827 (defconst org-speed-commands-default
14829 ("n" . outline-next-visible-heading)
14830 ("p" . outline-previous-visible-heading)
14831 ("f" . org-forward-same-level)
14832 ("b" . org-backward-same-level)
14833 ("u" . outline-up-heading)
14835 ("c" . org-cycle)
14836 ("C" . org-shifttab)
14837 ("U" . org-shiftmetaup)
14838 ("D" . org-shiftmetadown)
14839 ("r" . org-metaright)
14840 ("l" . org-metaleft)
14841 ("R" . org-shiftmetaright)
14842 ("L" . org-shiftmetaleft)
14843 ("i" . (progn (forward-char 1) (call-interactively
14844 'org-insert-heading-respect-content)))
14846 ("a" . org-agenda)
14847 ("/" . org-sparse-tree)
14848 (";" . org-set-tags-command)
14849 ("I" . org-clock-in)
14850 ("O" . org-clock-out)
14851 ("o" . org-open-at-point)
14852 ("t" . org-todo)
14853 ("j" . org-goto)
14854 ("g" . (org-refile t))
14855 ("e" . org-set-effort)
14856 ("0" . (org-priority ?\ ))
14857 ("1" . (org-priority ?A))
14858 ("2" . (org-priority ?B))
14859 ("3" . (org-priority ?C))
14860 ("." . outline-mark-subtree)
14861 ("^" . org-sort)
14862 ("w" . org-refile)
14863 ("a" . org-archive-subtree-default-with-confirmation)
14864 ("/" . org-sparse-tree)
14865 ("?" . org-speed-command-help)
14867 "The default speed commands.")
14869 (defun org-print-speed-command (e)
14870 (princ (car e))
14871 (princ " ")
14872 (if (symbolp (cdr e))
14873 (princ (symbol-name (cdr e)))
14874 (prin1 (cdr e)))
14875 (princ "\n"))
14877 (defun org-speed-command-help ()
14878 "Show the available speed commands."
14879 (interactive)
14880 (if (not org-use-speed-commands)
14881 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
14882 (with-output-to-temp-buffer "*Help*"
14883 (princ "Speed commands\n==============\n")
14884 (mapc 'org-print-speed-command org-speed-commands-user)
14885 (princ "\n")
14886 (mapc 'org-print-speed-command org-speed-commands-default))))
14888 (defvar org-self-insert-command-undo-counter 0)
14890 (defvar org-table-auto-blank-field) ; defined in org-table.el
14891 (defvar org-speed-command nil)
14892 (defun org-self-insert-command (N)
14893 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14894 If the cursor is in a table looking at whitespace, the whitespace is
14895 overwritten, and the table is not marked as requiring realignment."
14896 (interactive "p")
14897 (cond
14898 ((and org-use-speed-commands
14899 (bolp)
14900 (looking-at outline-regexp)
14901 (setq
14902 org-speed-command
14903 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
14904 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
14905 (cond
14906 ((commandp org-speed-command)
14907 (setq this-command org-speed-command)
14908 (call-interactively org-speed-command))
14909 ((functionp org-speed-command)
14910 (funcall org-speed-command))
14911 ((and org-speed-command (listp org-speed-command))
14912 (eval org-speed-command))
14913 (t (let (org-use-speed-commands)
14914 (call-interactively 'org-self-insert-command)))))
14915 ((and
14916 (org-table-p)
14917 (progn
14918 ;; check if we blank the field, and if that triggers align
14919 (and (featurep 'org-table) org-table-auto-blank-field
14920 (member last-command
14921 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14922 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14923 ;; got extra space, this field does not determine column width
14924 (let (org-table-may-need-update) (org-table-blank-field))
14925 ;; no extra space, this field may determine column width
14926 (org-table-blank-field)))
14928 (eq N 1)
14929 (looking-at "[^|\n]* |"))
14930 (let (org-table-may-need-update)
14931 (goto-char (1- (match-end 0)))
14932 (delete-backward-char 1)
14933 (goto-char (match-beginning 0))
14934 (self-insert-command N)))
14936 (setq org-table-may-need-update t)
14937 (self-insert-command N)
14938 (org-fix-tags-on-the-fly)
14939 (if org-self-insert-cluster-for-undo
14940 (if (not (eq last-command 'org-self-insert-command))
14941 (setq org-self-insert-command-undo-counter 1)
14942 (if (>= org-self-insert-command-undo-counter 20)
14943 (setq org-self-insert-command-undo-counter 1)
14944 (and (> org-self-insert-command-undo-counter 0)
14945 buffer-undo-list
14946 (not (cadr buffer-undo-list)) ; remove nil entry
14947 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14948 (setq org-self-insert-command-undo-counter
14949 (1+ org-self-insert-command-undo-counter))))))))
14951 (defun org-fix-tags-on-the-fly ()
14952 (when (and (equal (char-after (point-at-bol)) ?*)
14953 (org-on-heading-p))
14954 (org-align-tags-here org-tags-column)))
14956 (defun org-delete-backward-char (N)
14957 "Like `delete-backward-char', insert whitespace at field end in tables.
14958 When deleting backwards, in tables this function will insert whitespace in
14959 front of the next \"|\" separator, to keep the table aligned. The table will
14960 still be marked for re-alignment if the field did fill the entire column,
14961 because, in this case the deletion might narrow the column."
14962 (interactive "p")
14963 (if (and (org-table-p)
14964 (eq N 1)
14965 (string-match "|" (buffer-substring (point-at-bol) (point)))
14966 (looking-at ".*?|"))
14967 (let ((pos (point))
14968 (noalign (looking-at "[^|\n\r]* |"))
14969 (c org-table-may-need-update))
14970 (backward-delete-char N)
14971 (skip-chars-forward "^|")
14972 (insert " ")
14973 (goto-char (1- pos))
14974 ;; noalign: if there were two spaces at the end, this field
14975 ;; does not determine the width of the column.
14976 (if noalign (setq org-table-may-need-update c)))
14977 (backward-delete-char N)
14978 (org-fix-tags-on-the-fly)))
14980 (defun org-delete-char (N)
14981 "Like `delete-char', but insert whitespace at field end in tables.
14982 When deleting characters, in tables this function will insert whitespace in
14983 front of the next \"|\" separator, to keep the table aligned. The table will
14984 still be marked for re-alignment if the field did fill the entire column,
14985 because, in this case the deletion might narrow the column."
14986 (interactive "p")
14987 (if (and (org-table-p)
14988 (not (bolp))
14989 (not (= (char-after) ?|))
14990 (eq N 1))
14991 (if (looking-at ".*?|")
14992 (let ((pos (point))
14993 (noalign (looking-at "[^|\n\r]* |"))
14994 (c org-table-may-need-update))
14995 (replace-match (concat
14996 (substring (match-string 0) 1 -1)
14997 " |"))
14998 (goto-char pos)
14999 ;; noalign: if there were two spaces at the end, this field
15000 ;; does not determine the width of the column.
15001 (if noalign (setq org-table-may-need-update c)))
15002 (delete-char N))
15003 (delete-char N)
15004 (org-fix-tags-on-the-fly)))
15006 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15007 (put 'org-self-insert-command 'delete-selection t)
15008 (put 'orgtbl-self-insert-command 'delete-selection t)
15009 (put 'org-delete-char 'delete-selection 'supersede)
15010 (put 'org-delete-backward-char 'delete-selection 'supersede)
15011 (put 'org-yank 'delete-selection 'yank)
15013 ;; Make `flyspell-mode' delay after some commands
15014 (put 'org-self-insert-command 'flyspell-delayed t)
15015 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15016 (put 'org-delete-char 'flyspell-delayed t)
15017 (put 'org-delete-backward-char 'flyspell-delayed t)
15019 ;; Make pabbrev-mode expand after org-mode commands
15020 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15021 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15023 ;; How to do this: Measure non-white length of current string
15024 ;; If equal to column width, we should realign.
15026 (defun org-remap (map &rest commands)
15027 "In MAP, remap the functions given in COMMANDS.
15028 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15029 (let (new old)
15030 (while commands
15031 (setq old (pop commands) new (pop commands))
15032 (if (fboundp 'command-remapping)
15033 (org-defkey map (vector 'remap old) new)
15034 (substitute-key-definition old new map global-map)))))
15036 (when (eq org-enable-table-editor 'optimized)
15037 ;; If the user wants maximum table support, we need to hijack
15038 ;; some standard editing functions
15039 (org-remap org-mode-map
15040 'self-insert-command 'org-self-insert-command
15041 'delete-char 'org-delete-char
15042 'delete-backward-char 'org-delete-backward-char)
15043 (org-defkey org-mode-map "|" 'org-force-self-insert))
15045 (defvar org-ctrl-c-ctrl-c-hook nil
15046 "Hook for functions attaching themselves to `C-c C-c'.
15047 This can be used to add additional functionality to the C-c C-c key which
15048 executes context-dependent commands.
15049 Each function will be called with no arguments. The function must check
15050 if the context is appropriate for it to act. If yes, it should do its
15051 thing and then return a non-nil value. If the context is wrong,
15052 just do nothing and return nil.")
15054 (defvar org-tab-first-hook nil
15055 "Hook for functions to attach themselves to TAB.
15056 See `org-ctrl-c-ctrl-c-hook' for more information.
15057 This hook runs as the first action when TAB is pressed, even before
15058 `org-cycle' messes around with the `outline-regexp' to cater for
15059 inline tasks and plain list item folding.
15060 If any function in this hook returns t, not other actions like table
15061 field motion visibility cycling will be done.")
15063 (defvar org-tab-after-check-for-table-hook nil
15064 "Hook for functions to attach themselves to TAB.
15065 See `org-ctrl-c-ctrl-c-hook' for more information.
15066 This hook runs after it has been established that the cursor is not in a
15067 table, but before checking if the cursor is in a headline or if global cycling
15068 should be done.
15069 If any function in this hook returns t, not other actions like visibility
15070 cycling will be done.")
15072 (defvar org-tab-after-check-for-cycling-hook nil
15073 "Hook for functions to attach themselves to TAB.
15074 See `org-ctrl-c-ctrl-c-hook' for more information.
15075 This hook runs after it has been established that not table field motion and
15076 not visibility should be done because of current context. This is probably
15077 the place where a package like yasnippets can hook in.")
15079 (defvar org-tab-before-tab-emulation-hook nil
15080 "Hook for functions to attach themselves to TAB.
15081 See `org-ctrl-c-ctrl-c-hook' for more information.
15082 This hook runs after every other options for TAB have been exhausted, but
15083 before indentation and \t insertion takes place.")
15085 (defvar org-metaleft-hook nil
15086 "Hook for functions attaching themselves to `M-left'.
15087 See `org-ctrl-c-ctrl-c-hook' for more information.")
15088 (defvar org-metaright-hook nil
15089 "Hook for functions attaching themselves to `M-right'.
15090 See `org-ctrl-c-ctrl-c-hook' for more information.")
15091 (defvar org-metaup-hook nil
15092 "Hook for functions attaching themselves to `M-up'.
15093 See `org-ctrl-c-ctrl-c-hook' for more information.")
15094 (defvar org-metadown-hook nil
15095 "Hook for functions attaching themselves to `M-down'.
15096 See `org-ctrl-c-ctrl-c-hook' for more information.")
15097 (defvar org-shiftmetaleft-hook nil
15098 "Hook for functions attaching themselves to `M-S-left'.
15099 See `org-ctrl-c-ctrl-c-hook' for more information.")
15100 (defvar org-shiftmetaright-hook nil
15101 "Hook for functions attaching themselves to `M-S-right'.
15102 See `org-ctrl-c-ctrl-c-hook' for more information.")
15103 (defvar org-shiftmetaup-hook nil
15104 "Hook for functions attaching themselves to `M-S-up'.
15105 See `org-ctrl-c-ctrl-c-hook' for more information.")
15106 (defvar org-shiftmetadown-hook nil
15107 "Hook for functions attaching themselves to `M-S-down'.
15108 See `org-ctrl-c-ctrl-c-hook' for more information.")
15109 (defvar org-metareturn-hook nil
15110 "Hook for functions attaching themselves to `M-RET'.
15111 See `org-ctrl-c-ctrl-c-hook' for more information.")
15113 (defun org-modifier-cursor-error ()
15114 "Throw an error, a modified cursor command was applied in wrong context."
15115 (error "This command is active in special context like tables, headlines or items"))
15117 (defun org-shiftselect-error ()
15118 "Throw an error because Shift-Cursor command was applied in wrong context."
15119 (if (and (boundp 'shift-select-mode) shift-select-mode)
15120 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15121 (error "This command works only in special context like headlines or timestamps")))
15123 (defun org-call-for-shift-select (cmd)
15124 (let ((this-command-keys-shift-translated t))
15125 (call-interactively cmd)))
15127 (defun org-shifttab (&optional arg)
15128 "Global visibility cycling or move to previous table field.
15129 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15130 on context.
15131 See the individual commands for more information."
15132 (interactive "P")
15133 (cond
15134 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15135 ((integerp arg)
15136 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15137 (message "Content view to level: %d" arg)
15138 (org-content (prefix-numeric-value arg2))
15139 (setq org-cycle-global-status 'overview)))
15140 (t (call-interactively 'org-global-cycle))))
15142 (defun org-shiftmetaleft ()
15143 "Promote subtree or delete table column.
15144 Calls `org-promote-subtree', `org-outdent-item',
15145 or `org-table-delete-column', depending on context.
15146 See the individual commands for more information."
15147 (interactive)
15148 (cond
15149 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15150 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15151 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15152 ((org-at-item-p) (call-interactively 'org-outdent-item))
15153 (t (org-modifier-cursor-error))))
15155 (defun org-shiftmetaright ()
15156 "Demote subtree or insert table column.
15157 Calls `org-demote-subtree', `org-indent-item',
15158 or `org-table-insert-column', depending on context.
15159 See the individual commands for more information."
15160 (interactive)
15161 (cond
15162 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15163 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15164 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15165 ((org-at-item-p) (call-interactively 'org-indent-item))
15166 (t (org-modifier-cursor-error))))
15168 (defun org-shiftmetaup (&optional arg)
15169 "Move subtree up or kill table row.
15170 Calls `org-move-subtree-up' or `org-table-kill-row' or
15171 `org-move-item-up' depending on context. See the individual commands
15172 for more information."
15173 (interactive "P")
15174 (cond
15175 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15176 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15177 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15178 ((org-at-item-p) (call-interactively 'org-move-item-up))
15179 (t (org-modifier-cursor-error))))
15181 (defun org-shiftmetadown (&optional arg)
15182 "Move subtree down or insert table row.
15183 Calls `org-move-subtree-down' or `org-table-insert-row' or
15184 `org-move-item-down', depending on context. See the individual
15185 commands for more information."
15186 (interactive "P")
15187 (cond
15188 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15189 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15190 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15191 ((org-at-item-p) (call-interactively 'org-move-item-down))
15192 (t (org-modifier-cursor-error))))
15194 (defun org-metaleft (&optional arg)
15195 "Promote heading or move table column to left.
15196 Calls `org-do-promote' or `org-table-move-column', depending on context.
15197 With no specific context, calls the Emacs default `backward-word'.
15198 See the individual commands for more information."
15199 (interactive "P")
15200 (cond
15201 ((run-hook-with-args-until-success 'org-metaleft-hook))
15202 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15203 ((or (org-on-heading-p)
15204 (and (org-region-active-p)
15205 (save-excursion
15206 (goto-char (region-beginning))
15207 (org-on-heading-p))))
15208 (call-interactively 'org-do-promote))
15209 ((or (org-at-item-p)
15210 (and (org-region-active-p)
15211 (save-excursion
15212 (goto-char (region-beginning))
15213 (org-at-item-p))))
15214 (call-interactively 'org-outdent-item))
15215 (t (call-interactively 'backward-word))))
15217 (defun org-metaright (&optional arg)
15218 "Demote subtree or move table column to right.
15219 Calls `org-do-demote' or `org-table-move-column', depending on context.
15220 With no specific context, calls the Emacs default `forward-word'.
15221 See the individual commands for more information."
15222 (interactive "P")
15223 (cond
15224 ((run-hook-with-args-until-success 'org-metaright-hook))
15225 ((org-at-table-p) (call-interactively 'org-table-move-column))
15226 ((or (org-on-heading-p)
15227 (and (org-region-active-p)
15228 (save-excursion
15229 (goto-char (region-beginning))
15230 (org-on-heading-p))))
15231 (call-interactively 'org-do-demote))
15232 ((or (org-at-item-p)
15233 (and (org-region-active-p)
15234 (save-excursion
15235 (goto-char (region-beginning))
15236 (org-at-item-p))))
15237 (call-interactively 'org-indent-item))
15238 (t (call-interactively 'forward-word))))
15240 (defun org-metaup (&optional arg)
15241 "Move subtree up or move table row up.
15242 Calls `org-move-subtree-up' or `org-table-move-row' or
15243 `org-move-item-up', depending on context. See the individual commands
15244 for more information."
15245 (interactive "P")
15246 (cond
15247 ((run-hook-with-args-until-success 'org-metaup-hook))
15248 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15249 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15250 ((org-at-item-p) (call-interactively 'org-move-item-up))
15251 (t (transpose-lines 1) (beginning-of-line -1))))
15253 (defun org-metadown (&optional arg)
15254 "Move subtree down or move table row down.
15255 Calls `org-move-subtree-down' or `org-table-move-row' or
15256 `org-move-item-down', depending on context. See the individual
15257 commands for more information."
15258 (interactive "P")
15259 (cond
15260 ((run-hook-with-args-until-success 'org-metadown-hook))
15261 ((org-at-table-p) (call-interactively 'org-table-move-row))
15262 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15263 ((org-at-item-p) (call-interactively 'org-move-item-down))
15264 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15266 (defun org-shiftup (&optional arg)
15267 "Increase item in timestamp or increase priority of current headline.
15268 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15269 depending on context. See the individual commands for more information."
15270 (interactive "P")
15271 (cond
15272 ((and org-support-shift-select (org-region-active-p))
15273 (org-call-for-shift-select 'previous-line))
15274 ((org-at-timestamp-p t)
15275 (call-interactively (if org-edit-timestamp-down-means-later
15276 'org-timestamp-down 'org-timestamp-up)))
15277 ((and (not (eq org-support-shift-select 'always))
15278 org-enable-priority-commands
15279 (org-on-heading-p))
15280 (call-interactively 'org-priority-up))
15281 ((and (not org-support-shift-select) (org-at-item-p))
15282 (call-interactively 'org-previous-item))
15283 ((org-clocktable-try-shift 'up arg))
15284 (org-support-shift-select
15285 (org-call-for-shift-select 'previous-line))
15286 (t (org-shiftselect-error))))
15288 (defun org-shiftdown (&optional arg)
15289 "Decrease item in timestamp or decrease priority of current headline.
15290 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15291 depending on context. See the individual commands for more information."
15292 (interactive "P")
15293 (cond
15294 ((and org-support-shift-select (org-region-active-p))
15295 (org-call-for-shift-select 'next-line))
15296 ((org-at-timestamp-p t)
15297 (call-interactively (if org-edit-timestamp-down-means-later
15298 'org-timestamp-up 'org-timestamp-down)))
15299 ((and (not (eq org-support-shift-select 'always))
15300 org-enable-priority-commands
15301 (org-on-heading-p))
15302 (call-interactively 'org-priority-down))
15303 ((and (not org-support-shift-select) (org-at-item-p))
15304 (call-interactively 'org-next-item))
15305 ((org-clocktable-try-shift 'down arg))
15306 (org-support-shift-select
15307 (org-call-for-shift-select 'next-line))
15308 (t (org-shiftselect-error))))
15310 (defun org-shiftright (&optional arg)
15311 "Cycle the thing at point or in the current line, depending on context.
15312 Depending on context, this does one of the following:
15314 - switch a timestamp at point one day into the future
15315 - on a headline, switch to the next TODO keyword.
15316 - on an item, switch entire list to the next bullet type
15317 - on a property line, switch to the next allowed value
15318 - on a clocktable definition line, move time block into the future"
15319 (interactive "P")
15320 (cond
15321 ((and org-support-shift-select (org-region-active-p))
15322 (org-call-for-shift-select 'forward-char))
15323 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15324 ((and (not (eq org-support-shift-select 'always))
15325 (org-on-heading-p))
15326 (let ((org-inhibit-logging
15327 (not org-treat-S-cursor-todo-selection-as-state-change))
15328 (org-inhibit-blocking
15329 (not org-treat-S-cursor-todo-selection-as-state-change)))
15330 (org-call-with-arg 'org-todo 'right)))
15331 ((or (and org-support-shift-select
15332 (not (eq org-support-shift-select 'always))
15333 (org-at-item-bullet-p))
15334 (and (not org-support-shift-select) (org-at-item-p)))
15335 (org-call-with-arg 'org-cycle-list-bullet nil))
15336 ((and (not (eq org-support-shift-select 'always))
15337 (org-at-property-p))
15338 (call-interactively 'org-property-next-allowed-value))
15339 ((org-clocktable-try-shift 'right arg))
15340 (org-support-shift-select
15341 (org-call-for-shift-select 'forward-char))
15342 (t (org-shiftselect-error))))
15344 (defun org-shiftleft (&optional arg)
15345 "Cycle the thing at point or in the current line, depending on context.
15346 Depending on context, this does one of the following:
15348 - switch a timestamp at point one day into the past
15349 - on a headline, switch to the previous TODO keyword.
15350 - on an item, switch entire list to the previous bullet type
15351 - on a property line, switch to the previous allowed value
15352 - on a clocktable definition line, move time block into the past"
15353 (interactive "P")
15354 (cond
15355 ((and org-support-shift-select (org-region-active-p))
15356 (org-call-for-shift-select 'backward-char))
15357 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15358 ((and (not (eq org-support-shift-select 'always))
15359 (org-on-heading-p))
15360 (let ((org-inhibit-logging
15361 (not org-treat-S-cursor-todo-selection-as-state-change))
15362 (org-inhibit-blocking
15363 (not org-treat-S-cursor-todo-selection-as-state-change)))
15364 (org-call-with-arg 'org-todo 'left)))
15365 ((or (and org-support-shift-select
15366 (not (eq org-support-shift-select 'always))
15367 (org-at-item-bullet-p))
15368 (and (not org-support-shift-select) (org-at-item-p)))
15369 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15370 ((and (not (eq org-support-shift-select 'always))
15371 (org-at-property-p))
15372 (call-interactively 'org-property-previous-allowed-value))
15373 ((org-clocktable-try-shift 'left arg))
15374 (org-support-shift-select
15375 (org-call-for-shift-select 'backward-char))
15376 (t (org-shiftselect-error))))
15378 (defun org-shiftcontrolright ()
15379 "Switch to next TODO set."
15380 (interactive)
15381 (cond
15382 ((and org-support-shift-select (org-region-active-p))
15383 (org-call-for-shift-select 'forward-word))
15384 ((and (not (eq org-support-shift-select 'always))
15385 (org-on-heading-p))
15386 (org-call-with-arg 'org-todo 'nextset))
15387 (org-support-shift-select
15388 (org-call-for-shift-select 'forward-word))
15389 (t (org-shiftselect-error))))
15391 (defun org-shiftcontrolleft ()
15392 "Switch to previous TODO set."
15393 (interactive)
15394 (cond
15395 ((and org-support-shift-select (org-region-active-p))
15396 (org-call-for-shift-select 'backward-word))
15397 ((and (not (eq org-support-shift-select 'always))
15398 (org-on-heading-p))
15399 (org-call-with-arg 'org-todo 'previousset))
15400 (org-support-shift-select
15401 (org-call-for-shift-select 'backward-word))
15402 (t (org-shiftselect-error))))
15404 (defun org-ctrl-c-ret ()
15405 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15406 (interactive)
15407 (cond
15408 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15409 (t (call-interactively 'org-insert-heading))))
15411 (defun org-copy-special ()
15412 "Copy region in table or copy current subtree.
15413 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15414 See the individual commands for more information."
15415 (interactive)
15416 (call-interactively
15417 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15419 (defun org-cut-special ()
15420 "Cut region in table or cut current subtree.
15421 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15422 See the individual commands for more information."
15423 (interactive)
15424 (call-interactively
15425 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15427 (defun org-paste-special (arg)
15428 "Paste rectangular region into table, or past subtree relative to level.
15429 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15430 See the individual commands for more information."
15431 (interactive "P")
15432 (if (org-at-table-p)
15433 (org-table-paste-rectangle)
15434 (org-paste-subtree arg)))
15436 (defun org-edit-special ()
15437 "Call a special editor for the stuff at point.
15438 When at a table, call the formula editor with `org-table-edit-formulas'.
15439 When at the first line of an src example, call `org-edit-src-code'.
15440 When in an #+include line, visit the include file. Otherwise call
15441 `ffap' to visit the file at point."
15442 (interactive)
15443 (cond
15444 ((org-at-table-p)
15445 (call-interactively 'org-table-edit-formulas))
15446 ((save-excursion
15447 (beginning-of-line 1)
15448 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15449 (find-file (org-trim (match-string 1))))
15450 ((org-edit-src-code))
15451 ((org-edit-fixed-width-region))
15452 (t (call-interactively 'ffap))))
15455 (defun org-ctrl-c-ctrl-c (&optional arg)
15456 "Set tags in headline, or update according to changed information at point.
15458 This command does many different things, depending on context:
15460 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15461 this is what we do.
15463 - If the cursor is on a statistics cookie, update it.
15465 - If the cursor is in a headline, prompt for tags and insert them
15466 into the current line, aligned to `org-tags-column'. When called
15467 with prefix arg, realign all tags in the current buffer.
15469 - If the cursor is in one of the special #+KEYWORD lines, this
15470 triggers scanning the buffer for these lines and updating the
15471 information.
15473 - If the cursor is inside a table, realign the table. This command
15474 works even if the automatic table editor has been turned off.
15476 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15477 the entire table.
15479 - If the cursor is at a footnote reference or definition, jump to
15480 the corresponding definition or references, respectively.
15482 - If the cursor is a the beginning of a dynamic block, update it.
15484 - If the cursor is inside a table created by the table.el package,
15485 activate that table.
15487 - If the current buffer is a remember buffer, close note and file
15488 it. A prefix argument of 1 files to the default location
15489 without further interaction. A prefix argument of 2 files to
15490 the currently clocking task.
15492 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15493 links in this buffer.
15495 - If the cursor is on a numbered item in a plain list, renumber the
15496 ordered list.
15498 - If the cursor is on a checkbox, toggle it."
15499 (interactive "P")
15500 (let ((org-enable-table-editor t))
15501 (cond
15502 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15503 org-occur-highlights
15504 org-latex-fragment-image-overlays)
15505 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15506 (org-remove-occur-highlights)
15507 (org-remove-latex-fragment-image-overlays)
15508 (message "Temporary highlights/overlays removed from current buffer"))
15509 ((and (local-variable-p 'org-finish-function (current-buffer))
15510 (fboundp org-finish-function))
15511 (funcall org-finish-function))
15512 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15513 ((org-at-property-p)
15514 (call-interactively 'org-property-action))
15515 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15516 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15517 (or (org-on-heading-p) (org-at-item-p)))
15518 (call-interactively 'org-update-statistics-cookies))
15519 ((org-on-heading-p) (call-interactively 'org-set-tags))
15520 ((org-at-table.el-p)
15521 (require 'table)
15522 (beginning-of-line 1)
15523 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15524 (call-interactively 'table-recognize-table))
15525 ((org-at-table-p)
15526 (org-table-maybe-eval-formula)
15527 (if arg
15528 (call-interactively 'org-table-recalculate)
15529 (org-table-maybe-recalculate-line))
15530 (call-interactively 'org-table-align))
15531 ((or (org-footnote-at-reference-p)
15532 (org-footnote-at-definition-p))
15533 (call-interactively 'org-footnote-action))
15534 ((org-at-item-checkbox-p)
15535 (call-interactively 'org-toggle-checkbox))
15536 ((org-at-item-p)
15537 (if arg
15538 (call-interactively 'org-toggle-checkbox)
15539 (call-interactively 'org-maybe-renumber-ordered-list)))
15540 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15541 ;; Dynamic block
15542 (beginning-of-line 1)
15543 (save-excursion (org-update-dblock)))
15544 ((save-excursion
15545 (beginning-of-line 1)
15546 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15547 (cond
15548 ((equal (match-string 1) "TBLFM")
15549 ;; Recalculate the table before this line
15550 (save-excursion
15551 (beginning-of-line 1)
15552 (skip-chars-backward " \r\n\t")
15553 (if (org-at-table-p)
15554 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15556 ; (org-set-regexps-and-options)
15557 ; (org-restart-font-lock)
15558 (let ((org-inhibit-startup t)) (org-mode-restart))
15559 (message "Local setup has been refreshed"))))
15560 ((org-clock-update-time-maybe))
15561 (t (error "C-c C-c can do nothing useful at this location")))))
15563 (defun org-mode-restart ()
15564 "Restart Org-mode, to scan again for special lines.
15565 Also updates the keyword regular expressions."
15566 (interactive)
15567 (org-mode)
15568 (message "Org-mode restarted"))
15570 (defun org-kill-note-or-show-branches ()
15571 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15572 (interactive)
15573 (if (not org-finish-function)
15574 (call-interactively 'show-branches)
15575 (let ((org-note-abort t))
15576 (funcall org-finish-function))))
15578 (defun org-return (&optional indent)
15579 "Goto next table row or insert a newline.
15580 Calls `org-table-next-row' or `newline', depending on context.
15581 See the individual commands for more information."
15582 (interactive)
15583 (cond
15584 ((bobp) (if indent (newline-and-indent) (newline)))
15585 ((org-at-table-p)
15586 (org-table-justify-field-maybe)
15587 (call-interactively 'org-table-next-row))
15588 ((and org-return-follows-link
15589 (eq (get-text-property (point) 'face) 'org-link))
15590 (call-interactively 'org-open-at-point))
15591 ((and (org-at-heading-p)
15592 (looking-at
15593 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15594 (org-show-entry)
15595 (end-of-line 1)
15596 (newline))
15597 (t (if indent (newline-and-indent) (newline)))))
15599 (defun org-return-indent ()
15600 "Goto next table row or insert a newline and indent.
15601 Calls `org-table-next-row' or `newline-and-indent', depending on
15602 context. See the individual commands for more information."
15603 (interactive)
15604 (org-return t))
15606 (defun org-ctrl-c-star ()
15607 "Compute table, or change heading status of lines.
15608 Calls `org-table-recalculate' or `org-toggle-heading',
15609 depending on context."
15610 (interactive)
15611 (cond
15612 ((org-at-table-p)
15613 (call-interactively 'org-table-recalculate))
15615 ;; Convert all lines in region to list items
15616 (call-interactively 'org-toggle-heading))))
15618 (defun org-ctrl-c-minus ()
15619 "Insert separator line in table or modify bullet status of line.
15620 Also turns a plain line or a region of lines into list items.
15621 Calls `org-table-insert-hline', `org-toggle-item', or
15622 `org-cycle-list-bullet', depending on context."
15623 (interactive)
15624 (cond
15625 ((org-at-table-p)
15626 (call-interactively 'org-table-insert-hline))
15627 ((org-region-active-p)
15628 (call-interactively 'org-toggle-item))
15629 ((org-in-item-p)
15630 (call-interactively 'org-cycle-list-bullet))
15632 (call-interactively 'org-toggle-item))))
15634 (defun org-toggle-item ()
15635 "Convert headings or normal lines to items, items to normal lines.
15636 If there is no active region, only the current line is considered.
15638 If the first line in the region is a headline, convert all headlines to items.
15640 If the first line in the region is an item, convert all items to normal lines.
15642 If the first line is normal text, add an item bullet to each line."
15643 (interactive)
15644 (let (l2 l beg end)
15645 (if (org-region-active-p)
15646 (setq beg (region-beginning) end (region-end))
15647 (setq beg (point-at-bol)
15648 end (min (1+ (point-at-eol)) (point-max))))
15649 (save-excursion
15650 (goto-char end)
15651 (setq l2 (org-current-line))
15652 (goto-char beg)
15653 (beginning-of-line 1)
15654 (setq l (1- (org-current-line)))
15655 (if (org-at-item-p)
15656 ;; We already have items, de-itemize
15657 (while (< (setq l (1+ l)) l2)
15658 (when (org-at-item-p)
15659 (goto-char (match-beginning 2))
15660 (delete-region (match-beginning 2) (match-end 2))
15661 (and (looking-at "[ \t]+") (replace-match "")))
15662 (beginning-of-line 2))
15663 (if (org-on-heading-p)
15664 ;; Headings, convert to items
15665 (while (< (setq l (1+ l)) l2)
15666 (if (looking-at org-outline-regexp)
15667 (replace-match "- " t t))
15668 (beginning-of-line 2))
15669 ;; normal lines, turn them into items
15670 (while (< (setq l (1+ l)) l2)
15671 (unless (org-at-item-p)
15672 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15673 (replace-match "\\1- \\2")))
15674 (beginning-of-line 2)))))))
15676 (defun org-toggle-heading (&optional nstars)
15677 "Convert headings to normal text, or items or text to headings.
15678 If there is no active region, only the current line is considered.
15680 If the first line is a heading, remove the stars from all headlines
15681 in the region.
15683 If the first line is a plain list item, turn all plain list items
15684 into headings.
15686 If the first line is a normal line, turn each and every line in the
15687 region into a heading.
15689 When converting a line into a heading, the number of stars is chosen
15690 such that the lines become children of the current entry. However,
15691 when a prefix argument is given, its value determines the number of
15692 stars to add."
15693 (interactive "P")
15694 (let (l2 l itemp beg end)
15695 (if (org-region-active-p)
15696 (setq beg (region-beginning) end (region-end))
15697 (setq beg (point-at-bol)
15698 end (min (1+ (point-at-eol)) (point-max))))
15699 (save-excursion
15700 (goto-char end)
15701 (setq l2 (org-current-line))
15702 (goto-char beg)
15703 (beginning-of-line 1)
15704 (setq l (1- (org-current-line)))
15705 (if (org-on-heading-p)
15706 ;; We already have headlines, de-star them
15707 (while (< (setq l (1+ l)) l2)
15708 (when (org-on-heading-p t)
15709 (and (looking-at outline-regexp) (replace-match "")))
15710 (beginning-of-line 2))
15711 (setq itemp (org-at-item-p))
15712 (let* ((stars
15713 (if nstars
15714 (make-string (prefix-numeric-value current-prefix-arg)
15716 (save-excursion
15717 (if (re-search-backward org-complex-heading-regexp nil t)
15718 (match-string 1) ""))))
15719 (add-stars (cond (nstars "")
15720 ((equal stars "") "*")
15721 (org-odd-levels-only "**")
15722 (t "*")))
15723 (rpl (concat stars add-stars " ")))
15724 (while (< (setq l (1+ l)) l2)
15725 (if itemp
15726 (and (org-at-item-p) (replace-match rpl t t))
15727 (unless (org-on-heading-p)
15728 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15729 (replace-match (concat rpl (match-string 2))))))
15730 (beginning-of-line 2)))))))
15732 (defun org-meta-return (&optional arg)
15733 "Insert a new heading or wrap a region in a table.
15734 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15735 See the individual commands for more information."
15736 (interactive "P")
15737 (cond
15738 ((run-hook-with-args-until-success 'org-metareturn-hook))
15739 ((org-at-table-p)
15740 (call-interactively 'org-table-wrap-region))
15741 (t (call-interactively 'org-insert-heading))))
15743 ;;; Menu entries
15745 ;; Define the Org-mode menus
15746 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15747 '("Tbl"
15748 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15749 ["Next Field" org-cycle (org-at-table-p)]
15750 ["Previous Field" org-shifttab (org-at-table-p)]
15751 ["Next Row" org-return (org-at-table-p)]
15752 "--"
15753 ["Blank Field" org-table-blank-field (org-at-table-p)]
15754 ["Edit Field" org-table-edit-field (org-at-table-p)]
15755 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15756 "--"
15757 ("Column"
15758 ["Move Column Left" org-metaleft (org-at-table-p)]
15759 ["Move Column Right" org-metaright (org-at-table-p)]
15760 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15761 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15762 ("Row"
15763 ["Move Row Up" org-metaup (org-at-table-p)]
15764 ["Move Row Down" org-metadown (org-at-table-p)]
15765 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15766 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15767 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15768 "--"
15769 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15770 ("Rectangle"
15771 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15772 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15773 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15774 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15775 "--"
15776 ("Calculate"
15777 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15778 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15779 ["Edit Formulas" org-edit-special (org-at-table-p)]
15780 "--"
15781 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15782 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15783 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15784 "--"
15785 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15786 "--"
15787 ["Sum Column/Rectangle" org-table-sum
15788 (or (org-at-table-p) (org-region-active-p))]
15789 ["Which Column?" org-table-current-column (org-at-table-p)])
15790 ["Debug Formulas"
15791 org-table-toggle-formula-debugger
15792 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15793 ["Show Col/Row Numbers"
15794 org-table-toggle-coordinate-overlays
15795 :style toggle
15796 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15797 "--"
15798 ["Create" org-table-create (and (not (org-at-table-p))
15799 org-enable-table-editor)]
15800 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15801 ["Import from File" org-table-import (not (org-at-table-p))]
15802 ["Export to File" org-table-export (org-at-table-p)]
15803 "--"
15804 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15806 (easy-menu-define org-org-menu org-mode-map "Org menu"
15807 '("Org"
15808 ("Show/Hide"
15809 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15810 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15811 ["Sparse Tree..." org-sparse-tree t]
15812 ["Reveal Context" org-reveal t]
15813 ["Show All" show-all t]
15814 "--"
15815 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15816 "--"
15817 ["New Heading" org-insert-heading t]
15818 ("Navigate Headings"
15819 ["Up" outline-up-heading t]
15820 ["Next" outline-next-visible-heading t]
15821 ["Previous" outline-previous-visible-heading t]
15822 ["Next Same Level" outline-forward-same-level t]
15823 ["Previous Same Level" outline-backward-same-level t]
15824 "--"
15825 ["Jump" org-goto t])
15826 ("Edit Structure"
15827 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15828 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15829 "--"
15830 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15831 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15832 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15833 "--"
15834 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15835 "--"
15836 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15837 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15838 ["Demote Heading" org-metaright (not (org-at-table-p))]
15839 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15840 "--"
15841 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15842 "--"
15843 ["Convert to odd levels" org-convert-to-odd-levels t]
15844 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15845 ("Editing"
15846 ["Emphasis..." org-emphasize t]
15847 ["Edit Source Example" org-edit-special t]
15848 "--"
15849 ["Footnote new/jump" org-footnote-action t]
15850 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15851 ("Archive"
15852 ["Archive (default method)" org-archive-subtree-default t]
15853 "--"
15854 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
15855 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15856 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
15858 "--"
15859 ("Hyperlinks"
15860 ["Store Link (Global)" org-store-link t]
15861 ["Find existing link to here" org-occur-link-in-agenda-files t]
15862 ["Insert Link" org-insert-link t]
15863 ["Follow Link" org-open-at-point t]
15864 "--"
15865 ["Next link" org-next-link t]
15866 ["Previous link" org-previous-link t]
15867 "--"
15868 ["Descriptive Links"
15869 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15870 :style radio
15871 :selected (member '(org-link) buffer-invisibility-spec)]
15872 ["Literal Links"
15873 (progn
15874 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15875 :style radio
15876 :selected (not (member '(org-link) buffer-invisibility-spec))])
15877 "--"
15878 ("TODO Lists"
15879 ["TODO/DONE/-" org-todo t]
15880 ("Select keyword"
15881 ["Next keyword" org-shiftright (org-on-heading-p)]
15882 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15883 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15884 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15885 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15886 ["Show TODO Tree" org-show-todo-tree t]
15887 ["Global TODO list" org-todo-list t]
15888 "--"
15889 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15890 :selected org-enforce-todo-dependencies :style toggle :active t]
15891 "Settings for tree at point"
15892 ["Do Children sequentially" org-toggle-ordered-property :style radio
15893 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15894 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15895 ["Do Children parallel" org-toggle-ordered-property :style radio
15896 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15897 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15898 "--"
15899 ["Set Priority" org-priority t]
15900 ["Priority Up" org-shiftup t]
15901 ["Priority Down" org-shiftdown t]
15902 "--"
15903 ["Get news from all feeds" org-feed-update-all t]
15904 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15905 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15906 ("TAGS and Properties"
15907 ["Set Tags" org-set-tags-command t]
15908 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15909 "--"
15910 ["Set property" org-set-property t]
15911 ["Column view of properties" org-columns t]
15912 ["Insert Column View DBlock" org-insert-columns-dblock t])
15913 ("Dates and Scheduling"
15914 ["Timestamp" org-time-stamp t]
15915 ["Timestamp (inactive)" org-time-stamp-inactive t]
15916 ("Change Date"
15917 ["1 Day Later" org-shiftright t]
15918 ["1 Day Earlier" org-shiftleft t]
15919 ["1 ... Later" org-shiftup t]
15920 ["1 ... Earlier" org-shiftdown t])
15921 ["Compute Time Range" org-evaluate-time-range t]
15922 ["Schedule Item" org-schedule t]
15923 ["Deadline" org-deadline t]
15924 "--"
15925 ["Custom time format" org-toggle-time-stamp-overlays
15926 :style radio :selected org-display-custom-times]
15927 "--"
15928 ["Goto Calendar" org-goto-calendar t]
15929 ["Date from Calendar" org-date-from-calendar t]
15930 "--"
15931 ["Start/Restart Timer" org-timer-start t]
15932 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15933 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15934 ["Insert Timer String" org-timer t]
15935 ["Insert Timer Item" org-timer-item t])
15936 ("Logging work"
15937 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15938 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15939 ["Clock out" org-clock-out t]
15940 ["Clock cancel" org-clock-cancel t]
15941 "--"
15942 ["Mark as default task" org-clock-mark-default-task t]
15943 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15944 ["Goto running clock" org-clock-goto t]
15945 "--"
15946 ["Display times" org-clock-display t]
15947 ["Create clock table" org-clock-report t]
15948 "--"
15949 ["Record DONE time"
15950 (progn (setq org-log-done (not org-log-done))
15951 (message "Switching to %s will %s record a timestamp"
15952 (car org-done-keywords)
15953 (if org-log-done "automatically" "not")))
15954 :style toggle :selected org-log-done])
15955 "--"
15956 ["Agenda Command..." org-agenda t]
15957 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15958 ("File List for Agenda")
15959 ("Special views current file"
15960 ["TODO Tree" org-show-todo-tree t]
15961 ["Check Deadlines" org-check-deadlines t]
15962 ["Timeline" org-timeline t]
15963 ["Tags/Property tree" org-match-sparse-tree t])
15964 "--"
15965 ["Export/Publish..." org-export t]
15966 ("LaTeX"
15967 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15968 :selected org-cdlatex-mode]
15969 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15970 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15971 ["Modify math symbol" org-cdlatex-math-modify
15972 (org-inside-LaTeX-fragment-p)]
15973 ["Insert citation" org-reftex-citation t]
15974 "--"
15975 ["Export LaTeX fragments as images"
15976 (if (featurep 'org-exp)
15977 (setq org-export-with-LaTeX-fragments
15978 (not org-export-with-LaTeX-fragments))
15979 (require 'org-exp))
15980 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15981 org-export-with-LaTeX-fragments)])
15982 "--"
15983 ("MobileOrg"
15984 ["Push Files and Views" org-mobile-push t]
15985 ["Get Captured and Flagged" org-mobile-pull t]
15986 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
15987 "--"
15988 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
15989 "--"
15990 ("Documentation"
15991 ["Show Version" org-version t]
15992 ["Info Documentation" org-info t])
15993 ("Customize"
15994 ["Browse Org Group" org-customize t]
15995 "--"
15996 ["Expand This Menu" org-create-customize-menu
15997 (fboundp 'customize-menu-create)])
15998 ["Send bug report" org-submit-bug-report t]
15999 "--"
16000 ("Refresh/Reload"
16001 ["Refresh setup current buffer" org-mode-restart t]
16002 ["Reload Org (after update)" org-reload t]
16003 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16006 (defun org-info (&optional node)
16007 "Read documentation for Org-mode in the info system.
16008 With optional NODE, go directly to that node."
16009 (interactive)
16010 (info (format "(org)%s" (or node ""))))
16012 ;;;###autoload
16013 (defun org-submit-bug-report ()
16014 "Submit a bug report on Org-mode via mail.
16016 Don't hesitate to report any problems or inaccurate documentation.
16018 If you don't have setup sending mail from (X)Emacs, please copy the
16019 output buffer into your mail program, as it gives us important
16020 information about your Org-mode version and configuration."
16021 (interactive)
16022 (require 'reporter)
16023 (org-load-modules-maybe)
16024 (org-require-autoloaded-modules)
16025 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16026 (reporter-submit-bug-report
16027 "emacs-orgmode@gnu.org"
16028 (org-version)
16029 (let (list)
16030 (save-window-excursion
16031 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16032 (delete-other-windows)
16033 (erase-buffer)
16034 (insert "You are about to submit a bug report to the Org-mode mailing list.
16036 We would like to add your full Org-mode and Outline configuration to the
16037 bug report. This greatly simplifies the work of the maintainer and
16038 other experts on the mailing list.
16040 HOWEVER, some variables you have customized may contain private
16041 information. The names of customers, colleagues, or friends, might
16042 appear in the form of file names, tags, todo states, or search strings.
16043 If you answer yes to the prompt, you might want to check and remove
16044 such private information before sending the email.")
16045 (add-text-properties (point-min) (point-max) '(face org-warning))
16046 (when (yes-or-no-p "Include your Org-mode configuration ")
16047 (mapatoms
16048 (lambda (v)
16049 (and (boundp v)
16050 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16051 (or (and (symbol-value v)
16052 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16053 (and
16054 (get v 'custom-type) (get v 'standard-value)
16055 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16056 (push v list)))))
16057 (kill-buffer (get-buffer "*Warn about privacy*"))
16058 list))
16059 nil nil
16060 "Remember to cover the basics, that is, what you expected to happen and
16061 what in fact did happen. You don't know how to make a good report? See
16063 http://orgmode.org/manual/Feedback.html#Feedback
16065 Your bug report will be posted to the Org-mode mailing list.
16066 ------------------------------------------------------------------------")))
16068 (defun org-install-agenda-files-menu ()
16069 (let ((bl (buffer-list)))
16070 (save-excursion
16071 (while bl
16072 (set-buffer (pop bl))
16073 (if (org-mode-p) (setq bl nil)))
16074 (when (org-mode-p)
16075 (easy-menu-change
16076 '("Org") "File List for Agenda"
16077 (append
16078 (list
16079 ["Edit File List" (org-edit-agenda-file-list) t]
16080 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16081 ["Remove Current File from List" org-remove-file t]
16082 ["Cycle through agenda files" org-cycle-agenda-files t]
16083 ["Occur in all agenda files" org-occur-in-agenda-files t]
16084 "--")
16085 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16087 ;;;; Documentation
16089 ;;;###autoload
16090 (defun org-require-autoloaded-modules ()
16091 (interactive)
16092 (mapc 'require
16093 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16094 org-docbook org-exp org-html org-icalendar
16095 org-id org-latex
16096 org-publish org-remember org-table
16097 org-timer org-xoxo)))
16099 ;;;###autoload
16100 (defun org-reload (&optional uncompiled)
16101 "Reload all org lisp files.
16102 With prefix arg UNCOMPILED, load the uncompiled versions."
16103 (interactive "P")
16104 (require 'find-func)
16105 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16106 (dir-org (file-name-directory (org-find-library-name "org")))
16107 (dir-org-contrib (ignore-errors
16108 (file-name-directory
16109 (org-find-library-name "org-contribdir"))))
16110 (files
16111 (append (directory-files dir-org t file-re)
16112 (and dir-org-contrib
16113 (directory-files dir-org-contrib t file-re))))
16114 (remove-re (concat (if (featurep 'xemacs)
16115 "org-colview" "org-colview-xemacs")
16116 "\\'")))
16117 (setq files (mapcar 'file-name-sans-extension files))
16118 (setq files (mapcar
16119 (lambda (x) (if (string-match remove-re x) nil x))
16120 files))
16121 (setq files (delq nil files))
16122 (mapc
16123 (lambda (f)
16124 (when (featurep (intern (file-name-nondirectory f)))
16125 (if (and (not uncompiled)
16126 (file-exists-p (concat f ".elc")))
16127 (load (concat f ".elc") nil nil t)
16128 (load (concat f ".el") nil nil t))))
16129 files))
16130 (org-version))
16132 ;;;###autoload
16133 (defun org-customize ()
16134 "Call the customize function with org as argument."
16135 (interactive)
16136 (org-load-modules-maybe)
16137 (org-require-autoloaded-modules)
16138 (customize-browse 'org))
16140 (defun org-create-customize-menu ()
16141 "Create a full customization menu for Org-mode, insert it into the menu."
16142 (interactive)
16143 (org-load-modules-maybe)
16144 (org-require-autoloaded-modules)
16145 (if (fboundp 'customize-menu-create)
16146 (progn
16147 (easy-menu-change
16148 '("Org") "Customize"
16149 `(["Browse Org group" org-customize t]
16150 "--"
16151 ,(customize-menu-create 'org)
16152 ["Set" Custom-set t]
16153 ["Save" Custom-save t]
16154 ["Reset to Current" Custom-reset-current t]
16155 ["Reset to Saved" Custom-reset-saved t]
16156 ["Reset to Standard Settings" Custom-reset-standard t]))
16157 (message "\"Org\"-menu now contains full customization menu"))
16158 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16160 ;;;; Miscellaneous stuff
16162 ;;; Generally useful functions
16164 (defun org-get-at-bol (property)
16165 "Get text property PROPERTY at beginning of line."
16166 (get-text-property (point-at-bol) property))
16168 (defun org-find-text-property-in-string (prop s)
16169 "Return the first non-nil value of property PROP in string S."
16170 (or (get-text-property 0 prop s)
16171 (get-text-property (or (next-single-property-change 0 prop s) 0)
16172 prop s)))
16174 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16175 "Display the given MESSAGE as a warning."
16176 (if (fboundp 'display-warning)
16177 (display-warning 'org message
16178 (if (featurep 'xemacs)
16179 'warning
16180 :warning))
16181 (let ((buf (get-buffer-create "*Org warnings*")))
16182 (with-current-buffer buf
16183 (goto-char (point-max))
16184 (insert "Warning (Org): " message)
16185 (unless (bolp)
16186 (newline)))
16187 (display-buffer buf)
16188 (sit-for 0))))
16190 (defun org-in-commented-line ()
16191 "Is point in a line starting with `#'?"
16192 (equal (char-after (point-at-bol)) ?#))
16194 (defun org-in-verbatim-emphasis ()
16195 (save-match-data
16196 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16198 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16199 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16200 (if (and marker (marker-buffer marker)
16201 (buffer-live-p (marker-buffer marker)))
16202 (progn
16203 (switch-to-buffer (marker-buffer marker))
16204 (if (or (> marker (point-max)) (< marker (point-min)))
16205 (widen))
16206 (goto-char marker)
16207 (org-show-context 'org-goto))
16208 (if bookmark
16209 (bookmark-jump bookmark)
16210 (error "Cannot find location"))))
16212 (defun org-quote-csv-field (s)
16213 "Quote field for inclusion in CSV material."
16214 (if (string-match "[\",]" s)
16215 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16218 (defun org-plist-delete (plist property)
16219 "Delete PROPERTY from PLIST.
16220 This is in contrast to merely setting it to 0."
16221 (let (p)
16222 (while plist
16223 (if (not (eq property (car plist)))
16224 (setq p (plist-put p (car plist) (nth 1 plist))))
16225 (setq plist (cddr plist)))
16228 (defun org-force-self-insert (N)
16229 "Needed to enforce self-insert under remapping."
16230 (interactive "p")
16231 (self-insert-command N))
16233 (defun org-string-width (s)
16234 "Compute width of string, ignoring invisible characters.
16235 This ignores character with invisibility property `org-link', and also
16236 characters with property `org-cwidth', because these will become invisible
16237 upon the next fontification round."
16238 (let (b l)
16239 (when (or (eq t buffer-invisibility-spec)
16240 (assq 'org-link buffer-invisibility-spec))
16241 (while (setq b (text-property-any 0 (length s)
16242 'invisible 'org-link s))
16243 (setq s (concat (substring s 0 b)
16244 (substring s (or (next-single-property-change
16245 b 'invisible s) (length s)))))))
16246 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16247 (setq s (concat (substring s 0 b)
16248 (substring s (or (next-single-property-change
16249 b 'org-cwidth s) (length s))))))
16250 (setq l (string-width s) b -1)
16251 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16252 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16255 (defun org-get-indentation (&optional line)
16256 "Get the indentation of the current line, interpreting tabs.
16257 When LINE is given, assume it represents a line and compute its indentation."
16258 (if line
16259 (if (string-match "^ *" (org-remove-tabs line))
16260 (match-end 0))
16261 (save-excursion
16262 (beginning-of-line 1)
16263 (skip-chars-forward " \t")
16264 (current-column))))
16266 (defun org-remove-tabs (s &optional width)
16267 "Replace tabulators in S with spaces.
16268 Assumes that s is a single line, starting in column 0."
16269 (setq width (or width tab-width))
16270 (while (string-match "\t" s)
16271 (setq s (replace-match
16272 (make-string
16273 (- (* width (/ (+ (match-beginning 0) width) width))
16274 (match-beginning 0)) ?\ )
16275 t t s)))
16278 (defun org-fix-indentation (line ind)
16279 "Fix indentation in LINE.
16280 IND is a cons cell with target and minimum indentation.
16281 If the current indentation in LINE is smaller than the minimum,
16282 leave it alone. If it is larger than ind, set it to the target."
16283 (let* ((l (org-remove-tabs line))
16284 (i (org-get-indentation l))
16285 (i1 (car ind)) (i2 (cdr ind)))
16286 (if (>= i i2) (setq l (substring line i2)))
16287 (if (> i1 0)
16288 (concat (make-string i1 ?\ ) l)
16289 l)))
16291 (defun org-remove-indentation (code &optional n)
16292 "Remove the maximum common indentation from the lines in CODE.
16293 N may optionally be the number of spaces to remove."
16294 (with-temp-buffer
16295 (insert code)
16296 (org-do-remove-indentation n)
16297 (buffer-string)))
16299 (defun org-do-remove-indentation (&optional n)
16300 "Remove the maximum common indentation from the buffer."
16301 (untabify (point-min) (point-max))
16302 (let ((min 10000) re)
16303 (if n
16304 (setq min n)
16305 (goto-char (point-min))
16306 (while (re-search-forward "^ *[^ \n]" nil t)
16307 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16308 (unless (or (= min 0) (= min 10000))
16309 (setq re (format "^ \\{%d\\}" min))
16310 (goto-char (point-min))
16311 (while (re-search-forward re nil t)
16312 (replace-match "")
16313 (end-of-line 1))
16314 min)))
16316 (defun org-fill-template (template alist)
16317 "Find each %key of ALIST in TEMPLATE and replace it."
16318 (let (entry key value)
16319 (setq alist (sort (copy-sequence alist)
16320 (lambda (a b) (< (length (car a)) (length (car b))))))
16321 (while (setq entry (pop alist))
16322 (setq template
16323 (replace-regexp-in-string
16324 (concat "%" (regexp-quote (car entry)))
16325 (cdr entry) template t t)))
16326 template))
16328 (defun org-base-buffer (buffer)
16329 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16330 (if (not buffer)
16331 buffer
16332 (or (buffer-base-buffer buffer)
16333 buffer)))
16335 (defun org-trim (s)
16336 "Remove whitespace at beginning and end of string."
16337 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16338 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16341 (defun org-wrap (string &optional width lines)
16342 "Wrap string to either a number of lines, or a width in characters.
16343 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16344 that costs. If there is a word longer than WIDTH, the text is actually
16345 wrapped to the length of that word.
16346 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16347 many lines, whatever width that takes.
16348 The return value is a list of lines, without newlines at the end."
16349 (let* ((words (org-split-string string "[ \t\n]+"))
16350 (maxword (apply 'max (mapcar 'org-string-width words)))
16351 w ll)
16352 (cond (width
16353 (org-do-wrap words (max maxword width)))
16354 (lines
16355 (setq w maxword)
16356 (setq ll (org-do-wrap words maxword))
16357 (if (<= (length ll) lines)
16359 (setq ll words)
16360 (while (> (length ll) lines)
16361 (setq w (1+ w))
16362 (setq ll (org-do-wrap words w)))
16363 ll))
16364 (t (error "Cannot wrap this")))))
16366 (defun org-do-wrap (words width)
16367 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16368 (let (lines line)
16369 (while words
16370 (setq line (pop words))
16371 (while (and words (< (+ (length line) (length (car words))) width))
16372 (setq line (concat line " " (pop words))))
16373 (setq lines (push line lines)))
16374 (nreverse lines)))
16376 (defun org-split-string (string &optional separators)
16377 "Splits STRING into substrings at SEPARATORS.
16378 No empty strings are returned if there are matches at the beginning
16379 and end of string."
16380 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16381 (start 0)
16382 notfirst
16383 (list nil))
16384 (while (and (string-match rexp string
16385 (if (and notfirst
16386 (= start (match-beginning 0))
16387 (< start (length string)))
16388 (1+ start) start))
16389 (< (match-beginning 0) (length string)))
16390 (setq notfirst t)
16391 (or (eq (match-beginning 0) 0)
16392 (and (eq (match-beginning 0) (match-end 0))
16393 (eq (match-beginning 0) start))
16394 (setq list
16395 (cons (substring string start (match-beginning 0))
16396 list)))
16397 (setq start (match-end 0)))
16398 (or (eq start (length string))
16399 (setq list
16400 (cons (substring string start)
16401 list)))
16402 (nreverse list)))
16404 (defun org-quote-vert (s)
16405 "Replace \"|\" with \"\\vert\"."
16406 (while (string-match "|" s)
16407 (setq s (replace-match "\\vert" t t s)))
16410 (defun org-uuidgen-p (s)
16411 "Is S an ID created by UUIDGEN?"
16412 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16414 (defun org-context ()
16415 "Return a list of contexts of the current cursor position.
16416 If several contexts apply, all are returned.
16417 Each context entry is a list with a symbol naming the context, and
16418 two positions indicating start and end of the context. Possible
16419 contexts are:
16421 :headline anywhere in a headline
16422 :headline-stars on the leading stars in a headline
16423 :todo-keyword on a TODO keyword (including DONE) in a headline
16424 :tags on the TAGS in a headline
16425 :priority on the priority cookie in a headline
16426 :item on the first line of a plain list item
16427 :item-bullet on the bullet/number of a plain list item
16428 :checkbox on the checkbox in a plain list item
16429 :table in an org-mode table
16430 :table-special on a special filed in a table
16431 :table-table in a table.el table
16432 :link on a hyperlink
16433 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16434 :target on a <<target>>
16435 :radio-target on a <<<radio-target>>>
16436 :latex-fragment on a LaTeX fragment
16437 :latex-preview on a LaTeX fragment with overlayed preview image
16439 This function expects the position to be visible because it uses font-lock
16440 faces as a help to recognize the following contexts: :table-special, :link,
16441 and :keyword."
16442 (let* ((f (get-text-property (point) 'face))
16443 (faces (if (listp f) f (list f)))
16444 (p (point)) clist o)
16445 ;; First the large context
16446 (cond
16447 ((org-on-heading-p t)
16448 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16449 (when (progn
16450 (beginning-of-line 1)
16451 (looking-at org-todo-line-tags-regexp))
16452 (push (org-point-in-group p 1 :headline-stars) clist)
16453 (push (org-point-in-group p 2 :todo-keyword) clist)
16454 (push (org-point-in-group p 4 :tags) clist))
16455 (goto-char p)
16456 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16457 (if (looking-at "\\[#[A-Z0-9]\\]")
16458 (push (org-point-in-group p 0 :priority) clist)))
16460 ((org-at-item-p)
16461 (push (org-point-in-group p 2 :item-bullet) clist)
16462 (push (list :item (point-at-bol)
16463 (save-excursion (org-end-of-item) (point)))
16464 clist)
16465 (and (org-at-item-checkbox-p)
16466 (push (org-point-in-group p 0 :checkbox) clist)))
16468 ((org-at-table-p)
16469 (push (list :table (org-table-begin) (org-table-end)) clist)
16470 (if (memq 'org-formula faces)
16471 (push (list :table-special
16472 (previous-single-property-change p 'face)
16473 (next-single-property-change p 'face)) clist)))
16474 ((org-at-table-p 'any)
16475 (push (list :table-table) clist)))
16476 (goto-char p)
16478 ;; Now the small context
16479 (cond
16480 ((org-at-timestamp-p)
16481 (push (org-point-in-group p 0 :timestamp) clist))
16482 ((memq 'org-link faces)
16483 (push (list :link
16484 (previous-single-property-change p 'face)
16485 (next-single-property-change p 'face)) clist))
16486 ((memq 'org-special-keyword faces)
16487 (push (list :keyword
16488 (previous-single-property-change p 'face)
16489 (next-single-property-change p 'face)) clist))
16490 ((org-on-target-p)
16491 (push (org-point-in-group p 0 :target) clist)
16492 (goto-char (1- (match-beginning 0)))
16493 (if (looking-at org-radio-target-regexp)
16494 (push (org-point-in-group p 0 :radio-target) clist))
16495 (goto-char p))
16496 ((setq o (car (delq nil
16497 (mapcar
16498 (lambda (x)
16499 (if (memq x org-latex-fragment-image-overlays) x))
16500 (org-overlays-at (point))))))
16501 (push (list :latex-fragment
16502 (org-overlay-start o) (org-overlay-end o)) clist)
16503 (push (list :latex-preview
16504 (org-overlay-start o) (org-overlay-end o)) clist))
16505 ((org-inside-LaTeX-fragment-p)
16506 ;; FIXME: positions wrong.
16507 (push (list :latex-fragment (point) (point)) clist)))
16509 (setq clist (nreverse (delq nil clist)))
16510 clist))
16512 ;; FIXME: Compare with at-regexp-p Do we need both?
16513 (defun org-in-regexp (re &optional nlines visually)
16514 "Check if point is inside a match of regexp.
16515 Normally only the current line is checked, but you can include NLINES extra
16516 lines both before and after point into the search.
16517 If VISUALLY is set, require that the cursor is not after the match but
16518 really on, so that the block visually is on the match."
16519 (catch 'exit
16520 (let ((pos (point))
16521 (eol (point-at-eol (+ 1 (or nlines 0))))
16522 (inc (if visually 1 0)))
16523 (save-excursion
16524 (beginning-of-line (- 1 (or nlines 0)))
16525 (while (re-search-forward re eol t)
16526 (if (and (<= (match-beginning 0) pos)
16527 (>= (+ inc (match-end 0)) pos))
16528 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16530 (defun org-at-regexp-p (regexp)
16531 "Is point inside a match of REGEXP in the current line?"
16532 (catch 'exit
16533 (save-excursion
16534 (let ((pos (point)) (end (point-at-eol)))
16535 (beginning-of-line 1)
16536 (while (re-search-forward regexp end t)
16537 (if (and (<= (match-beginning 0) pos)
16538 (>= (match-end 0) pos))
16539 (throw 'exit t)))
16540 nil))))
16542 (defun org-occur-in-agenda-files (regexp &optional nlines)
16543 "Call `multi-occur' with buffers for all agenda files."
16544 (interactive "sOrg-files matching: \np")
16545 (let* ((files (org-agenda-files))
16546 (tnames (mapcar 'file-truename files))
16547 (extra org-agenda-text-search-extra-files)
16549 (when (eq (car extra) 'agenda-archives)
16550 (setq extra (cdr extra))
16551 (setq files (org-add-archive-files files)))
16552 (while (setq f (pop extra))
16553 (unless (member (file-truename f) tnames)
16554 (add-to-list 'files f 'append)
16555 (add-to-list 'tnames (file-truename f) 'append)))
16556 (multi-occur
16557 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16558 regexp)))
16560 (if (boundp 'occur-mode-find-occurrence-hook)
16561 ;; Emacs 23
16562 (add-hook 'occur-mode-find-occurrence-hook
16563 (lambda ()
16564 (when (org-mode-p)
16565 (org-reveal))))
16566 ;; Emacs 22
16567 (defadvice occur-mode-goto-occurrence
16568 (after org-occur-reveal activate)
16569 (and (org-mode-p) (org-reveal)))
16570 (defadvice occur-mode-goto-occurrence-other-window
16571 (after org-occur-reveal activate)
16572 (and (org-mode-p) (org-reveal)))
16573 (defadvice occur-mode-display-occurrence
16574 (after org-occur-reveal activate)
16575 (when (org-mode-p)
16576 (let ((pos (occur-mode-find-occurrence)))
16577 (with-current-buffer (marker-buffer pos)
16578 (save-excursion
16579 (goto-char pos)
16580 (org-reveal)))))))
16582 (defun org-occur-link-in-agenda-files ()
16583 "Create a link and search for it in the agendas.
16584 The link is not stored in `org-stored-links', it is just created
16585 for the search purpose."
16586 (interactive)
16587 (let ((link (condition-case nil
16588 (org-store-link nil)
16589 (error "Unable to create a link to here"))))
16590 (org-occur-in-agenda-files (regexp-quote link))))
16592 (defun org-uniquify (list)
16593 "Remove duplicate elements from LIST."
16594 (let (res)
16595 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16596 res))
16598 (defun org-delete-all (elts list)
16599 "Remove all elements in ELTS from LIST."
16600 (while elts
16601 (setq list (delete (pop elts) list)))
16602 list)
16604 (defun org-back-over-empty-lines ()
16605 "Move backwards over whitespace, to the beginning of the first empty line.
16606 Returns the number of empty lines passed."
16607 (let ((pos (point)))
16608 (skip-chars-backward " \t\n\r")
16609 (beginning-of-line 2)
16610 (goto-char (min (point) pos))
16611 (count-lines (point) pos)))
16613 (defun org-skip-whitespace ()
16614 (skip-chars-forward " \t\n\r"))
16616 (defun org-point-in-group (point group &optional context)
16617 "Check if POINT is in match-group GROUP.
16618 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16619 match. If the match group does ot exist or point is not inside it,
16620 return nil."
16621 (and (match-beginning group)
16622 (>= point (match-beginning group))
16623 (<= point (match-end group))
16624 (if context
16625 (list context (match-beginning group) (match-end group))
16626 t)))
16628 (defun org-switch-to-buffer-other-window (&rest args)
16629 "Switch to buffer in a second window on the current frame.
16630 In particular, do not allow pop-up frames."
16631 (let (pop-up-frames special-display-buffer-names special-display-regexps
16632 special-display-function)
16633 (apply 'switch-to-buffer-other-window args)))
16635 (defun org-combine-plists (&rest plists)
16636 "Create a single property list from all plists in PLISTS.
16637 The process starts by copying the first list, and then setting properties
16638 from the other lists. Settings in the last list are the most significant
16639 ones and overrule settings in the other lists."
16640 (let ((rtn (copy-sequence (pop plists)))
16641 p v ls)
16642 (while plists
16643 (setq ls (pop plists))
16644 (while ls
16645 (setq p (pop ls) v (pop ls))
16646 (setq rtn (plist-put rtn p v))))
16647 rtn))
16649 (defun org-move-line-down (arg)
16650 "Move the current line down. With prefix argument, move it past ARG lines."
16651 (interactive "p")
16652 (let ((col (current-column))
16653 beg end pos)
16654 (beginning-of-line 1) (setq beg (point))
16655 (beginning-of-line 2) (setq end (point))
16656 (beginning-of-line (+ 1 arg))
16657 (setq pos (move-marker (make-marker) (point)))
16658 (insert (delete-and-extract-region beg end))
16659 (goto-char pos)
16660 (org-move-to-column col)))
16662 (defun org-move-line-up (arg)
16663 "Move the current line up. With prefix argument, move it past ARG lines."
16664 (interactive "p")
16665 (let ((col (current-column))
16666 beg end pos)
16667 (beginning-of-line 1) (setq beg (point))
16668 (beginning-of-line 2) (setq end (point))
16669 (beginning-of-line (- arg))
16670 (setq pos (move-marker (make-marker) (point)))
16671 (insert (delete-and-extract-region beg end))
16672 (goto-char pos)
16673 (org-move-to-column col)))
16675 (defun org-replace-escapes (string table)
16676 "Replace %-escapes in STRING with values in TABLE.
16677 TABLE is an association list with keys like \"%a\" and string values.
16678 The sequences in STRING may contain normal field width and padding information,
16679 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16680 so values can contain further %-escapes if they are define later in TABLE."
16681 (let ((case-fold-search nil)
16682 e re rpl)
16683 (while (setq e (pop table))
16684 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16685 (while (string-match re string)
16686 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16687 (cdr e)))
16688 (setq string (replace-match rpl t t string))))
16689 string))
16692 (defun org-sublist (list start end)
16693 "Return a section of LIST, from START to END.
16694 Counting starts at 1."
16695 (let (rtn (c start))
16696 (setq list (nthcdr (1- start) list))
16697 (while (and list (<= c end))
16698 (push (pop list) rtn)
16699 (setq c (1+ c)))
16700 (nreverse rtn)))
16702 (defun org-find-base-buffer-visiting (file)
16703 "Like `find-buffer-visiting' but always return the base buffer and
16704 not an indirect buffer."
16705 (let ((buf (or (get-file-buffer file)
16706 (find-buffer-visiting file))))
16707 (if buf
16708 (or (buffer-base-buffer buf) buf)
16709 nil)))
16711 (defun org-image-file-name-regexp (&optional extensions)
16712 "Return regexp matching the file names of images.
16713 If EXTENSIONS is given, only match these."
16714 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16715 (image-file-name-regexp)
16716 (let ((image-file-name-extensions
16717 (or extensions
16718 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16719 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16720 (concat "\\."
16721 (regexp-opt (nconc (mapcar 'upcase
16722 image-file-name-extensions)
16723 image-file-name-extensions)
16725 "\\'"))))
16727 (defun org-file-image-p (file &optional extensions)
16728 "Return non-nil if FILE is an image."
16729 (save-match-data
16730 (string-match (org-image-file-name-regexp extensions) file)))
16732 (defun org-get-cursor-date ()
16733 "Return the date at cursor in as a time.
16734 This works in the calendar and in the agenda, anywhere else it just
16735 returns the current time."
16736 (let (date day defd)
16737 (cond
16738 ((eq major-mode 'calendar-mode)
16739 (setq date (calendar-cursor-to-date)
16740 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16741 ((eq major-mode 'org-agenda-mode)
16742 (setq day (get-text-property (point) 'day))
16743 (if day
16744 (setq date (calendar-gregorian-from-absolute day)
16745 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16746 (nth 2 date))))))
16747 (or defd (current-time))))
16749 (defvar org-agenda-action-marker (make-marker)
16750 "Marker pointing to the entry for the next agenda action.")
16752 (defun org-mark-entry-for-agenda-action ()
16753 "Mark the current entry as target of an agenda action.
16754 Agenda actions are actions executed from the agenda with the key `k',
16755 which make use of the date at the cursor."
16756 (interactive)
16757 (move-marker org-agenda-action-marker
16758 (save-excursion (org-back-to-heading t) (point))
16759 (current-buffer))
16760 (message
16761 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16763 ;;; Paragraph filling stuff.
16764 ;; We want this to be just right, so use the full arsenal.
16766 (defun org-indent-line-function ()
16767 "Indent line like previous, but further if previous was headline or item."
16768 (interactive)
16769 (let* ((pos (point))
16770 (itemp (org-at-item-p))
16771 (case-fold-search t)
16772 (org-drawer-regexp (or org-drawer-regexp "\000"))
16773 column bpos bcol tpos tcol bullet btype bullet-type)
16774 ;; Find the previous relevant line
16775 (beginning-of-line 1)
16776 (cond
16777 ((looking-at "#") (setq column 0))
16778 ((looking-at "\\*+ ") (setq column 0))
16779 ((and (looking-at "[ \t]*:END:")
16780 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16781 (save-excursion
16782 (goto-char (1- (match-beginning 1)))
16783 (setq column (current-column))))
16784 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16785 (save-excursion
16786 (re-search-backward
16787 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16788 (setq column (org-get-indentation (match-string 0))))
16790 (beginning-of-line 0)
16791 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16792 (not (looking-at "[ \t]*:END:"))
16793 (not (looking-at org-drawer-regexp)))
16794 (beginning-of-line 0))
16795 (cond
16796 ((looking-at "\\*+[ \t]+")
16797 (if (not org-adapt-indentation)
16798 (setq column 0)
16799 (goto-char (match-end 0))
16800 (setq column (current-column))))
16801 ((looking-at org-drawer-regexp)
16802 (goto-char (1- (match-beginning 1)))
16803 (setq column (current-column)))
16804 ((looking-at "\\([ \t]*\\):END:")
16805 (goto-char (match-end 1))
16806 (setq column (current-column)))
16807 ((org-in-item-p)
16808 (org-beginning-of-item)
16809 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16810 (setq bpos (match-beginning 1) tpos (match-end 0)
16811 bcol (progn (goto-char bpos) (current-column))
16812 tcol (progn (goto-char tpos) (current-column))
16813 bullet (match-string 1)
16814 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16815 (if (> tcol (+ bcol org-description-max-indent))
16816 (setq tcol (+ bcol 5)))
16817 (if (not itemp)
16818 (setq column tcol)
16819 (goto-char pos)
16820 (beginning-of-line 1)
16821 (if (looking-at "\\S-")
16822 (progn
16823 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16824 (setq bullet (match-string 1)
16825 btype (if (string-match "[0-9]" bullet) "n" bullet))
16826 (setq column (if (equal btype bullet-type) bcol tcol)))
16827 (setq column (org-get-indentation)))))
16828 (t (setq column (org-get-indentation))))))
16829 (goto-char pos)
16830 (if (<= (current-column) (current-indentation))
16831 (org-indent-line-to column)
16832 (save-excursion (org-indent-line-to column)))
16833 (setq column (current-column))
16834 (beginning-of-line 1)
16835 (if (looking-at
16836 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16837 (replace-match (concat (match-string 1)
16838 (format org-property-format
16839 (match-string 2) (match-string 3)))
16840 t t))
16841 (org-move-to-column column)))
16843 (defun org-set-autofill-regexps ()
16844 (interactive)
16845 ;; In the paragraph separator we include headlines, because filling
16846 ;; text in a line directly attached to a headline would otherwise
16847 ;; fill the headline as well.
16848 (org-set-local 'comment-start-skip "^#+[ \t]*")
16849 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16850 ;; The paragraph starter includes hand-formatted lists.
16851 (org-set-local
16852 'paragraph-start
16853 (concat
16854 "\f" "\\|"
16855 "[ ]*$" "\\|"
16856 "\\*+ " "\\|"
16857 "[ \t]*#" "\\|"
16858 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16859 "[ \t]*[:|]" "\\|"
16860 "\\$\\$" "\\|"
16861 "\\\\\\(begin\\|end\\|[][]\\)"))
16862 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16863 ;; But only if the user has not turned off tables or fixed-width regions
16864 (org-set-local
16865 'auto-fill-inhibit-regexp
16866 (concat "\\*+ \\|#\\+"
16867 "\\|[ \t]*" org-keyword-time-regexp
16868 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16869 (concat
16870 "\\|[ \t]*["
16871 (if org-enable-table-editor "|" "")
16872 (if org-enable-fixed-width-editor ":" "")
16873 "]"))))
16874 ;; We use our own fill-paragraph function, to make sure that tables
16875 ;; and fixed-width regions are not wrapped. That function will pass
16876 ;; through to `fill-paragraph' when appropriate.
16877 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16878 ; Adaptive filling: To get full control, first make sure that
16879 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16880 (org-set-local 'adaptive-fill-regexp "\000")
16881 (org-set-local 'adaptive-fill-function
16882 'org-adaptive-fill-function)
16883 (org-set-local
16884 'align-mode-rules-list
16885 '((org-in-buffer-settings
16886 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16887 (modes . '(org-mode))))))
16889 (defun org-fill-paragraph (&optional justify)
16890 "Re-align a table, pass through to fill-paragraph if no table."
16891 (let ((table-p (org-at-table-p))
16892 (table.el-p (org-at-table.el-p)))
16893 (cond ((and (equal (char-after (point-at-bol)) ?*)
16894 (save-excursion (goto-char (point-at-bol))
16895 (looking-at outline-regexp)))
16896 t) ; skip headlines
16897 (table.el-p t) ; skip table.el tables
16898 (table-p (org-table-align) t) ; align org-mode tables
16899 (t nil)))) ; call paragraph-fill
16901 ;; For reference, this is the default value of adaptive-fill-regexp
16902 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16904 (defun org-adaptive-fill-function ()
16905 "Return a fill prefix for org-mode files.
16906 In particular, this makes sure hanging paragraphs for hand-formatted lists
16907 work correctly."
16908 (cond ((looking-at "#[ \t]+")
16909 (match-string 0))
16910 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16911 (save-excursion
16912 (if (> (match-end 1) (+ (match-beginning 1)
16913 org-description-max-indent))
16914 (goto-char (+ (match-beginning 1) 5))
16915 (goto-char (match-end 0)))
16916 (make-string (current-column) ?\ )))
16917 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16918 (save-excursion
16919 (goto-char (match-end 0))
16920 (make-string (current-column) ?\ )))
16921 (t nil)))
16923 ;;; Other stuff.
16925 (defun org-toggle-fixed-width-section (arg)
16926 "Toggle the fixed-width export.
16927 If there is no active region, the QUOTE keyword at the current headline is
16928 inserted or removed. When present, it causes the text between this headline
16929 and the next to be exported as fixed-width text, and unmodified.
16930 If there is an active region, this command adds or removes a colon as the
16931 first character of this line. If the first character of a line is a colon,
16932 this line is also exported in fixed-width font."
16933 (interactive "P")
16934 (let* ((cc 0)
16935 (regionp (org-region-active-p))
16936 (beg (if regionp (region-beginning) (point)))
16937 (end (if regionp (region-end)))
16938 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16939 (case-fold-search nil)
16940 (re "[ \t]*\\(: \\)")
16941 off)
16942 (if regionp
16943 (save-excursion
16944 (goto-char beg)
16945 (setq cc (current-column))
16946 (beginning-of-line 1)
16947 (setq off (looking-at re))
16948 (while (> nlines 0)
16949 (setq nlines (1- nlines))
16950 (beginning-of-line 1)
16951 (cond
16952 (arg
16953 (org-move-to-column cc t)
16954 (insert ": \n")
16955 (forward-line -1))
16956 ((and off (looking-at re))
16957 (replace-match "" t t nil 1))
16958 ((not off) (org-move-to-column cc t) (insert ": ")))
16959 (forward-line 1)))
16960 (save-excursion
16961 (org-back-to-heading)
16962 (if (looking-at (concat outline-regexp
16963 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16964 (replace-match "" t t nil 1)
16965 (if (looking-at outline-regexp)
16966 (progn
16967 (goto-char (match-end 0))
16968 (insert org-quote-string " "))))))))
16970 (defun org-reftex-citation ()
16971 "Use reftex-citation to insert a citation into the buffer.
16972 This looks for a line like
16974 #+BIBLIOGRAPHY: foo plain option:-d
16976 and derives from it that foo.bib is the bbliography file relevant
16977 for this document. It then installs the necessary environment for RefTeX
16978 to work in this buffer and calls `reftex-citation' to insert a citation
16979 into the buffer.
16981 Export of such citations to both LaTeX and HTML is handled by the contributed
16982 package org-exp-bibtex by Taru Karttunen."
16983 (interactive)
16984 (let ((reftex-docstruct-symbol 'rds)
16985 (reftex-cite-format "\\cite{%l}")
16986 rds bib)
16987 (save-excursion
16988 (save-restriction
16989 (widen)
16990 (let ((case-fold-search t)
16991 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16992 (if (not (save-excursion
16993 (or (re-search-forward re nil t)
16994 (re-search-backward re nil t))))
16995 (error "No bibliography defined in file")
16996 (setq bib (concat (match-string 1) ".bib")
16997 rds (list (list 'bib bib)))))))
16998 (call-interactively 'reftex-citation)))
17000 ;;;; Functions extending outline functionality
17002 (defun org-beginning-of-line (&optional arg)
17003 "Go to the beginning of the current line. If that is invisible, continue
17004 to a visible line beginning. This makes the function of C-a more intuitive.
17005 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17006 first attempt, and only move to after the tags when the cursor is already
17007 beyond the end of the headline."
17008 (interactive "P")
17009 (let ((pos (point))
17010 (special (if (consp org-special-ctrl-a/e)
17011 (car org-special-ctrl-a/e)
17012 org-special-ctrl-a/e))
17013 refpos)
17014 (if (org-bound-and-true-p line-move-visual)
17015 (beginning-of-visual-line 1)
17016 (beginning-of-line 1))
17017 (if (and arg (fboundp 'move-beginning-of-line))
17018 (call-interactively 'move-beginning-of-line)
17019 (if (bobp)
17021 (backward-char 1)
17022 (if (org-invisible-p)
17023 (while (and (not (bobp)) (org-invisible-p))
17024 (backward-char 1)
17025 (beginning-of-line 1))
17026 (forward-char 1))))
17027 (when special
17028 (cond
17029 ((and (looking-at org-complex-heading-regexp)
17030 (= (char-after (match-end 1)) ?\ ))
17031 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17032 (point-at-eol)))
17033 (goto-char
17034 (if (eq special t)
17035 (cond ((> pos refpos) refpos)
17036 ((= pos (point)) refpos)
17037 (t (point)))
17038 (cond ((> pos (point)) (point))
17039 ((not (eq last-command this-command)) (point))
17040 (t refpos)))))
17041 ((org-at-item-p)
17042 (goto-char
17043 (if (eq special t)
17044 (cond ((> pos (match-end 4)) (match-end 4))
17045 ((= pos (point)) (match-end 4))
17046 (t (point)))
17047 (cond ((> pos (point)) (point))
17048 ((not (eq last-command this-command)) (point))
17049 (t (match-end 4))))))))
17050 (org-no-warnings
17051 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17053 (defun org-end-of-line (&optional arg)
17054 "Go to the end of the line.
17055 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17056 first attempt, and only move to after the tags when the cursor is already
17057 beyond the end of the headline."
17058 (interactive "P")
17059 (let ((special (if (consp org-special-ctrl-a/e)
17060 (cdr org-special-ctrl-a/e)
17061 org-special-ctrl-a/e)))
17062 (if (or (not special)
17063 (not (org-on-heading-p))
17064 arg)
17065 (call-interactively
17066 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17067 ((fboundp 'move-end-of-line) 'move-end-of-line)
17068 (t 'end-of-line)))
17069 (let ((pos (point)))
17070 (beginning-of-line 1)
17071 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17072 (if (eq special t)
17073 (if (or (< pos (match-beginning 1))
17074 (= pos (match-end 0)))
17075 (goto-char (match-beginning 1))
17076 (goto-char (match-end 0)))
17077 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17078 (goto-char (match-end 0))
17079 (goto-char (match-beginning 1))))
17080 (call-interactively (if (fboundp 'move-end-of-line)
17081 'move-end-of-line
17082 'end-of-line)))))
17083 (org-no-warnings
17084 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17086 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17087 (define-key org-mode-map "\C-e" 'org-end-of-line)
17088 (define-key org-mode-map [home] 'org-beginning-of-line)
17089 (define-key org-mode-map [end] 'org-end-of-line)
17091 (defun org-backward-sentence (&optional arg)
17092 "Go to beginning of sentence, or beginning of table field.
17093 This will call `backward-sentence' or `org-table-beginning-of-field',
17094 depending on context."
17095 (interactive "P")
17096 (cond
17097 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17098 (t (call-interactively 'backward-sentence))))
17100 (defun org-forward-sentence (&optional arg)
17101 "Go to end of sentence, or end of table field.
17102 This will call `forward-sentence' or `org-table-end-of-field',
17103 depending on context."
17104 (interactive "P")
17105 (cond
17106 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17107 (t (call-interactively 'forward-sentence))))
17109 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17110 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17112 (defun org-kill-line (&optional arg)
17113 "Kill line, to tags or end of line."
17114 (interactive "P")
17115 (cond
17116 ((or (not org-special-ctrl-k)
17117 (bolp)
17118 (not (org-on-heading-p)))
17119 (call-interactively 'kill-line))
17120 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17121 (kill-region (point) (match-beginning 1))
17122 (org-set-tags nil t))
17123 (t (kill-region (point) (point-at-eol)))))
17125 (define-key org-mode-map "\C-k" 'org-kill-line)
17127 (defun org-yank (&optional arg)
17128 "Yank. If the kill is a subtree, treat it specially.
17129 This command will look at the current kill and check if is a single
17130 subtree, or a series of subtrees[1]. If it passes the test, and if the
17131 cursor is at the beginning of a line or after the stars of a currently
17132 empty headline, then the yank is handled specially. How exactly depends
17133 on the value of the following variables, both set by default.
17135 org-yank-folded-subtrees
17136 When set, the subtree(s) will be folded after insertion, but only
17137 if doing so would now swallow text after the yanked text.
17139 org-yank-adjusted-subtrees
17140 When set, the subtree will be promoted or demoted in order to
17141 fit into the local outline tree structure, which means that the level
17142 will be adjusted so that it becomes the smaller one of the two
17143 *visible* surrounding headings.
17145 Any prefix to this command will cause `yank' to be called directly with
17146 no special treatment. In particular, a simple `C-u' prefix will just
17147 plainly yank the text as it is.
17149 \[1] The test checks if the first non-white line is a heading
17150 and if there are no other headings with fewer stars."
17151 (interactive "P")
17152 (org-yank-generic 'yank arg))
17154 (defun org-yank-generic (command arg)
17155 "Perform some yank-like command.
17157 This function implements the behavior described in the `org-yank'
17158 documentation. However, it has been generalized to work for any
17159 interactive command with similar behavior."
17161 ;; pretend to be command COMMAND
17162 (setq this-command command)
17164 (if arg
17165 (call-interactively command)
17167 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17168 (and (org-kill-is-subtree-p)
17169 (or (bolp)
17170 (and (looking-at "[ \t]*$")
17171 (string-match
17172 "\\`\\*+\\'"
17173 (buffer-substring (point-at-bol) (point)))))))
17174 swallowp)
17175 (cond
17176 ((and subtreep org-yank-folded-subtrees)
17177 (let ((beg (point))
17178 end)
17179 (if (and subtreep org-yank-adjusted-subtrees)
17180 (org-paste-subtree nil nil 'for-yank)
17181 (call-interactively command))
17183 (setq end (point))
17184 (goto-char beg)
17185 (when (and (bolp) subtreep
17186 (not (setq swallowp
17187 (org-yank-folding-would-swallow-text beg end))))
17188 (or (looking-at outline-regexp)
17189 (re-search-forward (concat "^" outline-regexp) end t))
17190 (while (and (< (point) end) (looking-at outline-regexp))
17191 (hide-subtree)
17192 (org-cycle-show-empty-lines 'folded)
17193 (condition-case nil
17194 (outline-forward-same-level 1)
17195 (error (goto-char end)))))
17196 (when swallowp
17197 (message
17198 "Inserted text not folded because that would swallow text"))
17200 (goto-char end)
17201 (skip-chars-forward " \t\n\r")
17202 (beginning-of-line 1)
17203 (push-mark beg 'nomsg)))
17204 ((and subtreep org-yank-adjusted-subtrees)
17205 (let ((beg (point-at-bol)))
17206 (org-paste-subtree nil nil 'for-yank)
17207 (push-mark beg 'nomsg)))
17209 (call-interactively command))))))
17211 (defun org-yank-folding-would-swallow-text (beg end)
17212 "Would hide-subtree at BEG swallow any text after END?"
17213 (let (level)
17214 (save-excursion
17215 (goto-char beg)
17216 (when (or (looking-at outline-regexp)
17217 (re-search-forward (concat "^" outline-regexp) end t))
17218 (setq level (org-outline-level)))
17219 (goto-char end)
17220 (skip-chars-forward " \t\r\n\v\f")
17221 (if (or (eobp)
17222 (and (bolp) (looking-at org-outline-regexp)
17223 (<= (org-outline-level) level)))
17224 nil ; Nothing would be swallowed
17225 t)))) ; something would swallow
17227 (define-key org-mode-map "\C-y" 'org-yank)
17229 (defun org-invisible-p ()
17230 "Check if point is at a character currently not visible."
17231 ;; Early versions of noutline don't have `outline-invisible-p'.
17232 (if (fboundp 'outline-invisible-p)
17233 (outline-invisible-p)
17234 (get-char-property (point) 'invisible)))
17236 (defun org-invisible-p2 ()
17237 "Check if point is at a character currently not visible."
17238 (save-excursion
17239 (if (and (eolp) (not (bobp))) (backward-char 1))
17240 ;; Early versions of noutline don't have `outline-invisible-p'.
17241 (if (fboundp 'outline-invisible-p)
17242 (outline-invisible-p)
17243 (get-char-property (point) 'invisible))))
17245 (defun org-back-to-heading (&optional invisible-ok)
17246 "Call `outline-back-to-heading', but provide a better error message."
17247 (condition-case nil
17248 (outline-back-to-heading invisible-ok)
17249 (error (error "Before first headline at position %d in buffer %s"
17250 (point) (current-buffer)))))
17252 (defun org-before-first-heading-p ()
17253 "Before first heading?"
17254 (save-excursion
17255 (null (re-search-backward "^\\*+ " nil t))))
17257 (defun org-on-heading-p (&optional ignored)
17258 (outline-on-heading-p t))
17259 (defun org-at-heading-p (&optional ignored)
17260 (outline-on-heading-p t))
17262 (defun org-at-heading-or-item-p ()
17263 (or (org-on-heading-p) (org-at-item-p)))
17265 (defun org-on-target-p ()
17266 (or (org-in-regexp org-radio-target-regexp)
17267 (org-in-regexp org-target-regexp)))
17269 (defun org-up-heading-all (arg)
17270 "Move to the heading line of which the present line is a subheading.
17271 This function considers both visible and invisible heading lines.
17272 With argument, move up ARG levels."
17273 (if (fboundp 'outline-up-heading-all)
17274 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17275 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17277 (defun org-up-heading-safe ()
17278 "Move to the heading line of which the present line is a subheading.
17279 This version will not throw an error. It will return the level of the
17280 headline found, or nil if no higher level is found.
17282 Also, this function will be a lot faster than `outline-up-heading',
17283 because it relies on stars being the outline starters. This can really
17284 make a significant difference in outlines with very many siblings."
17285 (let (start-level re)
17286 (org-back-to-heading t)
17287 (setq start-level (funcall outline-level))
17288 (if (equal start-level 1)
17290 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17291 (if (re-search-backward re nil t)
17292 (funcall outline-level)))))
17294 (defun org-first-sibling-p ()
17295 "Is this heading the first child of its parents?"
17296 (interactive)
17297 (let ((re (concat "^" outline-regexp))
17298 level l)
17299 (unless (org-at-heading-p t)
17300 (error "Not at a heading"))
17301 (setq level (funcall outline-level))
17302 (save-excursion
17303 (if (not (re-search-backward re nil t))
17305 (setq l (funcall outline-level))
17306 (< l level)))))
17308 (defun org-goto-sibling (&optional previous)
17309 "Goto the next sibling, even if it is invisible.
17310 When PREVIOUS is set, go to the previous sibling instead. Returns t
17311 when a sibling was found. When none is found, return nil and don't
17312 move point."
17313 (let ((fun (if previous 're-search-backward 're-search-forward))
17314 (pos (point))
17315 (re (concat "^" outline-regexp))
17316 level l)
17317 (when (condition-case nil (org-back-to-heading t) (error nil))
17318 (setq level (funcall outline-level))
17319 (catch 'exit
17320 (or previous (forward-char 1))
17321 (while (funcall fun re nil t)
17322 (setq l (funcall outline-level))
17323 (when (< l level) (goto-char pos) (throw 'exit nil))
17324 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17325 (goto-char pos)
17326 nil))))
17328 (defun org-show-siblings ()
17329 "Show all siblings of the current headline."
17330 (save-excursion
17331 (while (org-goto-sibling) (org-flag-heading nil)))
17332 (save-excursion
17333 (while (org-goto-sibling 'previous)
17334 (org-flag-heading nil))))
17336 (defun org-show-hidden-entry ()
17337 "Show an entry where even the heading is hidden."
17338 (save-excursion
17339 (org-show-entry)))
17341 (defun org-flag-heading (flag &optional entry)
17342 "Flag the current heading. FLAG non-nil means make invisible.
17343 When ENTRY is non-nil, show the entire entry."
17344 (save-excursion
17345 (org-back-to-heading t)
17346 ;; Check if we should show the entire entry
17347 (if entry
17348 (progn
17349 (org-show-entry)
17350 (save-excursion
17351 (and (outline-next-heading)
17352 (org-flag-heading nil))))
17353 (outline-flag-region (max (point-min) (1- (point)))
17354 (save-excursion (outline-end-of-heading) (point))
17355 flag))))
17357 (defun org-get-next-sibling ()
17358 "Move to next heading of the same level, and return point.
17359 If there is no such heading, return nil.
17360 This is like outline-next-sibling, but invisible headings are ok."
17361 (let ((level (funcall outline-level)))
17362 (outline-next-heading)
17363 (while (and (not (eobp)) (> (funcall outline-level) level))
17364 (outline-next-heading))
17365 (if (or (eobp) (< (funcall outline-level) level))
17367 (point))))
17369 (defun org-get-last-sibling ()
17370 "Move to previous heading of the same level, and return point.
17371 If there is no such heading, return nil."
17372 (let ((opoint (point))
17373 (level (funcall outline-level)))
17374 (outline-previous-heading)
17375 (when (and (/= (point) opoint) (outline-on-heading-p t))
17376 (while (and (> (funcall outline-level) level)
17377 (not (bobp)))
17378 (outline-previous-heading))
17379 (if (< (funcall outline-level) level)
17381 (point)))))
17383 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17384 ;; This contains an exact copy of the original function, but it uses
17385 ;; `org-back-to-heading', to make it work also in invisible
17386 ;; trees. And is uses an invisible-OK argument.
17387 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17388 ;; Furthermore, when used inside Org, finding the end of a large subtree
17389 ;; with many children and grandchildren etc, this can be much faster
17390 ;; than the outline version.
17391 (org-back-to-heading invisible-OK)
17392 (let ((first t)
17393 (level (funcall outline-level)))
17394 (if (and (org-mode-p) (< level 1000))
17395 ;; A true heading (not a plain list item), in Org-mode
17396 ;; This means we can easily find the end by looking
17397 ;; only for the right number of stars. Using a regexp to do
17398 ;; this is so much faster than using a Lisp loop.
17399 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17400 (forward-char 1)
17401 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17402 ;; something else, do it the slow way
17403 (while (and (not (eobp))
17404 (or first (> (funcall outline-level) level)))
17405 (setq first nil)
17406 (outline-next-heading)))
17407 (unless to-heading
17408 (if (memq (preceding-char) '(?\n ?\^M))
17409 (progn
17410 ;; Go to end of line before heading
17411 (forward-char -1)
17412 (if (memq (preceding-char) '(?\n ?\^M))
17413 ;; leave blank line before heading
17414 (forward-char -1))))))
17415 (point))
17417 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17418 "Use Org version in org-mode, for dramatic speed-up."
17419 (if (eq major-mode 'org-mode)
17420 (progn
17421 (org-end-of-subtree nil t)
17422 (unless (eobp) (backward-char 1)))
17423 ad-do-it))
17425 (defun org-forward-same-level (arg &optional invisible-ok)
17426 "Move forward to the arg'th subheading at same level as this one.
17427 Stop at the first and last subheadings of a superior heading."
17428 (interactive "p")
17429 (org-back-to-heading invisible-ok)
17430 (org-on-heading-p)
17431 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17432 (re (format "^\\*\\{1,%d\\} " level))
17434 (forward-char 1)
17435 (while (> arg 0)
17436 (while (and (re-search-forward re nil 'move)
17437 (setq l (- (match-end 0) (match-beginning 0) 1))
17438 (= l level)
17439 (not invisible-ok)
17440 (org-invisible-p))
17441 (if (< l level) (setq arg 1)))
17442 (setq arg (1- arg)))
17443 (beginning-of-line 1)))
17445 (defun org-backward-same-level (arg &optional invisible-ok)
17446 "Move backward to the arg'th subheading at same level as this one.
17447 Stop at the first and last subheadings of a superior heading."
17448 (interactive "p")
17449 (org-back-to-heading)
17450 (org-on-heading-p)
17451 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17452 (re (format "^\\*\\{1,%d\\} " level))
17454 (while (> arg 0)
17455 (while (and (re-search-backward re nil 'move)
17456 (setq l (- (match-end 0) (match-beginning 0) 1))
17457 (= l level)
17458 (not invisible-ok)
17459 (org-invisible-p))
17460 (if (< l level) (setq arg 1)))
17461 (setq arg (1- arg)))))
17463 (defun org-show-subtree ()
17464 "Show everything after this heading at deeper levels."
17465 (outline-flag-region
17466 (point)
17467 (save-excursion
17468 (org-end-of-subtree t t))
17469 nil))
17471 (defun org-show-entry ()
17472 "Show the body directly following this heading.
17473 Show the heading too, if it is currently invisible."
17474 (interactive)
17475 (save-excursion
17476 (condition-case nil
17477 (progn
17478 (org-back-to-heading t)
17479 (outline-flag-region
17480 (max (point-min) (1- (point)))
17481 (save-excursion
17482 (if (re-search-forward
17483 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17484 (match-beginning 1)
17485 (point-max)))
17486 nil)
17487 (org-cycle-hide-drawers 'children))
17488 (error nil))))
17490 (defun org-make-options-regexp (kwds &optional extra)
17491 "Make a regular expression for keyword lines."
17492 (concat
17494 "#?[ \t]*\\+\\("
17495 (mapconcat 'regexp-quote kwds "\\|")
17496 (if extra (concat "\\|" extra))
17497 "\\):[ \t]*"
17498 "\\(.*\\)"))
17500 ;; Make isearch reveal the necessary context
17501 (defun org-isearch-end ()
17502 "Reveal context after isearch exits."
17503 (when isearch-success ; only if search was successful
17504 (if (featurep 'xemacs)
17505 ;; Under XEmacs, the hook is run in the correct place,
17506 ;; we directly show the context.
17507 (org-show-context 'isearch)
17508 ;; In Emacs the hook runs *before* restoring the overlays.
17509 ;; So we have to use a one-time post-command-hook to do this.
17510 ;; (Emacs 22 has a special variable, see function `org-mode')
17511 (unless (and (boundp 'isearch-mode-end-hook-quit)
17512 isearch-mode-end-hook-quit)
17513 ;; Only when the isearch was not quitted.
17514 (org-add-hook 'post-command-hook 'org-isearch-post-command
17515 'append 'local)))))
17517 (defun org-isearch-post-command ()
17518 "Remove self from hook, and show context."
17519 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17520 (org-show-context 'isearch))
17523 ;;;; Integration with and fixes for other packages
17525 ;;; Imenu support
17527 (defvar org-imenu-markers nil
17528 "All markers currently used by Imenu.")
17529 (make-variable-buffer-local 'org-imenu-markers)
17531 (defun org-imenu-new-marker (&optional pos)
17532 "Return a new marker for use by Imenu, and remember the marker."
17533 (let ((m (make-marker)))
17534 (move-marker m (or pos (point)))
17535 (push m org-imenu-markers)
17538 (defun org-imenu-get-tree ()
17539 "Produce the index for Imenu."
17540 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17541 (setq org-imenu-markers nil)
17542 (let* ((n org-imenu-depth)
17543 (re (concat "^" outline-regexp))
17544 (subs (make-vector (1+ n) nil))
17545 (last-level 0)
17546 m level head)
17547 (save-excursion
17548 (save-restriction
17549 (widen)
17550 (goto-char (point-max))
17551 (while (re-search-backward re nil t)
17552 (setq level (org-reduced-level (funcall outline-level)))
17553 (when (<= level n)
17554 (looking-at org-complex-heading-regexp)
17555 (setq head (org-link-display-format
17556 (org-match-string-no-properties 4))
17557 m (org-imenu-new-marker))
17558 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17559 (if (>= level last-level)
17560 (push (cons head m) (aref subs level))
17561 (push (cons head (aref subs (1+ level))) (aref subs level))
17562 (loop for i from (1+ level) to n do (aset subs i nil)))
17563 (setq last-level level)))))
17564 (aref subs 1)))
17566 (eval-after-load "imenu"
17567 '(progn
17568 (add-hook 'imenu-after-jump-hook
17569 (lambda ()
17570 (if (eq major-mode 'org-mode)
17571 (org-show-context 'org-goto))))))
17573 (defun org-link-display-format (link)
17574 "Replace a link with either the description, or the link target
17575 if no description is present"
17576 (save-match-data
17577 (if (string-match org-bracket-link-analytic-regexp link)
17578 (replace-match (if (match-end 5)
17579 (match-string 5 link)
17580 (concat (match-string 1 link)
17581 (match-string 3 link)))
17582 nil t link)
17583 link)))
17585 ;; Speedbar support
17587 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17588 "Overlay marking the agenda restriction line in speedbar.")
17589 (org-overlay-put org-speedbar-restriction-lock-overlay
17590 'face 'org-agenda-restriction-lock)
17591 (org-overlay-put org-speedbar-restriction-lock-overlay
17592 'help-echo "Agendas are currently limited to this item.")
17593 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17595 (defun org-speedbar-set-agenda-restriction ()
17596 "Restrict future agenda commands to the location at point in speedbar.
17597 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17598 (interactive)
17599 (require 'org-agenda)
17600 (let (p m tp np dir txt)
17601 (cond
17602 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17603 'org-imenu t))
17604 (setq m (get-text-property p 'org-imenu-marker))
17605 (with-current-buffer (marker-buffer m)
17606 (goto-char m)
17607 (org-agenda-set-restriction-lock 'subtree)))
17608 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17609 'speedbar-function 'speedbar-find-file))
17610 (setq tp (previous-single-property-change
17611 (1+ p) 'speedbar-function)
17612 np (next-single-property-change
17613 tp 'speedbar-function)
17614 dir (speedbar-line-directory)
17615 txt (buffer-substring-no-properties (or tp (point-min))
17616 (or np (point-max))))
17617 (with-current-buffer (find-file-noselect
17618 (let ((default-directory dir))
17619 (expand-file-name txt)))
17620 (unless (org-mode-p)
17621 (error "Cannot restrict to non-Org-mode file"))
17622 (org-agenda-set-restriction-lock 'file)))
17623 (t (error "Don't know how to restrict Org-mode's agenda")))
17624 (org-move-overlay org-speedbar-restriction-lock-overlay
17625 (point-at-bol) (point-at-eol))
17626 (setq current-prefix-arg nil)
17627 (org-agenda-maybe-redo)))
17629 (eval-after-load "speedbar"
17630 '(progn
17631 (speedbar-add-supported-extension ".org")
17632 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17633 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17634 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17635 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17636 (add-hook 'speedbar-visiting-tag-hook
17637 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17640 ;;; Fixes and Hacks for problems with other packages
17642 ;; Make flyspell not check words in links, to not mess up our keymap
17643 (defun org-mode-flyspell-verify ()
17644 "Don't let flyspell put overlays at active buttons."
17645 (and (not (get-text-property (point) 'keymap))
17646 (not (get-text-property (point) 'org-no-flyspell))))
17648 (defun org-remove-flyspell-overlays-in (beg end)
17649 "Remove flyspell overlays in region."
17650 (and (org-bound-and-true-p flyspell-mode)
17651 (fboundp 'flyspell-delete-region-overlays)
17652 (flyspell-delete-region-overlays beg end))
17653 (add-text-properties beg end '(org-no-flyspell t)))
17655 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17656 (eval-after-load "bookmark"
17657 '(if (boundp 'bookmark-after-jump-hook)
17658 ;; We can use the hook
17659 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17660 ;; Hook not available, use advice
17661 (defadvice bookmark-jump (after org-make-visible activate)
17662 "Make the position visible."
17663 (org-bookmark-jump-unhide))))
17665 ;; Make sure saveplace shows the location if it was hidden
17666 (eval-after-load "saveplace"
17667 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17668 "Make the position visible."
17669 (org-bookmark-jump-unhide)))
17671 ;; Make sure ecb shows the location if it was hidden
17672 (eval-after-load "ecb"
17673 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17674 "Make hierarchy visible when jumping into location from ECB tree buffer."
17675 (if (eq major-mode 'org-mode)
17676 (org-show-context))))
17678 (defun org-bookmark-jump-unhide ()
17679 "Unhide the current position, to show the bookmark location."
17680 (and (org-mode-p)
17681 (or (org-invisible-p)
17682 (save-excursion (goto-char (max (point-min) (1- (point))))
17683 (org-invisible-p)))
17684 (org-show-context 'bookmark-jump)))
17686 ;; Make session.el ignore our circular variable
17687 (eval-after-load "session"
17688 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17690 ;;;; Experimental code
17692 (defun org-closed-in-range ()
17693 "Sparse tree of items closed in a certain time range.
17694 Still experimental, may disappear in the future."
17695 (interactive)
17696 ;; Get the time interval from the user.
17697 (let* ((time1 (org-float-time
17698 (org-read-date nil 'to-time nil "Starting date: ")))
17699 (time2 (org-float-time
17700 (org-read-date nil 'to-time nil "End date:")))
17701 ;; callback function
17702 (callback (lambda ()
17703 (let ((time
17704 (org-float-time
17705 (apply 'encode-time
17706 (org-parse-time-string
17707 (match-string 1))))))
17708 ;; check if time in interval
17709 (and (>= time time1) (<= time time2))))))
17710 ;; make tree, check each match with the callback
17711 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17713 ;;;; Finish up
17715 (provide 'org)
17717 (run-hooks 'org-load-hook)
17719 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17721 ;;; org.el ends here