Better error message for parsing a bogus time string
[org-mode.git] / lisp / org.el
blob8d336a9fbde7d230b8eef9271f6474bb16274fb8
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.29trans
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.29trans"
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* ((org-version org-version)
106 (git-version)
107 (dir (concat (file-name-directory (locate-library "org")) "../" ))
108 (version))
109 (if (and (file-exists-p (expand-file-name ".git" dir))
110 (executable-find "git"))
111 (let ((pwd (substring (pwd) 10)))
112 (cd dir)
113 (if (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
114 (save-excursion
115 (set-buffer "*Shell Command Output*")
116 (goto-char (point-min))
117 (re-search-forward "[^\n]+")
118 (setq git-version (match-string 0))
119 (subst-char-in-string ?- ?. git-version t)
120 (shell-command "git diff-index --name-only HEAD --")
121 (unless (eql 1 (point-max))
122 (setq git-version (concat git-version ".dirty")))
123 (setq org-version (concat org-version " (" git-version ")")))
124 (cd pwd))))
125 (setq version (format "Org-mode version %s" org-version))
126 (if here (insert version))
127 (message version)
128 version))
130 ;;; Compatibility constants
132 ;;; The custom variables
134 (defgroup org nil
135 "Outline-based notes management and organizer."
136 :tag "Org"
137 :group 'outlines
138 :group 'hypermedia
139 :group 'calendar)
141 (defcustom org-load-hook nil
142 "Hook that is run after org.el has been loaded."
143 :group 'org
144 :type 'hook)
146 (defvar org-modules) ; defined below
147 (defvar org-modules-loaded nil
148 "Have the modules been loaded already?")
150 (defun org-load-modules-maybe (&optional force)
151 "Load all extensions listed in `org-modules'."
152 (when (or force (not org-modules-loaded))
153 (mapc (lambda (ext)
154 (condition-case nil (require ext)
155 (error (message "Problems while trying to load feature `%s'" ext))))
156 org-modules)
157 (setq org-modules-loaded t)))
159 (defun org-set-modules (var value)
160 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
161 (set var value)
162 (when (featurep 'org)
163 (org-load-modules-maybe 'force)))
165 (when (org-bound-and-true-p org-modules)
166 (let ((a (member 'org-infojs org-modules)))
167 (and a (setcar a 'org-jsinfo))))
169 (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)
170 "Modules that should always be loaded together with org.el.
171 If a description starts with <C>, the file is not part of Emacs
172 and loading it will require that you have downloaded and properly installed
173 the org-mode distribution.
175 You can also use this system to load external packages (i.e. neither Org
176 core modules, not modules from the CONTRIB directory). Just add symbols
177 to the end of the list. If the package is called org-xyz.el, then you need
178 to add the symbol `xyz', and the package must have a call to
180 (provide 'org-xyz)"
181 :group 'org
182 :set 'org-set-modules
183 :type
184 '(set :greedy t
185 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
186 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
187 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
188 (const :tag " id: Global IDs for identifying entries" org-id)
189 (const :tag " info: Links to Info nodes" org-info)
190 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
191 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
192 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
193 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
194 (const :tag " mew Links to Mew folders/messages" org-mew)
195 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
196 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
197 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
198 (const :tag " vm: Links to VM folders/messages" org-vm)
199 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
200 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
201 (const :tag " mouse: Additional mouse support" org-mouse)
203 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
204 (const :tag "C annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
205 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
206 (const :tag "C browser-url: Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
207 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
208 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
209 (const :tag "C collector: Collect properties into tables" org-collector)
210 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
211 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
212 (const :tag "C eval: Include command output as text" org-eval)
213 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
214 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
215 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
216 (const :tag "C interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
217 (const :tag "C jira Add a jira:ticket protocol to Org" org-jira)
218 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
219 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
220 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
221 (const :tag "C mtags: Support for muse-like tags" org-mtags)
222 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
223 (const :tag "C R: Computation using the R language" org-R)
224 (const :tag "C registry: A registry for Org links" org-registry)
225 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
226 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
227 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
228 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
229 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
230 (const :tag "C track: Keep up with Org development" org-track)
231 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
233 (defcustom org-support-shift-select nil
234 "Non-nil means, make shift-cursor commands select text when possible.
236 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
237 selecting a region, or enlarge thusly regions started in this way.
238 In Org-mode, in special contexts, these same keys are used for other
239 purposes, important enough to compete with shift selection. Org tries
240 to balance these needs by supporting `shift-select-mode' outside these
241 special contexts, under control of this variable.
243 The default of this variable is nil, to avoid confusing behavior. Shifted
244 cursor keys will then execute Org commands in the following contexts:
245 - on a headline, changing TODO state (left/right) and priority (up/down)
246 - on a time stamp, changing the time
247 - in a plain list item, changing the bullet type
248 - in a property definition line, switching between allowed values
249 - in the BEGIN line of a clock table (changing the time block).
250 Outside these contexts, the commands will throw an error.
252 When this variable is t and the cursor is not in a special context,
253 Org-mode will support shift-selection for making and enlarging regions.
254 To make this more effective, the bullet cycling will no longer happen
255 anywhere in an item line, but only if the cursor is exactly on the bullet.
257 If you set this variable to the symbol `always', then the keys
258 will not be special in headlines, property lines, and item lines, to make
259 shift selection work there as well. If this is what you want, you can
260 use the following alternative commands: `C-c C-t' and `C-c ,' to
261 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
262 TODO sets, `C-c -' to cycle item bullet types, and properties can be
263 edited by hand or in column view.
265 However, when the cursor is on a timestamp, shift-cursor commands
266 will still edit the time stamp - this is just too good to give up.
268 XEmacs user should have this variable set to nil, because shift-select-mode
269 is Emacs 23 only."
270 :group 'org
271 :type '(choice
272 (const :tag "Never" nil)
273 (const :tag "When outside special context" t)
274 (const :tag "Everywhere except timestamps" always)))
276 (defgroup org-startup nil
277 "Options concerning startup of Org-mode."
278 :tag "Org Startup"
279 :group 'org)
281 (defcustom org-startup-folded t
282 "Non-nil means, entering Org-mode will switch to OVERVIEW.
283 This can also be configured on a per-file basis by adding one of
284 the following lines anywhere in the buffer:
286 #+STARTUP: fold
287 #+STARTUP: nofold
288 #+STARTUP: content"
289 :group 'org-startup
290 :type '(choice
291 (const :tag "nofold: show all" nil)
292 (const :tag "fold: overview" t)
293 (const :tag "content: all headlines" content)))
295 (defcustom org-startup-truncated t
296 "Non-nil means, entering Org-mode will set `truncate-lines'.
297 This is useful since some lines containing links can be very long and
298 uninteresting. Also tables look terrible when wrapped."
299 :group 'org-startup
300 :type 'boolean)
302 (defcustom org-startup-indented nil
303 "Non-nil means, turn on `org-indent-mode' on startup.
304 This can also be configured on a per-file basis by adding one of
305 the following lines anywhere in the buffer:
307 #+STARTUP: indent
308 #+STARTUP: noindent"
309 :group 'org-structure
310 :type '(choice
311 (const :tag "Not" nil)
312 (const :tag "Globally (slow on startup in large files)" t)))
314 (defcustom org-startup-align-all-tables nil
315 "Non-nil means, align all tables when visiting a file.
316 This is useful when the column width in tables is forced with <N> cookies
317 in table fields. Such tables will look correct only after the first re-align.
318 This can also be configured on a per-file basis by adding one of
319 the following lines anywhere in the buffer:
320 #+STARTUP: align
321 #+STARTUP: noalign"
322 :group 'org-startup
323 :type 'boolean)
325 (defcustom org-insert-mode-line-in-empty-file nil
326 "Non-nil means insert the first line setting Org-mode in empty files.
327 When the function `org-mode' is called interactively in an empty file, this
328 normally means that the file name does not automatically trigger Org-mode.
329 To ensure that the file will always be in Org-mode in the future, a
330 line enforcing Org-mode will be inserted into the buffer, if this option
331 has been set."
332 :group 'org-startup
333 :type 'boolean)
335 (defcustom org-replace-disputed-keys nil
336 "Non-nil means use alternative key bindings for some keys.
337 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
338 These keys are also used by other packages like shift-selection-mode'
339 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
340 If you want to use Org-mode together with one of these other modes,
341 or more generally if you would like to move some Org-mode commands to
342 other keys, set this variable and configure the keys with the variable
343 `org-disputed-keys'.
345 This option is only relevant at load-time of Org-mode, and must be set
346 *before* org.el is loaded. Changing it requires a restart of Emacs to
347 become effective."
348 :group 'org-startup
349 :type 'boolean)
351 (defcustom org-use-extra-keys nil
352 "Non-nil means use extra key sequence definitions for certain
353 commands. This happens automatically if you run XEmacs or if
354 window-system is nil. This variable lets you do the same
355 manually. You must set it before loading org.
357 Example: on Carbon Emacs 22 running graphically, with an external
358 keyboard on a Powerbook, the default way of setting M-left might
359 not work for either Alt or ESC. Setting this variable will make
360 it work for ESC."
361 :group 'org-startup
362 :type 'boolean)
364 (if (fboundp 'defvaralias)
365 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
367 (defcustom org-disputed-keys
368 '(([(shift up)] . [(meta p)])
369 ([(shift down)] . [(meta n)])
370 ([(shift left)] . [(meta -)])
371 ([(shift right)] . [(meta +)])
372 ([(control shift right)] . [(meta shift +)])
373 ([(control shift left)] . [(meta shift -)]))
374 "Keys for which Org-mode and other modes compete.
375 This is an alist, cars are the default keys, second element specifies
376 the alternative to use when `org-replace-disputed-keys' is t.
378 Keys can be specified in any syntax supported by `define-key'.
379 The value of this option takes effect only at Org-mode's startup,
380 therefore you'll have to restart Emacs to apply it after changing."
381 :group 'org-startup
382 :type 'alist)
384 (defun org-key (key)
385 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
386 Or return the original if not disputed."
387 (if org-replace-disputed-keys
388 (let* ((nkey (key-description key))
389 (x (org-find-if (lambda (x)
390 (equal (key-description (car x)) nkey))
391 org-disputed-keys)))
392 (if x (cdr x) key))
393 key))
395 (defun org-find-if (predicate seq)
396 (catch 'exit
397 (while seq
398 (if (funcall predicate (car seq))
399 (throw 'exit (car seq))
400 (pop seq)))))
402 (defun org-defkey (keymap key def)
403 "Define a key, possibly translated, as returned by `org-key'."
404 (define-key keymap (org-key key) def))
406 (defcustom org-ellipsis nil
407 "The ellipsis to use in the Org-mode outline.
408 When nil, just use the standard three dots. When a string, use that instead,
409 When a face, use the standard 3 dots, but with the specified face.
410 The change affects only Org-mode (which will then use its own display table).
411 Changing this requires executing `M-x org-mode' in a buffer to become
412 effective."
413 :group 'org-startup
414 :type '(choice (const :tag "Default" nil)
415 (face :tag "Face" :value org-warning)
416 (string :tag "String" :value "...#")))
418 (defvar org-display-table nil
419 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
421 (defgroup org-keywords nil
422 "Keywords in Org-mode."
423 :tag "Org Keywords"
424 :group 'org)
426 (defcustom org-deadline-string "DEADLINE:"
427 "String to mark deadline entries.
428 A deadline is this string, followed by a time stamp. Should be a word,
429 terminated by a colon. You can insert a schedule keyword and
430 a timestamp with \\[org-deadline].
431 Changes become only effective after restarting Emacs."
432 :group 'org-keywords
433 :type 'string)
435 (defcustom org-scheduled-string "SCHEDULED:"
436 "String to mark scheduled TODO entries.
437 A schedule is this string, followed by a time stamp. Should be a word,
438 terminated by a colon. You can insert a schedule keyword and
439 a timestamp with \\[org-schedule].
440 Changes become only effective after restarting Emacs."
441 :group 'org-keywords
442 :type 'string)
444 (defcustom org-closed-string "CLOSED:"
445 "String used as the prefix for timestamps logging closing a TODO entry."
446 :group 'org-keywords
447 :type 'string)
449 (defcustom org-clock-string "CLOCK:"
450 "String used as prefix for timestamps clocking work hours on an item."
451 :group 'org-keywords
452 :type 'string)
454 (defcustom org-comment-string "COMMENT"
455 "Entries starting with this keyword will never be exported.
456 An entry can be toggled between COMMENT and normal with
457 \\[org-toggle-comment].
458 Changes become only effective after restarting Emacs."
459 :group 'org-keywords
460 :type 'string)
462 (defcustom org-quote-string "QUOTE"
463 "Entries starting with this keyword will be exported in fixed-width font.
464 Quoting applies only to the text in the entry following the headline, and does
465 not extend beyond the next headline, even if that is lower level.
466 An entry can be toggled between QUOTE and normal with
467 \\[org-toggle-fixed-width-section]."
468 :group 'org-keywords
469 :type 'string)
471 (defconst org-repeat-re
472 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
473 "Regular expression for specifying repeated events.
474 After a match, group 1 contains the repeat expression.")
476 (defgroup org-structure nil
477 "Options concerning the general structure of Org-mode files."
478 :tag "Org Structure"
479 :group 'org)
481 (defgroup org-reveal-location nil
482 "Options about how to make context of a location visible."
483 :tag "Org Reveal Location"
484 :group 'org-structure)
486 (defconst org-context-choice
487 '(choice
488 (const :tag "Always" t)
489 (const :tag "Never" nil)
490 (repeat :greedy t :tag "Individual contexts"
491 (cons
492 (choice :tag "Context"
493 (const agenda)
494 (const org-goto)
495 (const occur-tree)
496 (const tags-tree)
497 (const link-search)
498 (const mark-goto)
499 (const bookmark-jump)
500 (const isearch)
501 (const default))
502 (boolean))))
503 "Contexts for the reveal options.")
505 (defcustom org-show-hierarchy-above '((default . t))
506 "Non-nil means, show full hierarchy when revealing a location.
507 Org-mode often shows locations in an org-mode file which might have
508 been invisible before. When this is set, the hierarchy of headings
509 above the exposed location is shown.
510 Turning this off for example for sparse trees makes them very compact.
511 Instead of t, this can also be an alist specifying this option for different
512 contexts. Valid contexts are
513 agenda when exposing an entry from the agenda
514 org-goto when using the command `org-goto' on key C-c C-j
515 occur-tree when using the command `org-occur' on key C-c /
516 tags-tree when constructing a sparse tree based on tags matches
517 link-search when exposing search matches associated with a link
518 mark-goto when exposing the jump goal of a mark
519 bookmark-jump when exposing a bookmark location
520 isearch when exiting from an incremental search
521 default default for all contexts not set explicitly"
522 :group 'org-reveal-location
523 :type org-context-choice)
525 (defcustom org-show-following-heading '((default . nil))
526 "Non-nil means, show following heading when revealing a location.
527 Org-mode often shows locations in an org-mode file which might have
528 been invisible before. When this is set, the heading following the
529 match is shown.
530 Turning this off for example for sparse trees makes them very compact,
531 but makes it harder to edit the location of the match. In such a case,
532 use the command \\[org-reveal] to show more context.
533 Instead of t, this can also be an alist specifying this option for different
534 contexts. See `org-show-hierarchy-above' for valid contexts."
535 :group 'org-reveal-location
536 :type org-context-choice)
538 (defcustom org-show-siblings '((default . nil) (isearch t))
539 "Non-nil means, show all sibling heading when revealing a location.
540 Org-mode often shows locations in an org-mode file which might have
541 been invisible before. When this is set, the sibling of the current entry
542 heading are all made visible. If `org-show-hierarchy-above' is t,
543 the same happens on each level of the hierarchy above the current entry.
545 By default this is on for the isearch context, off for all other contexts.
546 Turning this off for example for sparse trees makes them very compact,
547 but makes it harder to edit the location of the match. In such a case,
548 use the command \\[org-reveal] to show more context.
549 Instead of t, this can also be an alist specifying this option for different
550 contexts. See `org-show-hierarchy-above' for valid contexts."
551 :group 'org-reveal-location
552 :type org-context-choice)
554 (defcustom org-show-entry-below '((default . nil))
555 "Non-nil means, show the entry below a headline when revealing a location.
556 Org-mode often shows locations in an org-mode file which might have
557 been invisible before. When this is set, the text below the headline that is
558 exposed is also shown.
560 By default this is off for all contexts.
561 Instead of t, this can also be an alist specifying this option for different
562 contexts. See `org-show-hierarchy-above' for valid contexts."
563 :group 'org-reveal-location
564 :type org-context-choice)
566 (defcustom org-indirect-buffer-display 'other-window
567 "How should indirect tree buffers be displayed?
568 This applies to indirect buffers created with the commands
569 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
570 Valid values are:
571 current-window Display in the current window
572 other-window Just display in another window.
573 dedicated-frame Create one new frame, and re-use it each time.
574 new-frame Make a new frame each time. Note that in this case
575 previously-made indirect buffers are kept, and you need to
576 kill these buffers yourself."
577 :group 'org-structure
578 :group 'org-agenda-windows
579 :type '(choice
580 (const :tag "In current window" current-window)
581 (const :tag "In current frame, other window" other-window)
582 (const :tag "Each time a new frame" new-frame)
583 (const :tag "One dedicated frame" dedicated-frame)))
585 (defgroup org-cycle nil
586 "Options concerning visibility cycling in Org-mode."
587 :tag "Org Cycle"
588 :group 'org-structure)
590 (defcustom org-cycle-skip-children-state-if-no-children t
591 "Non-nil means, skip CHILDREN state in entries that don't have any."
592 :group 'org-cycle
593 :type 'boolean)
595 (defcustom org-cycle-max-level nil
596 "Maximum level which should still be subject to visibility cycling.
597 Levels higher than this will, for cycling, be treated as text, not a headline.
598 When `org-odd-levels-only' is set, a value of N in this variable actually
599 means 2N-1 stars as the limiting headline.
600 When nil, cycle all levels.
601 Note that the limiting level of cycling is also influenced by
602 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
603 `org-inlinetask-min-level' is, cycling will be limited to levels one less
604 than its value."
605 :group 'org-cycle
606 :type '(choice
607 (const :tag "No limit" nil)
608 (integer :tag "Maximum level")))
610 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
611 "Names of drawers. Drawers are not opened by cycling on the headline above.
612 Drawers only open with a TAB on the drawer line itself. A drawer looks like
613 this:
614 :DRAWERNAME:
615 .....
616 :END:
617 The drawer \"PROPERTIES\" is special for capturing properties through
618 the property API.
620 Drawers can be defined on the per-file basis with a line like:
622 #+DRAWERS: HIDDEN STATE PROPERTIES"
623 :group 'org-structure
624 :group 'org-cycle
625 :type '(repeat (string :tag "Drawer Name")))
627 (defcustom org-hide-block-startup nil
628 "Non-nil means, , entering Org-mode will fold all blocks.
629 This can also be set in on a per-file basis with
631 #+STARTUP: hideblocks
632 #+STARTUP: showblocks"
633 :group 'org-startup
634 :group 'org-cycle
635 :type 'boolean)
637 (defcustom org-cycle-global-at-bob nil
638 "Cycle globally if cursor is at beginning of buffer and not at a headline.
639 This makes it possible to do global cycling without having to use S-TAB or
640 C-u TAB. For this special case to work, the first line of the buffer
641 must not be a headline - it may be empty or some other text. When used in
642 this way, `org-cycle-hook' is disables temporarily, to make sure the
643 cursor stays at the beginning of the buffer.
644 When this option is nil, don't do anything special at the beginning
645 of the buffer."
646 :group 'org-cycle
647 :type 'boolean)
649 (defcustom org-cycle-emulate-tab t
650 "Where should `org-cycle' emulate TAB.
651 nil Never
652 white Only in completely white lines
653 whitestart Only at the beginning of lines, before the first non-white char
654 t Everywhere except in headlines
655 exc-hl-bol Everywhere except at the start of a headline
656 If TAB is used in a place where it does not emulate TAB, the current subtree
657 visibility is cycled."
658 :group 'org-cycle
659 :type '(choice (const :tag "Never" nil)
660 (const :tag "Only in completely white lines" white)
661 (const :tag "Before first char in a line" whitestart)
662 (const :tag "Everywhere except in headlines" t)
663 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
666 (defcustom org-cycle-separator-lines 2
667 "Number of empty lines needed to keep an empty line between collapsed trees.
668 If you leave an empty line between the end of a subtree and the following
669 headline, this empty line is hidden when the subtree is folded.
670 Org-mode will leave (exactly) one empty line visible if the number of
671 empty lines is equal or larger to the number given in this variable.
672 So the default 2 means, at least 2 empty lines after the end of a subtree
673 are needed to produce free space between a collapsed subtree and the
674 following headline.
676 If the number is negative, and the number of empty lines is at least -N,
677 all empty lines are shown.
679 Special case: when 0, never leave empty lines in collapsed view."
680 :group 'org-cycle
681 :type 'integer)
682 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
684 (defcustom org-pre-cycle-hook nil
685 "Hook that is run before visibility cycling is happening.
686 The function(s) in this hook must accept a single argument which indicates
687 the new state that will be set right after running this hook. The
688 argument is a symbol. Before a global state change, it can have the values
689 `overview', `content', or `all'. Before a local state change, it can have
690 the values `folded', `children', or `subtree'."
691 :group 'org-cycle
692 :type 'hook)
694 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
695 org-cycle-hide-drawers
696 org-cycle-show-empty-lines
697 org-optimize-window-after-visibility-change)
698 "Hook that is run after `org-cycle' has changed the buffer visibility.
699 The function(s) in this hook must accept a single argument which indicates
700 the new state that was set by the most recent `org-cycle' command. The
701 argument is a symbol. After a global state change, it can have the values
702 `overview', `content', or `all'. After a local state change, it can have
703 the values `folded', `children', or `subtree'."
704 :group 'org-cycle
705 :type 'hook)
707 (defgroup org-edit-structure nil
708 "Options concerning structure editing in Org-mode."
709 :tag "Org Edit Structure"
710 :group 'org-structure)
712 (defcustom org-odd-levels-only nil
713 "Non-nil means, skip even levels and only use odd levels for the outline.
714 This has the effect that two stars are being added/taken away in
715 promotion/demotion commands. It also influences how levels are
716 handled by the exporters.
717 Changing it requires restart of `font-lock-mode' to become effective
718 for fontification also in regions already fontified.
719 You may also set this on a per-file basis by adding one of the following
720 lines to the buffer:
722 #+STARTUP: odd
723 #+STARTUP: oddeven"
724 :group 'org-edit-structure
725 :group 'org-font-lock
726 :type 'boolean)
728 (defcustom org-adapt-indentation t
729 "Non-nil means, adapt indentation to outline node level.
731 When this variable is set, Org assumes that you write outlines by
732 indenting text in each node to align with the headline (after the stars).
733 The following issues are influenced by this variable:
735 - When this is set and the *entire* text in an entry is indented, the
736 indentation is increased by one space in a demotion command, and
737 decreased by one in a promotion command. If any line in the entry
738 body starts with text at column 0, indentation is not changed at all.
740 - Property drawers and planning information is inserted indented when
741 this variable s set. When nil, they will not be indented.
743 - TAB indents a line relative to context. The lines below a headline
744 will be indented when this variable is set.
746 Note that this is all about true indentation, by adding and removing
747 space characters. See also `org-indent.el' which does level-dependent
748 indentation in a virtual way, i.e. at display time in Emacs."
749 :group 'org-edit-structure
750 :type 'boolean)
752 (defcustom org-special-ctrl-a/e nil
753 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
755 When t, `C-a' will bring back the cursor to the beginning of the
756 headline text, i.e. after the stars and after a possible TODO keyword.
757 In an item, this will be the position after the bullet.
758 When the cursor is already at that position, another `C-a' will bring
759 it to the beginning of the line.
761 `C-e' will jump to the end of the headline, ignoring the presence of tags
762 in the headline. A second `C-e' will then jump to the true end of the
763 line, after any tags.
765 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
766 going to the true line boundary first. Only a directly following, identical
767 keypress will bring the cursor to the special positions.
769 This may also be a cons cell where the behavior for `C-a' and `C-e' is
770 set separately."
771 :group 'org-edit-structure
772 :type '(choice
773 (const :tag "off" nil)
774 (const :tag "after stars/bullet and before tags first" t)
775 (const :tag "true line boundary first" reversed)
776 (cons :tag "Set C-a and C-e separately"
777 (choice :tag "Special C-a"
778 (const :tag "off" nil)
779 (const :tag "after stars/bullet first" t)
780 (const :tag "before stars/bullet first" reversed))
781 (choice :tag "Special C-e"
782 (const :tag "off" nil)
783 (const :tag "before tags first" t)
784 (const :tag "after tags first" reversed)))))
785 (if (fboundp 'defvaralias)
786 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
788 (defcustom org-special-ctrl-k nil
789 "Non-nil means `C-k' will behave specially in headlines.
790 When nil, `C-k' will call the default `kill-line' command.
791 When t, the following will happen while the cursor is in the headline:
793 - When the cursor is at the beginning of a headline, kill the entire
794 line and possible the folded subtree below the line.
795 - When in the middle of the headline text, kill the headline up to the tags.
796 - When after the headline text, kill the tags."
797 :group 'org-edit-structure
798 :type 'boolean)
800 (defcustom org-yank-folded-subtrees t
801 "Non-nil means, when yanking subtrees, fold them.
802 If the kill is a single subtree, or a sequence of subtrees, i.e. if
803 it starts with a heading and all other headings in it are either children
804 or siblings, then fold all the subtrees. However, do this only if no
805 text after the yank would be swallowed into a folded tree by this action."
806 :group 'org-edit-structure
807 :type 'boolean)
809 (defcustom org-yank-adjusted-subtrees nil
810 "Non-nil means, when yanking subtrees, adjust the level.
811 With this setting, `org-paste-subtree' is used to insert the subtree, see
812 this function for details."
813 :group 'org-edit-structure
814 :type 'boolean)
816 (defcustom org-M-RET-may-split-line '((default . t))
817 "Non-nil means, M-RET will split the line at the cursor position.
818 When nil, it will go to the end of the line before making a
819 new line.
820 You may also set this option in a different way for different
821 contexts. Valid contexts are:
823 headline when creating a new headline
824 item when creating a new item
825 table in a table field
826 default the value to be used for all contexts not explicitly
827 customized"
828 :group 'org-structure
829 :group 'org-table
830 :type '(choice
831 (const :tag "Always" t)
832 (const :tag "Never" nil)
833 (repeat :greedy t :tag "Individual contexts"
834 (cons
835 (choice :tag "Context"
836 (const headline)
837 (const item)
838 (const table)
839 (const default))
840 (boolean)))))
843 (defcustom org-insert-heading-respect-content nil
844 "Non-nil means, insert new headings after the current subtree.
845 When nil, the new heading is created directly after the current line.
846 The commands \\[org-insert-heading-respect-content] and
847 \\[org-insert-todo-heading-respect-content] turn this variable on
848 for the duration of the command."
849 :group 'org-structure
850 :type 'boolean)
852 (defcustom org-blank-before-new-entry '((heading . auto)
853 (plain-list-item . auto))
854 "Should `org-insert-heading' leave a blank line before new heading/item?
855 The value is an alist, with `heading' and `plain-list-item' as car,
856 and a boolean flag as cdr. For plain lists, if the variable
857 `org-empty-line-terminates-plain-lists' is set, the setting here
858 is ignored and no empty line is inserted, to keep the list in tact."
859 :group 'org-edit-structure
860 :type '(list
861 (cons (const heading)
862 (choice (const :tag "Never" nil)
863 (const :tag "Always" t)
864 (const :tag "Auto" auto)))
865 (cons (const plain-list-item)
866 (choice (const :tag "Never" nil)
867 (const :tag "Always" t)
868 (const :tag "Auto" auto)))))
870 (defcustom org-insert-heading-hook nil
871 "Hook being run after inserting a new heading."
872 :group 'org-edit-structure
873 :type 'hook)
875 (defcustom org-enable-fixed-width-editor t
876 "Non-nil means, lines starting with \":\" are treated as fixed-width.
877 This currently only means, they are never auto-wrapped.
878 When nil, such lines will be treated like ordinary lines.
879 See also the QUOTE keyword."
880 :group 'org-edit-structure
881 :type 'boolean)
884 (defcustom org-goto-auto-isearch t
885 "Non-nil means, typing characters in org-goto starts incremental search."
886 :group 'org-edit-structure
887 :type 'boolean)
889 (defgroup org-sparse-trees nil
890 "Options concerning sparse trees in Org-mode."
891 :tag "Org Sparse Trees"
892 :group 'org-structure)
894 (defcustom org-highlight-sparse-tree-matches t
895 "Non-nil means, highlight all matches that define a sparse tree.
896 The highlights will automatically disappear the next time the buffer is
897 changed by an edit command."
898 :group 'org-sparse-trees
899 :type 'boolean)
901 (defcustom org-remove-highlights-with-change t
902 "Non-nil means, any change to the buffer will remove temporary highlights.
903 Such highlights are created by `org-occur' and `org-clock-display'.
904 When nil, `C-c C-c needs to be used to get rid of the highlights.
905 The highlights created by `org-preview-latex-fragment' always need
906 `C-c C-c' to be removed."
907 :group 'org-sparse-trees
908 :group 'org-time
909 :type 'boolean)
912 (defcustom org-occur-hook '(org-first-headline-recenter)
913 "Hook that is run after `org-occur' has constructed a sparse tree.
914 This can be used to recenter the window to show as much of the structure
915 as possible."
916 :group 'org-sparse-trees
917 :type 'hook)
919 (defgroup org-imenu-and-speedbar nil
920 "Options concerning imenu and speedbar in Org-mode."
921 :tag "Org Imenu and Speedbar"
922 :group 'org-structure)
924 (defcustom org-imenu-depth 2
925 "The maximum level for Imenu access to Org-mode headlines.
926 This also applied for speedbar access."
927 :group 'org-imenu-and-speedbar
928 :type 'integer)
930 (defgroup org-table nil
931 "Options concerning tables in Org-mode."
932 :tag "Org Table"
933 :group 'org)
935 (defcustom org-enable-table-editor 'optimized
936 "Non-nil means, lines starting with \"|\" are handled by the table editor.
937 When nil, such lines will be treated like ordinary lines.
939 When equal to the symbol `optimized', the table editor will be optimized to
940 do the following:
941 - Automatic overwrite mode in front of whitespace in table fields.
942 This makes the structure of the table stay in tact as long as the edited
943 field does not exceed the column width.
944 - Minimize the number of realigns. Normally, the table is aligned each time
945 TAB or RET are pressed to move to another field. With optimization this
946 happens only if changes to a field might have changed the column width.
947 Optimization requires replacing the functions `self-insert-command',
948 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
949 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
950 very good at guessing when a re-align will be necessary, but you can always
951 force one with \\[org-ctrl-c-ctrl-c].
953 If you would like to use the optimized version in Org-mode, but the
954 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
956 This variable can be used to turn on and off the table editor during a session,
957 but in order to toggle optimization, a restart is required.
959 See also the variable `org-table-auto-blank-field'."
960 :group 'org-table
961 :type '(choice
962 (const :tag "off" nil)
963 (const :tag "on" t)
964 (const :tag "on, optimized" optimized)))
966 (defcustom org-self-insert-cluster-for-undo t
967 "Non-nil means cluster self-insert commands for undo when possible.
968 If this is set, then, like in the Emacs command loop, 20 consequtive
969 characters will be undone together.
970 This is configurable, because there is some impact on typing performance."
971 :group 'org-table
972 :type 'boolean)
974 (defcustom org-table-tab-recognizes-table.el t
975 "Non-nil means, TAB will automatically notice a table.el table.
976 When it sees such a table, it moves point into it and - if necessary -
977 calls `table-recognize-table'."
978 :group 'org-table-editing
979 :type 'boolean)
981 (defgroup org-link nil
982 "Options concerning links in Org-mode."
983 :tag "Org Link"
984 :group 'org)
986 (defvar org-link-abbrev-alist-local nil
987 "Buffer-local version of `org-link-abbrev-alist', which see.
988 The value of this is taken from the #+LINK lines.")
989 (make-variable-buffer-local 'org-link-abbrev-alist-local)
991 (defcustom org-link-abbrev-alist nil
992 "Alist of link abbreviations.
993 The car of each element is a string, to be replaced at the start of a link.
994 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
995 links in Org-mode buffers can have an optional tag after a double colon, e.g.
997 [[linkkey:tag][description]]
999 The 'linkkey' must be a word word, starting with a letter, followed
1000 by letters, numbers, '-' or '_'.
1002 If REPLACE is a string, the tag will simply be appended to create the link.
1003 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1004 the placeholder \"%h\" will cause a url-encoded version of the tag to
1005 be inserted at that point (see the function `url-hexify-string').
1007 REPLACE may also be a function that will be called with the tag as the
1008 only argument to create the link, which should be returned as a string.
1010 See the manual for examples."
1011 :group 'org-link
1012 :type '(repeat
1013 (cons
1014 (string :tag "Protocol")
1015 (choice
1016 (string :tag "Format")
1017 (function)))))
1019 (defcustom org-descriptive-links t
1020 "Non-nil means, hide link part and only show description of bracket links.
1021 Bracket links are like [[link][description]]. This variable sets the initial
1022 state in new org-mode buffers. The setting can then be toggled on a
1023 per-buffer basis from the Org->Hyperlinks menu."
1024 :group 'org-link
1025 :type 'boolean)
1027 (defcustom org-link-file-path-type 'adaptive
1028 "How the path name in file links should be stored.
1029 Valid values are:
1031 relative Relative to the current directory, i.e. the directory of the file
1032 into which the link is being inserted.
1033 absolute Absolute path, if possible with ~ for home directory.
1034 noabbrev Absolute path, no abbreviation of home directory.
1035 adaptive Use relative path for files in the current directory and sub-
1036 directories of it. For other files, use an absolute path."
1037 :group 'org-link
1038 :type '(choice
1039 (const relative)
1040 (const absolute)
1041 (const noabbrev)
1042 (const adaptive)))
1044 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1045 "Types of links that should be activated in Org-mode files.
1046 This is a list of symbols, each leading to the activation of a certain link
1047 type. In principle, it does not hurt to turn on most link types - there may
1048 be a small gain when turning off unused link types. The types are:
1050 bracket The recommended [[link][description]] or [[link]] links with hiding.
1051 angular Links in angular brackets that may contain whitespace like
1052 <bbdb:Carsten Dominik>.
1053 plain Plain links in normal text, no whitespace, like http://google.com.
1054 radio Text that is matched by a radio target, see manual for details.
1055 tag Tag settings in a headline (link to tag search).
1056 date Time stamps (link to calendar).
1057 footnote Footnote labels.
1059 Changing this variable requires a restart of Emacs to become effective."
1060 :group 'org-link
1061 :type '(set :greedy t
1062 (const :tag "Double bracket links (new style)" bracket)
1063 (const :tag "Angular bracket links (old style)" angular)
1064 (const :tag "Plain text links" plain)
1065 (const :tag "Radio target matches" radio)
1066 (const :tag "Tags" tag)
1067 (const :tag "Timestamps" date)
1068 (const :tag "Footnotes" footnote)))
1070 (defcustom org-make-link-description-function nil
1071 "Function to use to generate link descriptions from links. If
1072 nil the link location will be used. This function must take two
1073 parameters; the first is the link and the second the description
1074 org-insert-link has generated, and should return the description
1075 to use."
1076 :group 'org-link
1077 :type 'function)
1079 (defgroup org-link-store nil
1080 "Options concerning storing links in Org-mode."
1081 :tag "Org Store Link"
1082 :group 'org-link)
1084 (defcustom org-email-link-description-format "Email %c: %.30s"
1085 "Format of the description part of a link to an email or usenet message.
1086 The following %-escapes will be replaced by corresponding information:
1088 %F full \"From\" field
1089 %f name, taken from \"From\" field, address if no name
1090 %T full \"To\" field
1091 %t first name in \"To\" field, address if no name
1092 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1093 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1094 %s subject
1095 %m message-id.
1097 You may use normal field width specification between the % and the letter.
1098 This is for example useful to limit the length of the subject.
1100 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1101 :group 'org-link-store
1102 :type 'string)
1104 (defcustom org-from-is-user-regexp
1105 (let (r1 r2)
1106 (when (and user-mail-address (not (string= user-mail-address "")))
1107 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1108 (when (and user-full-name (not (string= user-full-name "")))
1109 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1110 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1111 "Regexp matched against the \"From:\" header of an email or usenet message.
1112 It should match if the message is from the user him/herself."
1113 :group 'org-link-store
1114 :type 'regexp)
1116 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1117 "Non-nil means, storing a link to an Org file will use entry IDs.
1119 Note that before this variable is even considered, org-id must be loaded,
1120 so please customize `org-modules' and turn it on.
1122 The variable can have the following values:
1124 t Create an ID if needed to make a link to the current entry.
1126 create-if-interactive
1127 If `org-store-link' is called directly (interactively, as a user
1128 command), do create an ID to support the link. But when doing the
1129 job for remember, only use the ID if it already exists. The
1130 purpose of this setting is to avoid proliferation of unwanted
1131 IDs, just because you happen to be in an Org file when you
1132 call `org-remember' that automatically and preemptively
1133 creates a link. If you do want to get an ID link in a remember
1134 template to an entry not having an ID, create it first by
1135 explicitly creating a link to it, using `C-c C-l' first.
1137 create-if-interactive-and-no-custom-id
1138 Like create-if-interactive, but do not create an ID if there is
1139 a CUSTOM_ID property defined in the entry. This is the default.
1141 use-existing
1142 Use existing ID, do not create one.
1144 nil Never use an ID to make a link, instead link using a text search for
1145 the headline text."
1146 :group 'org-link-store
1147 :type '(choice
1148 (const :tag "Create ID to make link" t)
1149 (const :tag "Create if storing link interactively"
1150 create-if-interactive)
1151 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1152 create-if-interactive-and-no-custom-id)
1153 (const :tag "Only use existing" use-existing)
1154 (const :tag "Do not use ID to create link" nil)))
1156 (defcustom org-context-in-file-links t
1157 "Non-nil means, file links from `org-store-link' contain context.
1158 A search string will be added to the file name with :: as separator and
1159 used to find the context when the link is activated by the command
1160 `org-open-at-point'.
1161 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1162 negates this setting for the duration of the command."
1163 :group 'org-link-store
1164 :type 'boolean)
1166 (defcustom org-keep-stored-link-after-insertion nil
1167 "Non-nil means, keep link in list for entire session.
1169 The command `org-store-link' adds a link pointing to the current
1170 location to an internal list. These links accumulate during a session.
1171 The command `org-insert-link' can be used to insert links into any
1172 Org-mode file (offering completion for all stored links). When this
1173 option is nil, every link which has been inserted once using \\[org-insert-link]
1174 will be removed from the list, to make completing the unused links
1175 more efficient."
1176 :group 'org-link-store
1177 :type 'boolean)
1179 (defgroup org-link-follow nil
1180 "Options concerning following links in Org-mode."
1181 :tag "Org Follow Link"
1182 :group 'org-link)
1184 (defcustom org-link-translation-function nil
1185 "Function to translate links with different syntax to Org syntax.
1186 This can be used to translate links created for example by the Planner
1187 or emacs-wiki packages to Org syntax.
1188 The function must accept two parameters, a TYPE containing the link
1189 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1190 which is everything after the link protocol. It should return a cons
1191 with possibly modified values of type and path.
1192 Org contains a function for this, so if you set this variable to
1193 `org-translate-link-from-planner', you should be able follow many
1194 links created by planner."
1195 :group 'org-link-follow
1196 :type 'function)
1198 (defcustom org-follow-link-hook nil
1199 "Hook that is run after a link has been followed."
1200 :group 'org-link-follow
1201 :type 'hook)
1203 (defcustom org-tab-follows-link nil
1204 "Non-nil means, on links TAB will follow the link.
1205 Needs to be set before org.el is loaded.
1206 This really should not be used, it does not make sense, and the
1207 implementation is bad."
1208 :group 'org-link-follow
1209 :type 'boolean)
1211 (defcustom org-return-follows-link nil
1212 "Non-nil means, on links RET will follow the link.
1213 Needs to be set before org.el is loaded."
1214 :group 'org-link-follow
1215 :type 'boolean)
1217 (defcustom org-mouse-1-follows-link
1218 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1219 "Non-nil means, mouse-1 on a link will follow the link.
1220 A longer mouse click will still set point. Does not work on XEmacs.
1221 Needs to be set before org.el is loaded."
1222 :group 'org-link-follow
1223 :type 'boolean)
1225 (defcustom org-mark-ring-length 4
1226 "Number of different positions to be recorded in the ring
1227 Changing this requires a restart of Emacs to work correctly."
1228 :group 'org-link-follow
1229 :type 'integer)
1231 (defcustom org-link-frame-setup
1232 '((vm . vm-visit-folder-other-frame)
1233 (gnus . gnus-other-frame)
1234 (file . find-file-other-window))
1235 "Setup the frame configuration for following links.
1236 When following a link with Emacs, it may often be useful to display
1237 this link in another window or frame. This variable can be used to
1238 set this up for the different types of links.
1239 For VM, use any of
1240 `vm-visit-folder'
1241 `vm-visit-folder-other-frame'
1242 For Gnus, use any of
1243 `gnus'
1244 `gnus-other-frame'
1245 `org-gnus-no-new-news'
1246 For FILE, use any of
1247 `find-file'
1248 `find-file-other-window'
1249 `find-file-other-frame'
1250 For the calendar, use the variable `calendar-setup'.
1251 For BBDB, it is currently only possible to display the matches in
1252 another window."
1253 :group 'org-link-follow
1254 :type '(list
1255 (cons (const vm)
1256 (choice
1257 (const vm-visit-folder)
1258 (const vm-visit-folder-other-window)
1259 (const vm-visit-folder-other-frame)))
1260 (cons (const gnus)
1261 (choice
1262 (const gnus)
1263 (const gnus-other-frame)
1264 (const org-gnus-no-new-news)))
1265 (cons (const file)
1266 (choice
1267 (const find-file)
1268 (const find-file-other-window)
1269 (const find-file-other-frame)))))
1271 (defcustom org-display-internal-link-with-indirect-buffer nil
1272 "Non-nil means, use indirect buffer to display infile links.
1273 Activating internal links (from one location in a file to another location
1274 in the same file) normally just jumps to the location. When the link is
1275 activated with a C-u prefix (or with mouse-3), the link is displayed in
1276 another window. When this option is set, the other window actually displays
1277 an indirect buffer clone of the current buffer, to avoid any visibility
1278 changes to the current buffer."
1279 :group 'org-link-follow
1280 :type 'boolean)
1282 (defcustom org-open-non-existing-files nil
1283 "Non-nil means, `org-open-file' will open non-existing files.
1284 When nil, an error will be generated.
1285 This variable applies only to external applications because they
1286 might choke on non-existing files. If the link is to a file that
1287 will be openend in Emacs, the variable is ignored."
1288 :group 'org-link-follow
1289 :type 'boolean)
1291 (defcustom org-open-directory-means-index-dot-org nil
1292 "Non-nil means, a link to a directory really means to index.org.
1293 When nil, following a directory link will run dired or open a finder/explorer
1294 window on that directory."
1295 :group 'org-link-follow
1296 :type 'boolean)
1298 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1299 "Function and arguments to call for following mailto links.
1300 This is a list with the first element being a lisp function, and the
1301 remaining elements being arguments to the function. In string arguments,
1302 %a will be replaced by the address, and %s will be replaced by the subject
1303 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1304 :group 'org-link-follow
1305 :type '(choice
1306 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1307 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1308 (const :tag "message-mail" (message-mail "%a" "%s"))
1309 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1311 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1312 "Non-nil means, ask for confirmation before executing shell links.
1313 Shell links can be dangerous: just think about a link
1315 [[shell:rm -rf ~/*][Google Search]]
1317 This link would show up in your Org-mode document as \"Google Search\",
1318 but really it would remove your entire home directory.
1319 Therefore we advise against setting this variable to nil.
1320 Just change it to `y-or-n-p' if you want to confirm with a
1321 single keystroke rather than having to type \"yes\"."
1322 :group 'org-link-follow
1323 :type '(choice
1324 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1325 (const :tag "with y-or-n (faster)" y-or-n-p)
1326 (const :tag "no confirmation (dangerous)" nil)))
1328 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1329 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1330 Elisp links can be dangerous: just think about a link
1332 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1334 This link would show up in your Org-mode document as \"Google Search\",
1335 but really it would remove your entire home directory.
1336 Therefore we advise against setting this variable to nil.
1337 Just change it to `y-or-n-p' if you want to confirm with a
1338 single keystroke rather than having to type \"yes\"."
1339 :group 'org-link-follow
1340 :type '(choice
1341 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1342 (const :tag "with y-or-n (faster)" y-or-n-p)
1343 (const :tag "no confirmation (dangerous)" nil)))
1345 (defconst org-file-apps-defaults-gnu
1346 '((remote . emacs)
1347 (system . mailcap)
1348 (t . mailcap))
1349 "Default file applications on a UNIX or GNU/Linux system.
1350 See `org-file-apps'.")
1352 (defconst org-file-apps-defaults-macosx
1353 '((remote . emacs)
1354 (t . "open %s")
1355 (system . "open %s")
1356 ("ps.gz" . "gv %s")
1357 ("eps.gz" . "gv %s")
1358 ("dvi" . "xdvi %s")
1359 ("fig" . "xfig %s"))
1360 "Default file applications on a MacOS X system.
1361 The system \"open\" is known as a default, but we use X11 applications
1362 for some files for which the OS does not have a good default.
1363 See `org-file-apps'.")
1365 (defconst org-file-apps-defaults-windowsnt
1366 (list
1367 '(remote . emacs)
1368 (cons t
1369 (list (if (featurep 'xemacs)
1370 'mswindows-shell-execute
1371 'w32-shell-execute)
1372 "open" 'file))
1373 (cons 'system
1374 (list (if (featurep 'xemacs)
1375 'mswindows-shell-execute
1376 'w32-shell-execute)
1377 "open" 'file)))
1378 "Default file applications on a Windows NT system.
1379 The system \"open\" is used for most files.
1380 See `org-file-apps'.")
1382 (defcustom org-file-apps
1384 (auto-mode . emacs)
1385 ("\\.x?html?\\'" . default)
1386 ("\\.pdf\\'" . default)
1388 "External applications for opening `file:path' items in a document.
1389 Org-mode uses system defaults for different file types, but
1390 you can use this variable to set the application for a given file
1391 extension. The entries in this list are cons cells where the car identifies
1392 files and the cdr the corresponding command. Possible values for the
1393 file identifier are
1394 \"regex\" Regular expression matched against the file name. For backward
1395 compatibility, this can also be a string with only alphanumeric
1396 characters, which is then interpreted as an extension.
1397 `directory' Matches a directory
1398 `remote' Matches a remote file, accessible through tramp or efs.
1399 Remote files most likely should be visited through Emacs
1400 because external applications cannot handle such paths.
1401 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1402 so all files Emacs knows how to handle. Using this with
1403 command `emacs' will open most files in Emacs. Beware that this
1404 will also open html files inside Emacs, unless you add
1405 (\"html\" . default) to the list as well.
1406 t Default for files not matched by any of the other options.
1407 `system' The system command to open files, like `open' on Windows
1408 and Mac OS X, and mailcap under GNU/Linux. This is the command
1409 that will be selected if you call `C-c C-o' with a double
1410 `C-u C-u' prefix.
1412 Possible values for the command are:
1413 `emacs' The file will be visited by the current Emacs process.
1414 `default' Use the default application for this file type, which is the
1415 association for t in the list, most likely in the system-specific
1416 part.
1417 This can be used to overrule an unwanted setting in the
1418 system-specific variable.
1419 `system' Use the system command for opening files, like \"open\".
1420 This command is specified by the entry whose car is `system'.
1421 Most likely, the system-specific version of this variable
1422 does define this command, but you can overrule/replace it
1423 here.
1424 string A command to be executed by a shell; %s will be replaced
1425 by the path to the file.
1426 sexp A Lisp form which will be evaluated. The file path will
1427 be available in the Lisp variable `file'.
1428 For more examples, see the system specific constants
1429 `org-file-apps-defaults-macosx'
1430 `org-file-apps-defaults-windowsnt'
1431 `org-file-apps-defaults-gnu'."
1432 :group 'org-link-follow
1433 :type '(repeat
1434 (cons (choice :value ""
1435 (string :tag "Extension")
1436 (const :tag "System command to open files" system)
1437 (const :tag "Default for unrecognized files" t)
1438 (const :tag "Remote file" remote)
1439 (const :tag "Links to a directory" directory)
1440 (const :tag "Any files that have Emacs modes"
1441 auto-mode))
1442 (choice :value ""
1443 (const :tag "Visit with Emacs" emacs)
1444 (const :tag "Use default" default)
1445 (const :tag "Use the system command" system)
1446 (string :tag "Command")
1447 (sexp :tag "Lisp form")))))
1449 (defgroup org-refile nil
1450 "Options concerning refiling entries in Org-mode."
1451 :tag "Org Refile"
1452 :group 'org)
1454 (defcustom org-directory "~/org"
1455 "Directory with org files.
1456 This is just a default location to look for Org files. There is no need
1457 at all to put your files into this directory. It is only used in the
1458 following situations:
1460 1. When a remember template specifies a target file that is not an
1461 absolute path. The path will then be interpreted relative to
1462 `org-directory'
1463 2. When a remember note is filed away in an interactive way (when exiting the
1464 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1465 with `org-directory' as the default path."
1466 :group 'org-refile
1467 :group 'org-remember
1468 :type 'directory)
1470 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1471 "Default target for storing notes.
1472 Used by the hooks for remember.el. This can be a string, or nil to mean
1473 the value of `remember-data-file'.
1474 You can set this on a per-template basis with the variable
1475 `org-remember-templates'."
1476 :group 'org-refile
1477 :group 'org-remember
1478 :type '(choice
1479 (const :tag "Default from remember-data-file" nil)
1480 file))
1482 (defcustom org-goto-interface 'outline
1483 "The default interface to be used for `org-goto'.
1484 Allowed values are:
1485 outline The interface shows an outline of the relevant file
1486 and the correct heading is found by moving through
1487 the outline or by searching with incremental search.
1488 outline-path-completion Headlines in the current buffer are offered via
1489 completion. This is the interface also used by
1490 the refile command."
1491 :group 'org-refile
1492 :type '(choice
1493 (const :tag "Outline" outline)
1494 (const :tag "Outline-path-completion" outline-path-completion)))
1496 (defcustom org-goto-max-level 5
1497 "Maximum level to be considered when running org-goto with refile interface."
1498 :group 'org-refile
1499 :type 'integer)
1501 (defcustom org-reverse-note-order nil
1502 "Non-nil means, store new notes at the beginning of a file or entry.
1503 When nil, new notes will be filed to the end of a file or entry.
1504 This can also be a list with cons cells of regular expressions that
1505 are matched against file names, and values."
1506 :group 'org-remember
1507 :group 'org-refile
1508 :type '(choice
1509 (const :tag "Reverse always" t)
1510 (const :tag "Reverse never" nil)
1511 (repeat :tag "By file name regexp"
1512 (cons regexp boolean))))
1514 (defcustom org-refile-targets nil
1515 "Targets for refiling entries with \\[org-refile].
1516 This is list of cons cells. Each cell contains:
1517 - a specification of the files to be considered, either a list of files,
1518 or a symbol whose function or variable value will be used to retrieve
1519 a file name or a list of file names. If you use `org-agenda-files' for
1520 that, all agenda files will be scanned for targets. Nil means, consider
1521 headings in the current buffer.
1522 - A specification of how to find candidate refile targets. This may be
1523 any of:
1524 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1525 This tag has to be present in all target headlines, inheritance will
1526 not be considered.
1527 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1528 todo keyword.
1529 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1530 headlines that are refiling targets.
1531 - a cons cell (:level . N). Any headline of level N is considered a target.
1532 Note that, when `org-odd-levels-only' is set, level corresponds to
1533 order in hierarchy, not to the number of stars.
1534 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1535 Note that, when `org-odd-levels-only' is set, level corresponds to
1536 order in hierarchy, not to the number of stars.
1538 You can set the variable `org-refile-target-verify-function' to a function
1539 to verify each headline found by the simple critery above.
1541 When this variable is nil, all top-level headlines in the current buffer
1542 are used, equivalent to the value `((nil . (:level . 1))'."
1543 :group 'org-refile
1544 :type '(repeat
1545 (cons
1546 (choice :value org-agenda-files
1547 (const :tag "All agenda files" org-agenda-files)
1548 (const :tag "Current buffer" nil)
1549 (function) (variable) (file))
1550 (choice :tag "Identify target headline by"
1551 (cons :tag "Specific tag" (const :value :tag) (string))
1552 (cons :tag "TODO keyword" (const :value :todo) (string))
1553 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1554 (cons :tag "Level number" (const :value :level) (integer))
1555 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1557 (defcustom org-refile-target-verify-function nil
1558 "Function to verify if the headline at point should be a refile target.
1559 The function will be called without arguments, with point at the
1560 beginning of the headline. It should return t and leave point
1561 where it is if the headline is a valid target for refiling.
1563 If the target should not be selected, the function must return nil.
1564 In addition to this, it may move point to a place from where the search
1565 should be continued. For example, the function may decide that the entire
1566 subtree of the current entry should be excluded and move point to the end
1567 of the subtree."
1568 :group 'org-refile
1569 :type 'function)
1571 (defcustom org-refile-use-outline-path nil
1572 "Non-nil means, provide refile targets as paths.
1573 So a level 3 headline will be available as level1/level2/level3.
1575 When the value is `file', also include the file name (without directory)
1576 into the path. In this case, you can also stop the completion after
1577 the file name, to get entries inserted as top level in the file.
1579 When `full-file-path', include the full file path."
1580 :group 'org-refile
1581 :type '(choice
1582 (const :tag "Not" nil)
1583 (const :tag "Yes" t)
1584 (const :tag "Start with file name" file)
1585 (const :tag "Start with full file path" full-file-path)))
1587 (defcustom org-outline-path-complete-in-steps t
1588 "Non-nil means, complete the outline path in hierarchical steps.
1589 When Org-mode uses the refile interface to select an outline path
1590 \(see variable `org-refile-use-outline-path'), the completion of
1591 the path can be done is a single go, or if can be done in steps down
1592 the headline hierarchy. Going in steps is probably the best if you
1593 do not use a special completion package like `ido' or `icicles'.
1594 However, when using these packages, going in one step can be very
1595 fast, while still showing the whole path to the entry."
1596 :group 'org-refile
1597 :type 'boolean)
1599 (defcustom org-refile-allow-creating-parent-nodes nil
1600 "Non-nil means, allow to create new nodes as refile targets.
1601 New nodes are then created by adding \"/new node name\" to the completion
1602 of an existing node. When the value of this variable is `confirm',
1603 new node creation must be confirmed by the user (recommended)
1604 When nil, the completion must match an existing entry.
1606 Note that, if the new heading is not seen by the criteria
1607 listed in `org-refile-targets', multiple instances of the same
1608 heading would be created by trying again to file under the new
1609 heading."
1610 :group 'org-refile
1611 :type '(choice
1612 (const :tag "Never" nil)
1613 (const :tag "Always" t)
1614 (const :tag "Prompt for confirmation" confirm)))
1616 (defgroup org-todo nil
1617 "Options concerning TODO items in Org-mode."
1618 :tag "Org TODO"
1619 :group 'org)
1621 (defgroup org-progress nil
1622 "Options concerning Progress logging in Org-mode."
1623 :tag "Org Progress"
1624 :group 'org-time)
1626 (defvar org-todo-interpretation-widgets
1628 (:tag "Sequence (cycling hits every state)" sequence)
1629 (:tag "Type (cycling directly to DONE)" type))
1630 "The available interpretation symbols for customizing
1631 `org-todo-keywords'.
1632 Interested libraries should add to this list.")
1634 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1635 "List of TODO entry keyword sequences and their interpretation.
1636 \\<org-mode-map>This is a list of sequences.
1638 Each sequence starts with a symbol, either `sequence' or `type',
1639 indicating if the keywords should be interpreted as a sequence of
1640 action steps, or as different types of TODO items. The first
1641 keywords are states requiring action - these states will select a headline
1642 for inclusion into the global TODO list Org-mode produces. If one of
1643 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1644 signify that no further action is necessary. If \"|\" is not found,
1645 the last keyword is treated as the only DONE state of the sequence.
1647 The command \\[org-todo] cycles an entry through these states, and one
1648 additional state where no keyword is present. For details about this
1649 cycling, see the manual.
1651 TODO keywords and interpretation can also be set on a per-file basis with
1652 the special #+SEQ_TODO and #+TYP_TODO lines.
1654 Each keyword can optionally specify a character for fast state selection
1655 \(in combination with the variable `org-use-fast-todo-selection')
1656 and specifiers for state change logging, using the same syntax
1657 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1658 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1659 indicates to record a time stamp each time this state is selected.
1661 Each keyword may also specify if a timestamp or a note should be
1662 recorded when entering or leaving the state, by adding additional
1663 characters in the parenthesis after the keyword. This looks like this:
1664 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1665 record only the time of the state change. With X and Y being either
1666 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1667 Y when leaving the state if and only if the *target* state does not
1668 define X. You may omit any of the fast-selection key or X or /Y,
1669 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1671 For backward compatibility, this variable may also be just a list
1672 of keywords - in this case the interpretation (sequence or type) will be
1673 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1674 :group 'org-todo
1675 :group 'org-keywords
1676 :type '(choice
1677 (repeat :tag "Old syntax, just keywords"
1678 (string :tag "Keyword"))
1679 (repeat :tag "New syntax"
1680 (cons
1681 (choice
1682 :tag "Interpretation"
1683 ;;Quick and dirty way to see
1684 ;;`org-todo-interpretations'. This takes the
1685 ;;place of item arguments
1686 :convert-widget
1687 (lambda (widget)
1688 (widget-put widget
1689 :args (mapcar
1690 #'(lambda (x)
1691 (widget-convert
1692 (cons 'const x)))
1693 org-todo-interpretation-widgets))
1694 widget))
1695 (repeat
1696 (string :tag "Keyword"))))))
1698 (defvar org-todo-keywords-1 nil
1699 "All TODO and DONE keywords active in a buffer.")
1700 (make-variable-buffer-local 'org-todo-keywords-1)
1701 (defvar org-todo-keywords-for-agenda nil)
1702 (defvar org-done-keywords-for-agenda nil)
1703 (defvar org-todo-keyword-alist-for-agenda nil)
1704 (defvar org-tag-alist-for-agenda nil)
1705 (defvar org-agenda-contributing-files nil)
1706 (defvar org-not-done-keywords nil)
1707 (make-variable-buffer-local 'org-not-done-keywords)
1708 (defvar org-done-keywords nil)
1709 (make-variable-buffer-local 'org-done-keywords)
1710 (defvar org-todo-heads nil)
1711 (make-variable-buffer-local 'org-todo-heads)
1712 (defvar org-todo-sets nil)
1713 (make-variable-buffer-local 'org-todo-sets)
1714 (defvar org-todo-log-states nil)
1715 (make-variable-buffer-local 'org-todo-log-states)
1716 (defvar org-todo-kwd-alist nil)
1717 (make-variable-buffer-local 'org-todo-kwd-alist)
1718 (defvar org-todo-key-alist nil)
1719 (make-variable-buffer-local 'org-todo-key-alist)
1720 (defvar org-todo-key-trigger nil)
1721 (make-variable-buffer-local 'org-todo-key-trigger)
1723 (defcustom org-todo-interpretation 'sequence
1724 "Controls how TODO keywords are interpreted.
1725 This variable is in principle obsolete and is only used for
1726 backward compatibility, if the interpretation of todo keywords is
1727 not given already in `org-todo-keywords'. See that variable for
1728 more information."
1729 :group 'org-todo
1730 :group 'org-keywords
1731 :type '(choice (const sequence)
1732 (const type)))
1734 (defcustom org-use-fast-todo-selection t
1735 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1736 This variable describes if and under what circumstances the cycling
1737 mechanism for TODO keywords will be replaced by a single-key, direct
1738 selection scheme.
1740 When nil, fast selection is never used.
1742 When the symbol `prefix', it will be used when `org-todo' is called with
1743 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1744 in an agenda buffer.
1746 When t, fast selection is used by default. In this case, the prefix
1747 argument forces cycling instead.
1749 In all cases, the special interface is only used if access keys have actually
1750 been assigned by the user, i.e. if keywords in the configuration are followed
1751 by a letter in parenthesis, like TODO(t)."
1752 :group 'org-todo
1753 :type '(choice
1754 (const :tag "Never" nil)
1755 (const :tag "By default" t)
1756 (const :tag "Only with C-u C-c C-t" prefix)))
1758 (defcustom org-provide-todo-statistics t
1759 "Non-nil means, update todo statistics after insert and toggle.
1760 ALL-HEADLINES means update todo statistics by including headlines
1761 with no TODO keyword as well, counting them as not done.
1762 A list of TODO keywords means the same, but skip keywords that are
1763 not in this list.
1765 When this is set, todo statistics is updated in the parent of the
1766 current entry each time a todo state is changed."
1767 :group 'org-todo
1768 :type '(choice
1769 (const :tag "Yes, only for TODO entries" t)
1770 (const :tag "Yes, including all entries" 'all-headlines)
1771 (repeat :tag "Yes, for TODOs in this list"
1772 (string :tag "TODO keyword"))
1773 (other :tag "No TODO statistics" nil)))
1775 (defcustom org-hierarchical-todo-statistics t
1776 "Non-nil means, TODO statistics covers just direct children.
1777 When nil, all entries in the subtree are considered.
1778 This has only an effect if `org-provide-todo-statistics' is set.
1779 To set this to nil for only a single subtree, use a COOKIE_DATA
1780 property and include the word \"recursive\" into the value."
1781 :group 'org-todo
1782 :type 'boolean)
1784 (defcustom org-after-todo-state-change-hook nil
1785 "Hook which is run after the state of a TODO item was changed.
1786 The new state (a string with a TODO keyword, or nil) is available in the
1787 Lisp variable `state'."
1788 :group 'org-todo
1789 :type 'hook)
1791 (defvar org-blocker-hook nil
1792 "Hook for functions that are allowed to block a state change.
1794 Each function gets as its single argument a property list, see
1795 `org-trigger-hook' for more information about this list.
1797 If any of the functions in this hook returns nil, the state change
1798 is blocked.")
1800 (defvar org-trigger-hook nil
1801 "Hook for functions that are triggered by a state change.
1803 Each function gets as its single argument a property list with at least
1804 the following elements:
1806 (:type type-of-change :position pos-at-entry-start
1807 :from old-state :to new-state)
1809 Depending on the type, more properties may be present.
1811 This mechanism is currently implemented for:
1813 TODO state changes
1814 ------------------
1815 :type todo-state-change
1816 :from previous state (keyword as a string), or nil, or a symbol
1817 'todo' or 'done', to indicate the general type of state.
1818 :to new state, like in :from")
1820 (defcustom org-enforce-todo-dependencies nil
1821 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1822 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1823 be blocked if any prior sibling is not yet done.
1824 Finally, if the parent is blocked because of ordered siblings of its own,
1825 the child will also be blocked.
1826 This variable needs to be set before org.el is loaded, and you need to
1827 restart Emacs after a change to make the change effective. The only way
1828 to change is while Emacs is running is through the customize interface."
1829 :set (lambda (var val)
1830 (set var val)
1831 (if val
1832 (add-hook 'org-blocker-hook
1833 'org-block-todo-from-children-or-siblings-or-parent)
1834 (remove-hook 'org-blocker-hook
1835 'org-block-todo-from-children-or-siblings-or-parent)))
1836 :group 'org-todo
1837 :type 'boolean)
1839 (defcustom org-enforce-todo-checkbox-dependencies nil
1840 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1841 When this is nil, checkboxes have no influence on switching TODO states.
1842 When non-nil, you first need to check off all check boxes before the TODO
1843 entry can be switched to DONE.
1844 This variable needs to be set before org.el is loaded, and you need to
1845 restart Emacs after a change to make the change effective. The only way
1846 to change is while Emacs is running is through the customize interface."
1847 :set (lambda (var val)
1848 (set var val)
1849 (if val
1850 (add-hook 'org-blocker-hook
1851 'org-block-todo-from-checkboxes)
1852 (remove-hook 'org-blocker-hook
1853 'org-block-todo-from-checkboxes)))
1854 :group 'org-todo
1855 :type 'boolean)
1857 (defcustom org-treat-insert-todo-heading-as-state-change nil
1858 "Non-nil means, inserting a TODO heading is treated as state change.
1859 So when the command \\[org-insert-todo-heading] is used, state change
1860 logging will apply if appropriate. When nil, the new TODO item will
1861 be inserted directly, and no logging will take place."
1862 :group 'org-todo
1863 :type 'boolean)
1865 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1866 "Non-nil means, switching TODO states with S-cursor counts as state change.
1867 This is the default behavior. However, setting this to nil allows a
1868 convenient way to select a TODO state and bypass any logging associated
1869 with that."
1870 :group 'org-todo
1871 :type 'boolean)
1873 (defcustom org-todo-state-tags-triggers nil
1874 "Tag changes that should be triggered by TODO state changes.
1875 This is a list. Each entry is
1877 (state-change (tag . flag) .......)
1879 State-change can be a string with a state, and empty string to indicate the
1880 state that has no TODO keyword, or it can be one of the symbols `todo'
1881 or `done', meaning any not-done or done state, respectively."
1882 :group 'org-todo
1883 :group 'org-tags
1884 :type '(repeat
1885 (cons (choice :tag "When changing to"
1886 (const :tag "Not-done state" todo)
1887 (const :tag "Done state" done)
1888 (string :tag "State"))
1889 (repeat
1890 (cons :tag "Tag action"
1891 (string :tag "Tag")
1892 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1894 (defcustom org-log-done nil
1895 "Information to record when a task moves to the DONE state.
1897 Possible values are:
1899 nil Don't add anything, just change the keyword
1900 time Add a time stamp to the task
1901 note Prompt a closing note and add it with template `org-log-note-headings'
1903 This option can also be set with on a per-file-basis with
1905 #+STARTUP: nologdone
1906 #+STARTUP: logdone
1907 #+STARTUP: lognotedone
1909 You can have local logging settings for a subtree by setting the LOGGING
1910 property to one or more of these keywords."
1911 :group 'org-todo
1912 :group 'org-progress
1913 :type '(choice
1914 (const :tag "No logging" nil)
1915 (const :tag "Record CLOSED timestamp" time)
1916 (const :tag "Record CLOSED timestamp with closing note." note)))
1918 ;; Normalize old uses of org-log-done.
1919 (cond
1920 ((eq org-log-done t) (setq org-log-done 'time))
1921 ((and (listp org-log-done) (memq 'done org-log-done))
1922 (setq org-log-done 'note)))
1924 (defcustom org-log-note-clock-out nil
1925 "Non-nil means, record a note when clocking out of an item.
1926 This can also be configured on a per-file basis by adding one of
1927 the following lines anywhere in the buffer:
1929 #+STARTUP: lognoteclock-out
1930 #+STARTUP: nolognoteclock-out"
1931 :group 'org-todo
1932 :group 'org-progress
1933 :type 'boolean)
1935 (defcustom org-log-done-with-time t
1936 "Non-nil means, the CLOSED time stamp will contain date and time.
1937 When nil, only the date will be recorded."
1938 :group 'org-progress
1939 :type 'boolean)
1941 (defcustom org-log-note-headings
1942 '((done . "CLOSING NOTE %t")
1943 (state . "State %-12s from %-12S %t")
1944 (note . "Note taken on %t")
1945 (clock-out . ""))
1946 "Headings for notes added to entries.
1947 The value is an alist, with the car being a symbol indicating the note
1948 context, and the cdr is the heading to be used. The heading may also be the
1949 empty string.
1950 %t in the heading will be replaced by a time stamp.
1951 %s will be replaced by the new TODO state, in double quotes.
1952 %S will be replaced by the old TODO state, in double quotes.
1953 %u will be replaced by the user name.
1954 %U will be replaced by the full user name."
1955 :group 'org-todo
1956 :group 'org-progress
1957 :type '(list :greedy t
1958 (cons (const :tag "Heading when closing an item" done) string)
1959 (cons (const :tag
1960 "Heading when changing todo state (todo sequence only)"
1961 state) string)
1962 (cons (const :tag "Heading when just taking a note" note) string)
1963 (cons (const :tag "Heading when clocking out" clock-out) string)))
1965 (unless (assq 'note org-log-note-headings)
1966 (push '(note . "%t") org-log-note-headings))
1968 (defcustom org-log-into-drawer nil
1969 "Non-nil means, insert state change notes and time stamps into a drawer.
1970 When nil, state changes notes will be inserted after the headline and
1971 any scheduling and clock lines, but not inside a drawer.
1973 The value of this variable should be the name of the drawer to use.
1974 LOGBOOK is proposed at the default drawer for this purpose, you can
1975 also set this to a string to define the drawer of your choice.
1977 A value of t is also allowed, representing \"LOGBOOK\".
1979 If this variable is set, `org-log-state-notes-insert-after-drawers'
1980 will be ignored.
1982 You can set the property LOG_INTO_DRAWER to overrule this setting for
1983 a subtree."
1984 :group 'org-todo
1985 :group 'org-progress
1986 :type '(choice
1987 (const :tag "Not into a drawer" nil)
1988 (const :tag "LOGBOOK" t)
1989 (string :tag "Other")))
1991 (if (fboundp 'defvaralias)
1992 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1994 (defun org-log-into-drawer ()
1995 "Return the value of `org-log-into-drawer', but let properties overrule.
1996 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1997 used instead of the default value."
1998 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1999 (cond
2000 ((or (not p) (equal p "nil")) org-log-into-drawer)
2001 ((equal p "t") "LOGBOOK")
2002 (t p))))
2004 (defcustom org-log-state-notes-insert-after-drawers nil
2005 "Non-nil means, insert state change notes after any drawers in entry.
2006 Only the drawers that *immediately* follow the headline and the
2007 deadline/scheduled line are skipped.
2008 When nil, insert notes right after the heading and perhaps the line
2009 with deadline/scheduling if present.
2011 This variable will have no effect if `org-log-into-drawer' is
2012 set."
2013 :group 'org-todo
2014 :group 'org-progress
2015 :type 'boolean)
2017 (defcustom org-log-states-order-reversed t
2018 "Non-nil means, the latest state change note will be directly after heading.
2019 When nil, the notes will be orderer according to time."
2020 :group 'org-todo
2021 :group 'org-progress
2022 :type 'boolean)
2024 (defcustom org-log-repeat 'time
2025 "Non-nil means, record moving through the DONE state when triggering repeat.
2026 An auto-repeating tasks is immediately switched back to TODO when marked
2027 done. If you are not logging state changes (by adding \"@\" or \"!\" to
2028 the TODO keyword definition, or recording a closing note by setting
2029 `org-log-done', there will be no record of the task moving through DONE.
2030 This variable forces taking a note anyway. Possible values are:
2032 nil Don't force a record
2033 time Record a time stamp
2034 note Record a note
2036 This option can also be set with on a per-file-basis with
2038 #+STARTUP: logrepeat
2039 #+STARTUP: lognoterepeat
2040 #+STARTUP: nologrepeat
2042 You can have local logging settings for a subtree by setting the LOGGING
2043 property to one or more of these keywords."
2044 :group 'org-todo
2045 :group 'org-progress
2046 :type '(choice
2047 (const :tag "Don't force a record" nil)
2048 (const :tag "Force recording the DONE state" time)
2049 (const :tag "Force recording a note with the DONE state" note)))
2052 (defgroup org-priorities nil
2053 "Priorities in Org-mode."
2054 :tag "Org Priorities"
2055 :group 'org-todo)
2057 (defcustom org-enable-priority-commands t
2058 "Non-nil means, priority commands are active.
2059 When nil, these commands will be disabled, so that you never accidentally
2060 set a priority."
2061 :group 'org-priorities
2062 :type 'boolean)
2064 (defcustom org-highest-priority ?A
2065 "The highest priority of TODO items. A character like ?A, ?B etc.
2066 Must have a smaller ASCII number than `org-lowest-priority'."
2067 :group 'org-priorities
2068 :type 'character)
2070 (defcustom org-lowest-priority ?C
2071 "The lowest priority of TODO items. A character like ?A, ?B etc.
2072 Must have a larger ASCII number than `org-highest-priority'."
2073 :group 'org-priorities
2074 :type 'character)
2076 (defcustom org-default-priority ?B
2077 "The default priority of TODO items.
2078 This is the priority an item get if no explicit priority is given."
2079 :group 'org-priorities
2080 :type 'character)
2082 (defcustom org-priority-start-cycle-with-default t
2083 "Non-nil means, start with default priority when starting to cycle.
2084 When this is nil, the first step in the cycle will be (depending on the
2085 command used) one higher or lower that the default priority."
2086 :group 'org-priorities
2087 :type 'boolean)
2089 (defgroup org-time nil
2090 "Options concerning time stamps and deadlines in Org-mode."
2091 :tag "Org Time"
2092 :group 'org)
2094 (defcustom org-insert-labeled-timestamps-at-point nil
2095 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2096 When nil, these labeled time stamps are forces into the second line of an
2097 entry, just after the headline. When scheduling from the global TODO list,
2098 the time stamp will always be forced into the second line."
2099 :group 'org-time
2100 :type 'boolean)
2102 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2103 "Formats for `format-time-string' which are used for time stamps.
2104 It is not recommended to change this constant.")
2106 (defcustom org-time-stamp-rounding-minutes '(0 5)
2107 "Number of minutes to round time stamps to.
2108 These are two values, the first applies when first creating a time stamp.
2109 The second applies when changing it with the commands `S-up' and `S-down'.
2110 When changing the time stamp, this means that it will change in steps
2111 of N minutes, as given by the second value.
2113 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2114 numbers should be factors of 60, so for example 5, 10, 15.
2116 When this is larger than 1, you can still force an exact time-stamp by using
2117 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2118 and by using a prefix arg to `S-up/down' to specify the exact number
2119 of minutes to shift."
2120 :group 'org-time
2121 :get '(lambda (var) ; Make sure all entries have 5 elements
2122 (if (integerp (default-value var))
2123 (list (default-value var) 5)
2124 (default-value var)))
2125 :type '(list
2126 (integer :tag "when inserting times")
2127 (integer :tag "when modifying times")))
2129 ;; Normalize old customizations of this variable.
2130 (when (integerp org-time-stamp-rounding-minutes)
2131 (setq org-time-stamp-rounding-minutes
2132 (list org-time-stamp-rounding-minutes
2133 org-time-stamp-rounding-minutes)))
2135 (defcustom org-display-custom-times nil
2136 "Non-nil means, overlay custom formats over all time stamps.
2137 The formats are defined through the variable `org-time-stamp-custom-formats'.
2138 To turn this on on a per-file basis, insert anywhere in the file:
2139 #+STARTUP: customtime"
2140 :group 'org-time
2141 :set 'set-default
2142 :type 'sexp)
2143 (make-variable-buffer-local 'org-display-custom-times)
2145 (defcustom org-time-stamp-custom-formats
2146 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2147 "Custom formats for time stamps. See `format-time-string' for the syntax.
2148 These are overlayed over the default ISO format if the variable
2149 `org-display-custom-times' is set. Time like %H:%M should be at the
2150 end of the second format. The custom formats are also honored by export
2151 commands, if custom time display is turned on at the time of export."
2152 :group 'org-time
2153 :type 'sexp)
2155 (defun org-time-stamp-format (&optional long inactive)
2156 "Get the right format for a time string."
2157 (let ((f (if long (cdr org-time-stamp-formats)
2158 (car org-time-stamp-formats))))
2159 (if inactive
2160 (concat "[" (substring f 1 -1) "]")
2161 f)))
2163 (defcustom org-time-clocksum-format "%d:%02d"
2164 "The format string used when creating CLOCKSUM lines, or when
2165 org-mode generates a time duration."
2166 :group 'org-time
2167 :type 'string)
2169 (defcustom org-deadline-warning-days 14
2170 "No. of days before expiration during which a deadline becomes active.
2171 This variable governs the display in sparse trees and in the agenda.
2172 When 0 or negative, it means use this number (the absolute value of it)
2173 even if a deadline has a different individual lead time specified.
2175 Custom commands can set this variable in the options section."
2176 :group 'org-time
2177 :group 'org-agenda-daily/weekly
2178 :type 'integer)
2180 (defcustom org-read-date-prefer-future t
2181 "Non-nil means, assume future for incomplete date input from user.
2182 This affects the following situations:
2183 1. The user gives a day, but no month.
2184 For example, if today is the 15th, and you enter \"3\", Org-mode will
2185 read this as the third of *next* month. However, if you enter \"17\",
2186 it will be considered as *this* month.
2187 2. The user gives a month but not a year.
2188 For example, if it is april and you enter \"feb 2\", this will be read
2189 as feb 2, *next* year. \"May 5\", however, will be this year.
2191 Currently this does not work for ISO week specifications.
2193 When this option is nil, the current month and year will always be used
2194 as defaults."
2195 :group 'org-time
2196 :type 'boolean)
2198 (defcustom org-read-date-display-live t
2199 "Non-nil means, display current interpretation of date prompt live.
2200 This display will be in an overlay, in the minibuffer."
2201 :group 'org-time
2202 :type 'boolean)
2204 (defcustom org-read-date-popup-calendar t
2205 "Non-nil means, pop up a calendar when prompting for a date.
2206 In the calendar, the date can be selected with mouse-1. However, the
2207 minibuffer will also be active, and you can simply enter the date as well.
2208 When nil, only the minibuffer will be available."
2209 :group 'org-time
2210 :type 'boolean)
2211 (if (fboundp 'defvaralias)
2212 (defvaralias 'org-popup-calendar-for-date-prompt
2213 'org-read-date-popup-calendar))
2215 (defcustom org-read-date-minibuffer-setup-hook nil
2216 "Hook to be used to set up keys for the date/time interface.
2217 Add key definitions to `minibuffer-local-map', which will be a temporary
2218 copy."
2219 :group 'org-time
2220 :type 'hook)
2222 (defcustom org-extend-today-until 0
2223 "The hour when your day really ends. Must be an integer.
2224 This has influence for the following applications:
2225 - When switching the agenda to \"today\". It it is still earlier than
2226 the time given here, the day recognized as TODAY is actually yesterday.
2227 - When a date is read from the user and it is still before the time given
2228 here, the current date and time will be assumed to be yesterday, 23:59.
2229 Also, timestamps inserted in remember templates follow this rule.
2231 IMPORTANT: This is a feature whose implementation is and likely will
2232 remain incomplete. Really, it is only here because past midnight seems to
2233 be the favorite working time of John Wiegley :-)"
2234 :group 'org-time
2235 :type 'integer)
2237 (defcustom org-edit-timestamp-down-means-later nil
2238 "Non-nil means, S-down will increase the time in a time stamp.
2239 When nil, S-up will increase."
2240 :group 'org-time
2241 :type 'boolean)
2243 (defcustom org-calendar-follow-timestamp-change t
2244 "Non-nil means, make the calendar window follow timestamp changes.
2245 When a timestamp is modified and the calendar window is visible, it will be
2246 moved to the new date."
2247 :group 'org-time
2248 :type 'boolean)
2250 (defgroup org-tags nil
2251 "Options concerning tags in Org-mode."
2252 :tag "Org Tags"
2253 :group 'org)
2255 (defcustom org-tag-alist nil
2256 "List of tags allowed in Org-mode files.
2257 When this list is nil, Org-mode will base TAG input on what is already in the
2258 buffer.
2259 The value of this variable is an alist, the car of each entry must be a
2260 keyword as a string, the cdr may be a character that is used to select
2261 that tag through the fast-tag-selection interface.
2262 See the manual for details."
2263 :group 'org-tags
2264 :type '(repeat
2265 (choice
2266 (cons (string :tag "Tag name")
2267 (character :tag "Access char"))
2268 (const :tag "Start radio group" (:startgroup))
2269 (const :tag "End radio group" (:endgroup))
2270 (const :tag "New line" (:newline)))))
2272 (defcustom org-tag-persistent-alist nil
2273 "List of tags that will always appear in all Org-mode files.
2274 This is in addition to any in buffer settings or customizations
2275 of `org-tag-alist'.
2276 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2277 The value of this variable is an alist, the car of each entry must be a
2278 keyword as a string, the cdr may be a character that is used to select
2279 that tag through the fast-tag-selection interface.
2280 See the manual for details.
2281 To disable these tags on a per-file basis, insert anywhere in the file:
2282 #+STARTUP: noptag"
2283 :group 'org-tags
2284 :type '(repeat
2285 (choice
2286 (cons (string :tag "Tag name")
2287 (character :tag "Access char"))
2288 (const :tag "Start radio group" (:startgroup))
2289 (const :tag "End radio group" (:endgroup))
2290 (const :tag "New line" (:newline)))))
2292 (defvar org-file-tags nil
2293 "List of tags that can be inherited by all entries in the file.
2294 The tags will be inherited if the variable `org-use-tag-inheritance'
2295 says they should be.
2296 This variable is populated from #+TAG lines.")
2298 (defcustom org-use-fast-tag-selection 'auto
2299 "Non-nil means, use fast tag selection scheme.
2300 This is a special interface to select and deselect tags with single keys.
2301 When nil, fast selection is never used.
2302 When the symbol `auto', fast selection is used if and only if selection
2303 characters for tags have been configured, either through the variable
2304 `org-tag-alist' or through a #+TAGS line in the buffer.
2305 When t, fast selection is always used and selection keys are assigned
2306 automatically if necessary."
2307 :group 'org-tags
2308 :type '(choice
2309 (const :tag "Always" t)
2310 (const :tag "Never" nil)
2311 (const :tag "When selection characters are configured" 'auto)))
2313 (defcustom org-fast-tag-selection-single-key nil
2314 "Non-nil means, fast tag selection exits after first change.
2315 When nil, you have to press RET to exit it.
2316 During fast tag selection, you can toggle this flag with `C-c'.
2317 This variable can also have the value `expert'. In this case, the window
2318 displaying the tags menu is not even shown, until you press C-c again."
2319 :group 'org-tags
2320 :type '(choice
2321 (const :tag "No" nil)
2322 (const :tag "Yes" t)
2323 (const :tag "Expert" expert)))
2325 (defvar org-fast-tag-selection-include-todo nil
2326 "Non-nil means, fast tags selection interface will also offer TODO states.
2327 This is an undocumented feature, you should not rely on it.")
2329 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2330 "The column to which tags should be indented in a headline.
2331 If this number is positive, it specifies the column. If it is negative,
2332 it means that the tags should be flushright to that column. For example,
2333 -80 works well for a normal 80 character screen."
2334 :group 'org-tags
2335 :type 'integer)
2337 (defcustom org-auto-align-tags t
2338 "Non-nil means, realign tags after pro/demotion of TODO state change.
2339 These operations change the length of a headline and therefore shift
2340 the tags around. With this options turned on, after each such operation
2341 the tags are again aligned to `org-tags-column'."
2342 :group 'org-tags
2343 :type 'boolean)
2345 (defcustom org-use-tag-inheritance t
2346 "Non-nil means, tags in levels apply also for sublevels.
2347 When nil, only the tags directly given in a specific line apply there.
2348 This may also be a list of tags that should be inherited, or a regexp that
2349 matches tags that should be inherited. Additional control is possible
2350 with the variable `org-tags-exclude-from-inheritance' which gives an
2351 explicit list of tags to be excluded from inheritance., even if the value of
2352 `org-use-tag-inheritance' would select it for inheritance.
2354 If this option is t, a match early-on in a tree can lead to a large
2355 number of matches in the subtree when constructing the agenda or creating
2356 a sparse tree. If you only want to see the first match in a tree during
2357 a search, check out the variable `org-tags-match-list-sublevels'."
2358 :group 'org-tags
2359 :type '(choice
2360 (const :tag "Not" nil)
2361 (const :tag "Always" t)
2362 (repeat :tag "Specific tags" (string :tag "Tag"))
2363 (regexp :tag "Tags matched by regexp")))
2365 (defcustom org-tags-exclude-from-inheritance nil
2366 "List of tags that should never be inherited.
2367 This is a way to exclude a few tags from inheritance. For way to do
2368 the opposite, to actively allow inheritance for selected tags,
2369 see the variable `org-use-tag-inheritance'."
2370 :group 'org-tags
2371 :type '(repeat (string :tag "Tag")))
2373 (defun org-tag-inherit-p (tag)
2374 "Check if TAG is one that should be inherited."
2375 (cond
2376 ((member tag org-tags-exclude-from-inheritance) nil)
2377 ((eq org-use-tag-inheritance t) t)
2378 ((not org-use-tag-inheritance) nil)
2379 ((stringp org-use-tag-inheritance)
2380 (string-match org-use-tag-inheritance tag))
2381 ((listp org-use-tag-inheritance)
2382 (member tag org-use-tag-inheritance))
2383 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2385 (defcustom org-tags-match-list-sublevels t
2386 "Non-nil means list also sublevels of headlines matching a search.
2387 This variable applies to tags/property searches, and also to stuck
2388 projects because this search is based on a tags match as well.
2390 When set to the symbol `indented', sublevels are indented with
2391 leading dots.
2393 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2394 the sublevels of a headline matching a tag search often also match
2395 the same search. Listing all of them can create very long lists.
2396 Setting this variable to nil causes subtrees of a match to be skipped.
2398 This variable is semi-obsolete and probably should always be true. It
2399 is better to limit inheritance to certain tags using the variables
2400 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2401 :group 'org-tags
2402 :type '(choice
2403 (const :tag "No, don't list them" nil)
2404 (const :tag "Yes, do list them" t)
2405 (const :tag "List them, indented with leading dots" indented)))
2407 (defcustom org-tags-sort-function nil
2408 "When set, tags are sorted using this function as a comparator"
2409 :group 'org-tags
2410 :type '(choice
2411 (const :tag "No sorting" nil)
2412 (const :tag "Alphabetical" string<)
2413 (const :tag "Reverse alphabetical" string>)
2414 (function :tag "Custom function" nil)))
2416 (defvar org-tags-history nil
2417 "History of minibuffer reads for tags.")
2418 (defvar org-last-tags-completion-table nil
2419 "The last used completion table for tags.")
2420 (defvar org-after-tags-change-hook nil
2421 "Hook that is run after the tags in a line have changed.")
2423 (defgroup org-properties nil
2424 "Options concerning properties in Org-mode."
2425 :tag "Org Properties"
2426 :group 'org)
2428 (defcustom org-property-format "%-10s %s"
2429 "How property key/value pairs should be formatted by `indent-line'.
2430 When `indent-line' hits a property definition, it will format the line
2431 according to this format, mainly to make sure that the values are
2432 lined-up with respect to each other."
2433 :group 'org-properties
2434 :type 'string)
2436 (defcustom org-use-property-inheritance nil
2437 "Non-nil means, properties apply also for sublevels.
2439 This setting is chiefly used during property searches. Turning it on can
2440 cause significant overhead when doing a search, which is why it is not
2441 on by default.
2443 When nil, only the properties directly given in the current entry count.
2444 When t, every property is inherited. The value may also be a list of
2445 properties that should have inheritance, or a regular expression matching
2446 properties that should be inherited.
2448 However, note that some special properties use inheritance under special
2449 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2450 and the properties ending in \"_ALL\" when they are used as descriptor
2451 for valid values of a property.
2453 Note for programmers:
2454 When querying an entry with `org-entry-get', you can control if inheritance
2455 should be used. By default, `org-entry-get' looks only at the local
2456 properties. You can request inheritance by setting the inherit argument
2457 to t (to force inheritance) or to `selective' (to respect the setting
2458 in this variable)."
2459 :group 'org-properties
2460 :type '(choice
2461 (const :tag "Not" nil)
2462 (const :tag "Always" t)
2463 (repeat :tag "Specific properties" (string :tag "Property"))
2464 (regexp :tag "Properties matched by regexp")))
2466 (defun org-property-inherit-p (property)
2467 "Check if PROPERTY is one that should be inherited."
2468 (cond
2469 ((eq org-use-property-inheritance t) t)
2470 ((not org-use-property-inheritance) nil)
2471 ((stringp org-use-property-inheritance)
2472 (string-match org-use-property-inheritance property))
2473 ((listp org-use-property-inheritance)
2474 (member property org-use-property-inheritance))
2475 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2477 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2478 "The default column format, if no other format has been defined.
2479 This variable can be set on the per-file basis by inserting a line
2481 #+COLUMNS: %25ITEM ....."
2482 :group 'org-properties
2483 :type 'string)
2485 (defcustom org-columns-ellipses ".."
2486 "The ellipses to be used when a field in column view is truncated.
2487 When this is the empty string, as many characters as possible are shown,
2488 but then there will be no visual indication that the field has been truncated.
2489 When this is a string of length N, the last N characters of a truncated
2490 field are replaced by this string. If the column is narrower than the
2491 ellipses string, only part of the ellipses string will be shown."
2492 :group 'org-properties
2493 :type 'string)
2495 (defcustom org-columns-modify-value-for-display-function nil
2496 "Function that modifies values for display in column view.
2497 For example, it can be used to cut out a certain part from a time stamp.
2498 The function must take 2 arguments:
2500 column-title The title of the column (*not* the property name)
2501 value The value that should be modified.
2503 The function should return the value that should be displayed,
2504 or nil if the normal value should be used."
2505 :group 'org-properties
2506 :type 'function)
2508 (defcustom org-effort-property "Effort"
2509 "The property that is being used to keep track of effort estimates.
2510 Effort estimates given in this property need to have the format H:MM."
2511 :group 'org-properties
2512 :group 'org-progress
2513 :type '(string :tag "Property"))
2515 (defconst org-global-properties-fixed
2516 '(("VISIBILITY_ALL" . "folded children content all")
2517 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2518 "List of property/value pairs that can be inherited by any entry.
2520 These are fixed values, for the preset properties. The user variable
2521 that can be used to add to this list is `org-global-properties'.
2523 The entries in this list are cons cells where the car is a property
2524 name and cdr is a string with the value. If the value represents
2525 multiple items like an \"_ALL\" property, separate the items by
2526 spaces.")
2528 (defcustom org-global-properties nil
2529 "List of property/value pairs that can be inherited by any entry.
2531 This list will be combined with the constant `org-global-properties-fixed'.
2533 The entries in this list are cons cells where the car is a property
2534 name and cdr is a string with the value.
2536 You can set buffer-local values for the same purpose in the variable
2537 `org-file-properties' this by adding lines like
2539 #+PROPERTY: NAME VALUE"
2540 :group 'org-properties
2541 :type '(repeat
2542 (cons (string :tag "Property")
2543 (string :tag "Value"))))
2545 (defvar org-file-properties nil
2546 "List of property/value pairs that can be inherited by any entry.
2547 Valid for the current buffer.
2548 This variable is populated from #+PROPERTY lines.")
2549 (make-variable-buffer-local 'org-file-properties)
2551 (defgroup org-agenda nil
2552 "Options concerning agenda views in Org-mode."
2553 :tag "Org Agenda"
2554 :group 'org)
2556 (defvar org-category nil
2557 "Variable used by org files to set a category for agenda display.
2558 Such files should use a file variable to set it, for example
2560 # -*- mode: org; org-category: \"ELisp\"
2562 or contain a special line
2564 #+CATEGORY: ELisp
2566 If the file does not specify a category, then file's base name
2567 is used instead.")
2568 (make-variable-buffer-local 'org-category)
2569 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2571 (defcustom org-agenda-files nil
2572 "The files to be used for agenda display.
2573 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2574 \\[org-remove-file]. You can also use customize to edit the list.
2576 If an entry is a directory, all files in that directory that are matched by
2577 `org-agenda-file-regexp' will be part of the file list.
2579 If the value of the variable is not a list but a single file name, then
2580 the list of agenda files is actually stored and maintained in that file, one
2581 agenda file per line."
2582 :group 'org-agenda
2583 :type '(choice
2584 (repeat :tag "List of files and directories" file)
2585 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2587 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2588 "Regular expression to match files for `org-agenda-files'.
2589 If any element in the list in that variable contains a directory instead
2590 of a normal file, all files in that directory that are matched by this
2591 regular expression will be included."
2592 :group 'org-agenda
2593 :type 'regexp)
2595 (defcustom org-agenda-text-search-extra-files nil
2596 "List of extra files to be searched by text search commands.
2597 These files will be search in addition to the agenda files by the
2598 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2599 Note that these files will only be searched for text search commands,
2600 not for the other agenda views like todo lists, tag searches or the weekly
2601 agenda. This variable is intended to list notes and possibly archive files
2602 that should also be searched by these two commands.
2603 In fact, if the first element in the list is the symbol `agenda-archives',
2604 than all archive files of all agenda files will be added to the search
2605 scope."
2606 :group 'org-agenda
2607 :type '(set :greedy t
2608 (const :tag "Agenda Archives" agenda-archives)
2609 (repeat :inline t (file))))
2611 (if (fboundp 'defvaralias)
2612 (defvaralias 'org-agenda-multi-occur-extra-files
2613 'org-agenda-text-search-extra-files))
2615 (defcustom org-agenda-skip-unavailable-files nil
2616 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2617 A nil value means to remove them, after a query, from the list."
2618 :group 'org-agenda
2619 :type 'boolean)
2621 (defcustom org-calendar-to-agenda-key [?c]
2622 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2623 The command `org-calendar-goto-agenda' will be bound to this key. The
2624 default is the character `c' because then `c' can be used to switch back and
2625 forth between agenda and calendar."
2626 :group 'org-agenda
2627 :type 'sexp)
2629 (defcustom org-calendar-agenda-action-key [?k]
2630 "The key to be installed in `calendar-mode-map' for agenda-action.
2631 The command `org-agenda-action' will be bound to this key. The
2632 default is the character `k' because we use the same key in the agenda."
2633 :group 'org-agenda
2634 :type 'sexp)
2636 (eval-after-load "calendar"
2637 '(progn
2638 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2639 'org-calendar-goto-agenda)
2640 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2641 'org-agenda-action)))
2643 (defgroup org-latex nil
2644 "Options for embedding LaTeX code into Org-mode."
2645 :tag "Org LaTeX"
2646 :group 'org)
2648 (defcustom org-format-latex-options
2649 '(:foreground default :background default :scale 1.0
2650 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2651 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2652 "Options for creating images from LaTeX fragments.
2653 This is a property list with the following properties:
2654 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2655 `default' means use the foreground of the default face.
2656 :background the background color, or \"Transparent\".
2657 `default' means use the background of the default face.
2658 :scale a scaling factor for the size of the images.
2659 :html-foreground, :html-background, :html-scale
2660 the same numbers for HTML export.
2661 :matchers a list indicating which matchers should be used to
2662 find LaTeX fragments. Valid members of this list are:
2663 \"begin\" find environments
2664 \"$1\" find single characters surrounded by $.$
2665 \"$\" find math expressions surrounded by $...$
2666 \"$$\" find math expressions surrounded by $$....$$
2667 \"\\(\" find math expressions surrounded by \\(...\\)
2668 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2669 :group 'org-latex
2670 :type 'plist)
2672 (defcustom org-format-latex-header "\\documentclass{article}
2673 \\usepackage{fullpage} % do not remove
2674 \\usepackage{amssymb}
2675 \\usepackage[usenames]{color}
2676 \\usepackage{amsmath}
2677 \\usepackage{latexsym}
2678 \\usepackage[mathscr]{eucal}
2679 \\pagestyle{empty} % do not remove"
2680 "The document header used for processing LaTeX fragments."
2681 :group 'org-latex
2682 :type 'string)
2685 (defgroup org-font-lock nil
2686 "Font-lock settings for highlighting in Org-mode."
2687 :tag "Org Font Lock"
2688 :group 'org)
2690 (defcustom org-level-color-stars-only nil
2691 "Non-nil means fontify only the stars in each headline.
2692 When nil, the entire headline is fontified.
2693 Changing it requires restart of `font-lock-mode' to become effective
2694 also in regions already fontified."
2695 :group 'org-font-lock
2696 :type 'boolean)
2698 (defcustom org-hide-leading-stars nil
2699 "Non-nil means, hide the first N-1 stars in a headline.
2700 This works by using the face `org-hide' for these stars. This
2701 face is white for a light background, and black for a dark
2702 background. You may have to customize the face `org-hide' to
2703 make this work.
2704 Changing it requires restart of `font-lock-mode' to become effective
2705 also in regions already fontified.
2706 You may also set this on a per-file basis by adding one of the following
2707 lines to the buffer:
2709 #+STARTUP: hidestars
2710 #+STARTUP: showstars"
2711 :group 'org-font-lock
2712 :type 'boolean)
2714 (defcustom org-fontify-done-headline nil
2715 "Non-nil means, change the face of a headline if it is marked DONE.
2716 Normally, only the TODO/DONE keyword indicates the state of a headline.
2717 When this is non-nil, the headline after the keyword is set to the
2718 `org-headline-done' as an additional indication."
2719 :group 'org-font-lock
2720 :type 'boolean)
2722 (defcustom org-fontify-emphasized-text t
2723 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2724 Changing this variable requires a restart of Emacs to take effect."
2725 :group 'org-font-lock
2726 :type 'boolean)
2728 (defcustom org-fontify-whole-heading-line nil
2729 "Non-nil means fontify the whole line for headings.
2730 This is useful when setting a background color for the
2731 org-leve-* faces."
2732 :group 'org-font-lock
2733 :type 'boolean)
2735 (defcustom org-highlight-latex-fragments-and-specials nil
2736 "Non-nil means, fontify what is treated specially by the exporters."
2737 :group 'org-font-lock
2738 :type 'boolean)
2740 (defcustom org-hide-emphasis-markers nil
2741 "Non-nil mean font-lock should hide the emphasis marker characters."
2742 :group 'org-font-lock
2743 :type 'boolean)
2745 (defvar org-emph-re nil
2746 "Regular expression for matching emphasis.")
2747 (defvar org-verbatim-re nil
2748 "Regular expression for matching verbatim text.")
2749 (defvar org-emphasis-regexp-components) ; defined just below
2750 (defvar org-emphasis-alist) ; defined just below
2751 (defun org-set-emph-re (var val)
2752 "Set variable and compute the emphasis regular expression."
2753 (set var val)
2754 (when (and (boundp 'org-emphasis-alist)
2755 (boundp 'org-emphasis-regexp-components)
2756 org-emphasis-alist org-emphasis-regexp-components)
2757 (let* ((e org-emphasis-regexp-components)
2758 (pre (car e))
2759 (post (nth 1 e))
2760 (border (nth 2 e))
2761 (body (nth 3 e))
2762 (nl (nth 4 e))
2763 (body1 (concat body "*?"))
2764 (markers (mapconcat 'car org-emphasis-alist ""))
2765 (vmarkers (mapconcat
2766 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2767 org-emphasis-alist "")))
2768 ;; make sure special characters appear at the right position in the class
2769 (if (string-match "\\^" markers)
2770 (setq markers (concat (replace-match "" t t markers) "^")))
2771 (if (string-match "-" markers)
2772 (setq markers (concat (replace-match "" t t markers) "-")))
2773 (if (string-match "\\^" vmarkers)
2774 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2775 (if (string-match "-" vmarkers)
2776 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2777 (if (> nl 0)
2778 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2779 (int-to-string nl) "\\}")))
2780 ;; Make the regexp
2781 (setq org-emph-re
2782 (concat "\\([" pre "]\\|^\\)"
2783 "\\("
2784 "\\([" markers "]\\)"
2785 "\\("
2786 "[^" border "]\\|"
2787 "[^" border "]"
2788 body1
2789 "[^" border "]"
2790 "\\)"
2791 "\\3\\)"
2792 "\\([" post "]\\|$\\)"))
2793 (setq org-verbatim-re
2794 (concat "\\([" pre "]\\|^\\)"
2795 "\\("
2796 "\\([" vmarkers "]\\)"
2797 "\\("
2798 "[^" border "]\\|"
2799 "[^" border "]"
2800 body1
2801 "[^" border "]"
2802 "\\)"
2803 "\\3\\)"
2804 "\\([" post "]\\|$\\)")))))
2806 (defcustom org-emphasis-regexp-components
2807 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2808 "Components used to build the regular expression for emphasis.
2809 This is a list with 6 entries. Terminology: In an emphasis string
2810 like \" *strong word* \", we call the initial space PREMATCH, the final
2811 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2812 and \"trong wor\" is the body. The different components in this variable
2813 specify what is allowed/forbidden in each part:
2815 pre Chars allowed as prematch. Beginning of line will be allowed too.
2816 post Chars allowed as postmatch. End of line will be allowed too.
2817 border The chars *forbidden* as border characters.
2818 body-regexp A regexp like \".\" to match a body character. Don't use
2819 non-shy groups here, and don't allow newline here.
2820 newline The maximum number of newlines allowed in an emphasis exp.
2822 Use customize to modify this, or restart Emacs after changing it."
2823 :group 'org-font-lock
2824 :set 'org-set-emph-re
2825 :type '(list
2826 (sexp :tag "Allowed chars in pre ")
2827 (sexp :tag "Allowed chars in post ")
2828 (sexp :tag "Forbidden chars in border ")
2829 (sexp :tag "Regexp for body ")
2830 (integer :tag "number of newlines allowed")
2831 (option (boolean :tag "Please ignore this button"))))
2833 (defcustom org-emphasis-alist
2834 `(("*" bold "<b>" "</b>")
2835 ("/" italic "<i>" "</i>")
2836 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2837 ("=" org-code "<code>" "</code>" verbatim)
2838 ("~" org-verbatim "<code>" "</code>" verbatim)
2839 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2840 "<del>" "</del>")
2842 "Special syntax for emphasized text.
2843 Text starting and ending with a special character will be emphasized, for
2844 example *bold*, _underlined_ and /italic/. This variable sets the marker
2845 characters, the face to be used by font-lock for highlighting in Org-mode
2846 Emacs buffers, and the HTML tags to be used for this.
2847 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2848 Use customize to modify this, or restart Emacs after changing it."
2849 :group 'org-font-lock
2850 :set 'org-set-emph-re
2851 :type '(repeat
2852 (list
2853 (string :tag "Marker character")
2854 (choice
2855 (face :tag "Font-lock-face")
2856 (plist :tag "Face property list"))
2857 (string :tag "HTML start tag")
2858 (string :tag "HTML end tag")
2859 (option (const verbatim)))))
2861 (defvar org-protecting-blocks
2862 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2863 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2864 This is needed for font-lock setup.")
2866 ;;; Miscellaneous options
2868 (defgroup org-completion nil
2869 "Completion in Org-mode."
2870 :tag "Org Completion"
2871 :group 'org)
2873 (defcustom org-completion-use-ido nil
2874 "Non-nil means, use ido completion wherever possible.
2875 Note that `ido-mode' must be active for this variable to be relevant.
2876 If you decide to turn this variable on, you might well want to turn off
2877 `org-outline-path-complete-in-steps'.
2878 See also `org-completion-use-iswitchb'."
2879 :group 'org-completion
2880 :type 'boolean)
2882 (defcustom org-completion-use-iswitchb nil
2883 "Non-nil means, use iswitchb completion wherever possible.
2884 Note that `iswitchb-mode' must be active for this variable to be relevant.
2885 If you decide to turn this variable on, you might well want to turn off
2886 `org-outline-path-complete-in-steps'.
2887 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
2888 :group 'org-completion
2889 :type 'boolean)
2891 (defcustom org-completion-fallback-command 'hippie-expand
2892 "The expansion command called by \\[org-complete] in normal context.
2893 Normal means, no org-mode-specific context."
2894 :group 'org-completion
2895 :type 'function)
2897 ;;; Functions and variables from ther packages
2898 ;; Declared here to avoid compiler warnings
2900 ;; XEmacs only
2901 (defvar outline-mode-menu-heading)
2902 (defvar outline-mode-menu-show)
2903 (defvar outline-mode-menu-hide)
2904 (defvar zmacs-regions) ; XEmacs regions
2906 ;; Emacs only
2907 (defvar mark-active)
2909 ;; Various packages
2910 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2911 (declare-function calendar-forward-day "cal-move" (arg))
2912 (declare-function calendar-goto-date "cal-move" (date))
2913 (declare-function calendar-goto-today "cal-move" ())
2914 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2915 (defvar calc-embedded-close-formula)
2916 (defvar calc-embedded-open-formula)
2917 (declare-function cdlatex-tab "ext:cdlatex" ())
2918 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2919 (defvar font-lock-unfontify-region-function)
2920 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2921 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2922 (defvar iswitchb-temp-buflist)
2923 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2924 (defvar org-agenda-tags-todo-honor-ignore-options)
2925 (declare-function org-agenda-skip "org-agenda" ())
2926 (declare-function org-format-agenda-item "org-agenda"
2927 (extra txt &optional category tags dotime noprefix remove-re))
2928 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2929 (declare-function org-agenda-change-all-lines "org-agenda"
2930 (newhead hdmarker &optional fixface just-this))
2931 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2932 (declare-function org-agenda-maybe-redo "org-agenda" ())
2933 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2934 (beg end))
2935 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2936 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2937 "org-agenda" (&optional end))
2938 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
2939 (declare-function org-indent-mode "org-indent" (arg))
2940 (declare-function parse-time-string "parse-time" (string))
2941 (declare-function remember "remember" (&optional initial))
2942 (declare-function remember-buffer-desc "remember" ())
2943 (declare-function remember-finalize "remember" ())
2944 (defvar remember-save-after-remembering)
2945 (defvar remember-data-file)
2946 (defvar remember-register)
2947 (defvar remember-buffer)
2948 (defvar remember-handler-functions)
2949 (defvar remember-annotation-functions)
2950 (defvar texmathp-why)
2951 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2952 (declare-function table--at-cell-p "table" (position &optional object at-column))
2954 (defvar w3m-current-url)
2955 (defvar w3m-current-title)
2957 (defvar org-latex-regexps)
2959 ;;; Autoload and prepare some org modules
2961 ;; Some table stuff that needs to be defined here, because it is used
2962 ;; by the functions setting up org-mode or checking for table context.
2964 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2965 "Detects an org-type or table-type table.")
2966 (defconst org-table-line-regexp "^[ \t]*|"
2967 "Detects an org-type table line.")
2968 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2969 "Detects an org-type table line.")
2970 (defconst org-table-hline-regexp "^[ \t]*|-"
2971 "Detects an org-type table hline.")
2972 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2973 "Detects a table-type table hline.")
2974 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2975 "Searching from within a table (any type) this finds the first line
2976 outside the table.")
2978 ;; Autoload the functions in org-table.el that are needed by functions here.
2980 (eval-and-compile
2981 (org-autoload "org-table"
2982 '(org-table-align org-table-begin org-table-blank-field
2983 org-table-convert org-table-convert-region org-table-copy-down
2984 org-table-copy-region org-table-create
2985 org-table-create-or-convert-from-region
2986 org-table-create-with-table.el org-table-current-dline
2987 org-table-cut-region org-table-delete-column org-table-edit-field
2988 org-table-edit-formulas org-table-end org-table-eval-formula
2989 org-table-export org-table-field-info
2990 org-table-get-stored-formulas org-table-goto-column
2991 org-table-hline-and-move org-table-import org-table-insert-column
2992 org-table-insert-hline org-table-insert-row org-table-iterate
2993 org-table-justify-field-maybe org-table-kill-row
2994 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2995 org-table-move-column org-table-move-column-left
2996 org-table-move-column-right org-table-move-row
2997 org-table-move-row-down org-table-move-row-up
2998 org-table-next-field org-table-next-row org-table-paste-rectangle
2999 org-table-previous-field org-table-recalculate
3000 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3001 org-table-toggle-coordinate-overlays
3002 org-table-toggle-formula-debugger org-table-wrap-region
3003 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3005 (defun org-at-table-p (&optional table-type)
3006 "Return t if the cursor is inside an org-type table.
3007 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3008 (if org-enable-table-editor
3009 (save-excursion
3010 (beginning-of-line 1)
3011 (looking-at (if table-type org-table-any-line-regexp
3012 org-table-line-regexp)))
3013 nil))
3014 (defsubst org-table-p () (org-at-table-p))
3016 (defun org-at-table.el-p ()
3017 "Return t if and only if we are at a table.el table."
3018 (and (org-at-table-p 'any)
3019 (save-excursion
3020 (goto-char (org-table-begin 'any))
3021 (looking-at org-table1-hline-regexp))))
3022 (defun org-table-recognize-table.el ()
3023 "If there is a table.el table nearby, recognize it and move into it."
3024 (if org-table-tab-recognizes-table.el
3025 (if (org-at-table.el-p)
3026 (progn
3027 (beginning-of-line 1)
3028 (if (looking-at org-table-dataline-regexp)
3030 (if (looking-at org-table1-hline-regexp)
3031 (progn
3032 (beginning-of-line 2)
3033 (if (looking-at org-table-any-border-regexp)
3034 (beginning-of-line -1)))))
3035 (if (re-search-forward "|" (org-table-end t) t)
3036 (progn
3037 (require 'table)
3038 (if (table--at-cell-p (point))
3040 (message "recognizing table.el table...")
3041 (table-recognize-table)
3042 (message "recognizing table.el table...done")))
3043 (error "This should not happen..."))
3045 nil)
3046 nil))
3048 (defun org-at-table-hline-p ()
3049 "Return t if the cursor is inside a hline in a table."
3050 (if org-enable-table-editor
3051 (save-excursion
3052 (beginning-of-line 1)
3053 (looking-at org-table-hline-regexp))
3054 nil))
3056 (defvar org-table-clean-did-remove-column nil)
3058 (defun org-table-map-tables (function)
3059 "Apply FUNCTION to the start of all tables in the buffer."
3060 (save-excursion
3061 (save-restriction
3062 (widen)
3063 (goto-char (point-min))
3064 (while (re-search-forward org-table-any-line-regexp nil t)
3065 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3066 (beginning-of-line 1)
3067 (when (looking-at org-table-line-regexp)
3068 (save-excursion (funcall function))
3069 (or (looking-at org-table-line-regexp)
3070 (forward-char 1)))
3071 (re-search-forward org-table-any-border-regexp nil 1))))
3072 (message "Mapping tables: done"))
3074 ;; Declare and autoload functions from org-exp.el & Co
3076 (declare-function org-default-export-plist "org-exp")
3077 (declare-function org-infile-export-plist "org-exp")
3078 (declare-function org-get-current-options "org-exp")
3079 (eval-and-compile
3080 (org-autoload "org-exp"
3081 '(org-export org-export-visible
3082 org-insert-export-options-template
3083 org-table-clean-before-export))
3084 (org-autoload "org-ascii"
3085 '(org-export-as-ascii org-export-ascii-preprocess
3086 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3087 org-export-region-as-ascii))
3088 (org-autoload "org-html"
3089 '(org-export-as-html-and-open
3090 org-export-as-html-batch org-export-as-html-to-buffer
3091 org-replace-region-by-html org-export-region-as-html
3092 org-export-as-html))
3093 (org-autoload "org-icalendar"
3094 '(org-export-icalendar-this-file
3095 org-export-icalendar-all-agenda-files
3096 org-export-icalendar-combine-agenda-files))
3097 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3099 ;; Declare and autoload functions from org-agenda.el
3101 (eval-and-compile
3102 (org-autoload "org-agenda"
3103 '(org-agenda org-agenda-list org-search-view
3104 org-todo-list org-tags-view org-agenda-list-stuck-projects
3105 org-diary org-agenda-to-appt
3106 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3108 ;; Autoload org-remember
3110 (eval-and-compile
3111 (org-autoload "org-remember"
3112 '(org-remember-insinuate org-remember-annotation
3113 org-remember-apply-template org-remember org-remember-handler)))
3115 ;; Autoload org-clock.el
3118 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3119 (beg end))
3120 (declare-function org-clock-update-mode-line "org-clock" ())
3121 (defvar org-clock-start-time)
3122 (defvar org-clock-marker (make-marker)
3123 "Marker recording the last clock-in.")
3124 (defvar org-clock-hd-marker (make-marker)
3125 "Marker recording the last clock-in, but the headline position.")
3126 (defun org-clock-is-active ()
3127 "Return non-nil if clock is currently running.
3128 The return value is actually the clock marker."
3129 (marker-buffer org-clock-marker))
3131 (eval-and-compile
3132 (org-autoload
3133 "org-clock"
3134 '(org-clock-in org-clock-out org-clock-cancel
3135 org-clock-goto org-clock-sum org-clock-display
3136 org-clock-remove-overlays org-clock-report
3137 org-clocktable-shift org-dblock-write:clocktable
3138 org-get-clocktable)))
3140 (defun org-clock-update-time-maybe ()
3141 "If this is a CLOCK line, update it and return t.
3142 Otherwise, return nil."
3143 (interactive)
3144 (save-excursion
3145 (beginning-of-line 1)
3146 (skip-chars-forward " \t")
3147 (when (looking-at org-clock-string)
3148 (let ((re (concat "[ \t]*" org-clock-string
3149 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3150 "\\([ \t]*=>.*\\)?\\)?"))
3151 ts te h m s neg)
3152 (cond
3153 ((not (looking-at re))
3154 nil)
3155 ((not (match-end 2))
3156 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3157 (> org-clock-marker (point))
3158 (<= org-clock-marker (point-at-eol)))
3159 ;; The clock is running here
3160 (setq org-clock-start-time
3161 (apply 'encode-time
3162 (org-parse-time-string (match-string 1))))
3163 (org-clock-update-mode-line)))
3165 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3166 (end-of-line 1)
3167 (setq ts (match-string 1)
3168 te (match-string 3))
3169 (setq s (- (time-to-seconds
3170 (apply 'encode-time (org-parse-time-string te)))
3171 (time-to-seconds
3172 (apply 'encode-time (org-parse-time-string ts))))
3173 neg (< s 0)
3174 s (abs s)
3175 h (floor (/ s 3600))
3176 s (- s (* 3600 h))
3177 m (floor (/ s 60))
3178 s (- s (* 60 s)))
3179 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3180 t))))))
3182 (defun org-check-running-clock ()
3183 "Check if the current buffer contains the running clock.
3184 If yes, offer to stop it and to save the buffer with the changes."
3185 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3186 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3187 (buffer-name))))
3188 (org-clock-out)
3189 (when (y-or-n-p "Save changed buffer?")
3190 (save-buffer))))
3192 (defun org-clocktable-try-shift (dir n)
3193 "Check if this line starts a clock table, if yes, shift the time block."
3194 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3195 (org-clocktable-shift dir n)))
3197 ;; Autoload org-timer.el
3199 (eval-and-compile
3200 (org-autoload
3201 "org-timer"
3202 '(org-timer-start org-timer org-timer-item
3203 org-timer-change-times-in-region
3204 org-timer-set-timer
3205 org-timer-reset-timers
3206 org-timer-show-remaining-time)))
3208 ;; Autoload org-feed.el
3210 (eval-and-compile
3211 (org-autoload
3212 "org-feed"
3213 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3216 ;; Autoload org-indent.el
3218 (eval-and-compile
3219 (org-autoload
3220 "org-indent"
3221 '(org-indent-mode)))
3223 ;; Autoload archiving code
3224 ;; The stuff that is needed for cycling and tags has to be defined here.
3226 (defgroup org-archive nil
3227 "Options concerning archiving in Org-mode."
3228 :tag "Org Archive"
3229 :group 'org-structure)
3231 (defcustom org-archive-location "%s_archive::"
3232 "The location where subtrees should be archived.
3234 The value of this variable is a string, consisting of two parts,
3235 separated by a double-colon. The first part is a filename and
3236 the second part is a headline.
3238 When the filename is omitted, archiving happens in the same file.
3239 %s in the filename will be replaced by the current file
3240 name (without the directory part). Archiving to a different file
3241 is useful to keep archived entries from contributing to the
3242 Org-mode Agenda.
3244 The archived entries will be filed as subtrees of the specified
3245 headline. When the headline is omitted, the subtrees are simply
3246 filed away at the end of the file, as top-level entries. Also in
3247 the heading you can use %s to represent the file name, this can be
3248 useful when using the same archive for a number of different files.
3250 Here are a few examples:
3251 \"%s_archive::\"
3252 If the current file is Projects.org, archive in file
3253 Projects.org_archive, as top-level trees. This is the default.
3255 \"::* Archived Tasks\"
3256 Archive in the current file, under the top-level headline
3257 \"* Archived Tasks\".
3259 \"~/org/archive.org::\"
3260 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3262 \"~/org/archive.org::From %s\"
3263 Archive in file ~/org/archive.org (absolute path), und headlines
3264 \"From FILENAME\" where file name is the current file name.
3266 \"basement::** Finished Tasks\"
3267 Archive in file ./basement (relative path), as level 3 trees
3268 below the level 2 heading \"** Finished Tasks\".
3270 You may set this option on a per-file basis by adding to the buffer a
3271 line like
3273 #+ARCHIVE: basement::** Finished Tasks
3275 You may also define it locally for a subtree by setting an ARCHIVE property
3276 in the entry. If such a property is found in an entry, or anywhere up
3277 the hierarchy, it will be used."
3278 :group 'org-archive
3279 :type 'string)
3281 (defcustom org-archive-tag "ARCHIVE"
3282 "The tag that marks a subtree as archived.
3283 An archived subtree does not open during visibility cycling, and does
3284 not contribute to the agenda listings.
3285 After changing this, font-lock must be restarted in the relevant buffers to
3286 get the proper fontification."
3287 :group 'org-archive
3288 :group 'org-keywords
3289 :type 'string)
3291 (defcustom org-agenda-skip-archived-trees t
3292 "Non-nil means, the agenda will skip any items located in archived trees.
3293 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3294 variable is no longer recommended, you should leave it at the value t.
3295 Instead, use the key `v' to cycle the archives-mode in the agenda."
3296 :group 'org-archive
3297 :group 'org-agenda-skip
3298 :type 'boolean)
3300 (defcustom org-columns-skip-arrchived-trees t
3301 "Non-nil means, irgnore archived trees when creating column view."
3302 :group 'org-archive
3303 :group 'org-properties
3304 :type 'boolean)
3306 (defcustom org-cycle-open-archived-trees nil
3307 "Non-nil means, `org-cycle' will open archived trees.
3308 An archived tree is a tree marked with the tag ARCHIVE.
3309 When nil, archived trees will stay folded. You can still open them with
3310 normal outline commands like `show-all', but not with the cycling commands."
3311 :group 'org-archive
3312 :group 'org-cycle
3313 :type 'boolean)
3315 (defcustom org-sparse-tree-open-archived-trees nil
3316 "Non-nil means sparse tree construction shows matches in archived trees.
3317 When nil, matches in these trees are highlighted, but the trees are kept in
3318 collapsed state."
3319 :group 'org-archive
3320 :group 'org-sparse-trees
3321 :type 'boolean)
3323 (defun org-cycle-hide-archived-subtrees (state)
3324 "Re-hide all archived subtrees after a visibility state change."
3325 (when (and (not org-cycle-open-archived-trees)
3326 (not (memq state '(overview folded))))
3327 (save-excursion
3328 (let* ((globalp (memq state '(contents all)))
3329 (beg (if globalp (point-min) (point)))
3330 (end (if globalp (point-max) (org-end-of-subtree t))))
3331 (org-hide-archived-subtrees beg end)
3332 (goto-char beg)
3333 (if (looking-at (concat ".*:" org-archive-tag ":"))
3334 (message "%s" (substitute-command-keys
3335 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3337 (defun org-force-cycle-archived ()
3338 "Cycle subtree even if it is archived."
3339 (interactive)
3340 (setq this-command 'org-cycle)
3341 (let ((org-cycle-open-archived-trees t))
3342 (call-interactively 'org-cycle)))
3344 (defun org-hide-archived-subtrees (beg end)
3345 "Re-hide all archived subtrees after a visibility state change."
3346 (save-excursion
3347 (let* ((re (concat ":" org-archive-tag ":")))
3348 (goto-char beg)
3349 (while (re-search-forward re end t)
3350 (and (org-on-heading-p) (hide-subtree))
3351 (org-end-of-subtree t)))))
3353 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3355 (eval-and-compile
3356 (org-autoload "org-archive"
3357 '(org-add-archive-files org-archive-subtree
3358 org-archive-to-archive-sibling org-toggle-archive-tag)))
3360 ;; Autoload Column View Code
3362 (declare-function org-columns-number-to-string "org-colview")
3363 (declare-function org-columns-get-format-and-top-level "org-colview")
3364 (declare-function org-columns-compute "org-colview")
3366 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3367 '(org-columns-number-to-string org-columns-get-format-and-top-level
3368 org-columns-compute org-agenda-columns org-columns-remove-overlays
3369 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3371 ;; Autoload ID code
3373 (declare-function org-id-store-link "org-id")
3374 (declare-function org-id-locations-load "org-id")
3375 (declare-function org-id-locations-save "org-id")
3376 (defvar org-id-track-globally)
3377 (org-autoload "org-id"
3378 '(org-id-get-create org-id-new org-id-copy org-id-get
3379 org-id-get-with-outline-path-completion
3380 org-id-get-with-outline-drilling
3381 org-id-goto org-id-find org-id-store-link))
3383 ;; Autoload Plotting Code
3385 (org-autoload "org-plot"
3386 '(org-plot/gnuplot))
3388 ;;; Variables for pre-computed regular expressions, all buffer local
3390 (defvar org-drawer-regexp nil
3391 "Matches first line of a hidden block.")
3392 (make-variable-buffer-local 'org-drawer-regexp)
3393 (defvar org-todo-regexp nil
3394 "Matches any of the TODO state keywords.")
3395 (make-variable-buffer-local 'org-todo-regexp)
3396 (defvar org-not-done-regexp nil
3397 "Matches any of the TODO state keywords except the last one.")
3398 (make-variable-buffer-local 'org-not-done-regexp)
3399 (defvar org-not-done-heading-regexp nil
3400 "Matches a TODO headline that is not done.")
3401 (make-variable-buffer-local 'org-not-done-regexp)
3402 (defvar org-todo-line-regexp nil
3403 "Matches a headline and puts TODO state into group 2 if present.")
3404 (make-variable-buffer-local 'org-todo-line-regexp)
3405 (defvar org-complex-heading-regexp nil
3406 "Matches a headline and puts everything into groups:
3407 group 1: the stars
3408 group 2: The todo keyword, maybe
3409 group 3: Priority cookie
3410 group 4: True headline
3411 group 5: Tags")
3412 (make-variable-buffer-local 'org-complex-heading-regexp)
3413 (defvar org-todo-line-tags-regexp nil
3414 "Matches a headline and puts TODO state into group 2 if present.
3415 Also put tags into group 4 if tags are present.")
3416 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3417 (defvar org-nl-done-regexp nil
3418 "Matches newline followed by a headline with the DONE keyword.")
3419 (make-variable-buffer-local 'org-nl-done-regexp)
3420 (defvar org-looking-at-done-regexp nil
3421 "Matches the DONE keyword a point.")
3422 (make-variable-buffer-local 'org-looking-at-done-regexp)
3423 (defvar org-ds-keyword-length 12
3424 "Maximum length of the Deadline and SCHEDULED keywords.")
3425 (make-variable-buffer-local 'org-ds-keyword-length)
3426 (defvar org-deadline-regexp nil
3427 "Matches the DEADLINE keyword.")
3428 (make-variable-buffer-local 'org-deadline-regexp)
3429 (defvar org-deadline-time-regexp nil
3430 "Matches the DEADLINE keyword together with a time stamp.")
3431 (make-variable-buffer-local 'org-deadline-time-regexp)
3432 (defvar org-deadline-line-regexp nil
3433 "Matches the DEADLINE keyword and the rest of the line.")
3434 (make-variable-buffer-local 'org-deadline-line-regexp)
3435 (defvar org-scheduled-regexp nil
3436 "Matches the SCHEDULED keyword.")
3437 (make-variable-buffer-local 'org-scheduled-regexp)
3438 (defvar org-scheduled-time-regexp nil
3439 "Matches the SCHEDULED keyword together with a time stamp.")
3440 (make-variable-buffer-local 'org-scheduled-time-regexp)
3441 (defvar org-closed-time-regexp nil
3442 "Matches the CLOSED keyword together with a time stamp.")
3443 (make-variable-buffer-local 'org-closed-time-regexp)
3445 (defvar org-keyword-time-regexp nil
3446 "Matches any of the 4 keywords, together with the time stamp.")
3447 (make-variable-buffer-local 'org-keyword-time-regexp)
3448 (defvar org-keyword-time-not-clock-regexp nil
3449 "Matches any of the 3 keywords, together with the time stamp.")
3450 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3451 (defvar org-maybe-keyword-time-regexp nil
3452 "Matches a timestamp, possibly preceeded by a keyword.")
3453 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3454 (defvar org-planning-or-clock-line-re nil
3455 "Matches a line with planning or clock info.")
3456 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3458 (defconst org-plain-time-of-day-regexp
3459 (concat
3460 "\\(\\<[012]?[0-9]"
3461 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3462 "\\(--?"
3463 "\\(\\<[012]?[0-9]"
3464 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3465 "\\)?")
3466 "Regular expression to match a plain time or time range.
3467 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3468 groups carry important information:
3469 0 the full match
3470 1 the first time, range or not
3471 8 the second time, if it is a range.")
3473 (defconst org-plain-time-extension-regexp
3474 (concat
3475 "\\(\\<[012]?[0-9]"
3476 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3477 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3478 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3479 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3480 groups carry important information:
3481 0 the full match
3482 7 hours of duration
3483 9 minutes of duration")
3485 (defconst org-stamp-time-of-day-regexp
3486 (concat
3487 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3488 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3489 "\\(--?"
3490 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3491 "Regular expression to match a timestamp time or time range.
3492 After a match, the following groups carry important information:
3493 0 the full match
3494 1 date plus weekday, for backreferencing to make sure both times on same day
3495 2 the first time, range or not
3496 4 the second time, if it is a range.")
3498 (defconst org-startup-options
3499 '(("fold" org-startup-folded t)
3500 ("overview" org-startup-folded t)
3501 ("nofold" org-startup-folded nil)
3502 ("showall" org-startup-folded nil)
3503 ("content" org-startup-folded content)
3504 ("indent" org-startup-indented t)
3505 ("noindent" org-startup-indented nil)
3506 ("hidestars" org-hide-leading-stars t)
3507 ("showstars" org-hide-leading-stars nil)
3508 ("odd" org-odd-levels-only t)
3509 ("oddeven" org-odd-levels-only nil)
3510 ("align" org-startup-align-all-tables t)
3511 ("noalign" org-startup-align-all-tables nil)
3512 ("customtime" org-display-custom-times t)
3513 ("logdone" org-log-done time)
3514 ("lognotedone" org-log-done note)
3515 ("nologdone" org-log-done nil)
3516 ("lognoteclock-out" org-log-note-clock-out t)
3517 ("nolognoteclock-out" org-log-note-clock-out nil)
3518 ("logrepeat" org-log-repeat state)
3519 ("lognoterepeat" org-log-repeat note)
3520 ("nologrepeat" org-log-repeat nil)
3521 ("fninline" org-footnote-define-inline t)
3522 ("nofninline" org-footnote-define-inline nil)
3523 ("fnlocal" org-footnote-section nil)
3524 ("fnauto" org-footnote-auto-label t)
3525 ("fnprompt" org-footnote-auto-label nil)
3526 ("fnconfirm" org-footnote-auto-label confirm)
3527 ("fnplain" org-footnote-auto-label plain)
3528 ("fnadjust" org-footnote-auto-adjust t)
3529 ("nofnadjust" org-footnote-auto-adjust nil)
3530 ("constcgs" constants-unit-system cgs)
3531 ("constSI" constants-unit-system SI)
3532 ("noptag" org-tag-persistent-alist nil)
3533 ("hideblocks" org-hide-block-startup t)
3534 ("nohideblocks" org-hide-block-startup nil))
3535 "Variable associated with STARTUP options for org-mode.
3536 Each element is a list of three items: The startup options as written
3537 in the #+STARTUP line, the corresponding variable, and the value to
3538 set this variable to if the option is found. An optional forth element PUSH
3539 means to push this value onto the list in the variable.")
3541 (defun org-set-regexps-and-options ()
3542 "Precompute regular expressions for current buffer."
3543 (when (org-mode-p)
3544 (org-set-local 'org-todo-kwd-alist nil)
3545 (org-set-local 'org-todo-key-alist nil)
3546 (org-set-local 'org-todo-key-trigger nil)
3547 (org-set-local 'org-todo-keywords-1 nil)
3548 (org-set-local 'org-done-keywords nil)
3549 (org-set-local 'org-todo-heads nil)
3550 (org-set-local 'org-todo-sets nil)
3551 (org-set-local 'org-todo-log-states nil)
3552 (org-set-local 'org-file-properties nil)
3553 (org-set-local 'org-file-tags nil)
3554 (let ((re (org-make-options-regexp
3555 '("CATEGORY" "TODO" "COLUMNS"
3556 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3557 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3558 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3559 (splitre "[ \t]+")
3560 kwds kws0 kwsa key log value cat arch tags const links hw dws
3561 tail sep kws1 prio props ftags drawers
3562 ext-setup-or-nil setup-contents (start 0))
3563 (save-excursion
3564 (save-restriction
3565 (widen)
3566 (goto-char (point-min))
3567 (while (or (and ext-setup-or-nil
3568 (string-match re ext-setup-or-nil start)
3569 (setq start (match-end 0)))
3570 (and (setq ext-setup-or-nil nil start 0)
3571 (re-search-forward re nil t)))
3572 (setq key (upcase (match-string 1 ext-setup-or-nil))
3573 value (org-match-string-no-properties 2 ext-setup-or-nil))
3574 (cond
3575 ((equal key "CATEGORY")
3576 (if (string-match "[ \t]+$" value)
3577 (setq value (replace-match "" t t value)))
3578 (setq cat value))
3579 ((member key '("SEQ_TODO" "TODO"))
3580 (push (cons 'sequence (org-split-string value splitre)) kwds))
3581 ((equal key "TYP_TODO")
3582 (push (cons 'type (org-split-string value splitre)) kwds))
3583 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3584 ;; general TODO-like setup
3585 (push (cons (intern (downcase (match-string 1 key)))
3586 (org-split-string value splitre)) kwds))
3587 ((equal key "TAGS")
3588 (setq tags (append tags (if tags '("\\n") nil)
3589 (org-split-string value splitre))))
3590 ((equal key "COLUMNS")
3591 (org-set-local 'org-columns-default-format value))
3592 ((equal key "LINK")
3593 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3594 (push (cons (match-string 1 value)
3595 (org-trim (match-string 2 value)))
3596 links)))
3597 ((equal key "PRIORITIES")
3598 (setq prio (org-split-string value " +")))
3599 ((equal key "PROPERTY")
3600 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3601 (push (cons (match-string 1 value) (match-string 2 value))
3602 props)))
3603 ((equal key "FILETAGS")
3604 (when (string-match "\\S-" value)
3605 (setq ftags
3606 (append
3607 ftags
3608 (apply 'append
3609 (mapcar (lambda (x) (org-split-string x ":"))
3610 (org-split-string value)))))))
3611 ((equal key "DRAWERS")
3612 (setq drawers (org-split-string value splitre)))
3613 ((equal key "CONSTANTS")
3614 (setq const (append const (org-split-string value splitre))))
3615 ((equal key "STARTUP")
3616 (let ((opts (org-split-string value splitre))
3617 l var val)
3618 (while (setq l (pop opts))
3619 (when (setq l (assoc l org-startup-options))
3620 (setq var (nth 1 l) val (nth 2 l))
3621 (if (not (nth 3 l))
3622 (set (make-local-variable var) val)
3623 (if (not (listp (symbol-value var)))
3624 (set (make-local-variable var) nil))
3625 (set (make-local-variable var) (symbol-value var))
3626 (add-to-list var val))))))
3627 ((equal key "ARCHIVE")
3628 (string-match " *$" value)
3629 (setq arch (replace-match "" t t value))
3630 (remove-text-properties 0 (length arch)
3631 '(face t fontified t) arch))
3632 ((equal key "SETUPFILE")
3633 (setq setup-contents (org-file-contents
3634 (expand-file-name
3635 (org-remove-double-quotes value))
3636 'noerror))
3637 (if (not ext-setup-or-nil)
3638 (setq ext-setup-or-nil setup-contents start 0)
3639 (setq ext-setup-or-nil
3640 (concat (substring ext-setup-or-nil 0 start)
3641 "\n" setup-contents "\n"
3642 (substring ext-setup-or-nil start)))))
3643 ))))
3644 (when cat
3645 (org-set-local 'org-category (intern cat))
3646 (push (cons "CATEGORY" cat) props))
3647 (when prio
3648 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3649 (setq prio (mapcar 'string-to-char prio))
3650 (org-set-local 'org-highest-priority (nth 0 prio))
3651 (org-set-local 'org-lowest-priority (nth 1 prio))
3652 (org-set-local 'org-default-priority (nth 2 prio)))
3653 (and props (org-set-local 'org-file-properties (nreverse props)))
3654 (and ftags (org-set-local 'org-file-tags
3655 (mapcar 'org-add-prop-inherited ftags)))
3656 (and drawers (org-set-local 'org-drawers drawers))
3657 (and arch (org-set-local 'org-archive-location arch))
3658 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3659 ;; Process the TODO keywords
3660 (unless kwds
3661 ;; Use the global values as if they had been given locally.
3662 (setq kwds (default-value 'org-todo-keywords))
3663 (if (stringp (car kwds))
3664 (setq kwds (list (cons org-todo-interpretation
3665 (default-value 'org-todo-keywords)))))
3666 (setq kwds (reverse kwds)))
3667 (setq kwds (nreverse kwds))
3668 (let (inter kws kw)
3669 (while (setq kws (pop kwds))
3670 (let ((kws (or
3671 (run-hook-with-args-until-success
3672 'org-todo-setup-filter-hook kws)
3673 kws)))
3674 (setq inter (pop kws) sep (member "|" kws)
3675 kws0 (delete "|" (copy-sequence kws))
3676 kwsa nil
3677 kws1 (mapcar
3678 (lambda (x)
3679 ;; 1 2
3680 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3681 (progn
3682 (setq kw (match-string 1 x)
3683 key (and (match-end 2) (match-string 2 x))
3684 log (org-extract-log-state-settings x))
3685 (push (cons kw (and key (string-to-char key))) kwsa)
3686 (and log (push log org-todo-log-states))
3688 (error "Invalid TODO keyword %s" x)))
3689 kws0)
3690 kwsa (if kwsa (append '((:startgroup))
3691 (nreverse kwsa)
3692 '((:endgroup))))
3693 hw (car kws1)
3694 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3695 tail (list inter hw (car dws) (org-last dws))))
3696 (add-to-list 'org-todo-heads hw 'append)
3697 (push kws1 org-todo-sets)
3698 (setq org-done-keywords (append org-done-keywords dws nil))
3699 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3700 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3701 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3702 (setq org-todo-sets (nreverse org-todo-sets)
3703 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3704 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3705 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3706 ;; Process the constants
3707 (when const
3708 (let (e cst)
3709 (while (setq e (pop const))
3710 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3711 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3712 (setq org-table-formula-constants-local cst)))
3714 ;; Process the tags.
3715 (when tags
3716 (let (e tgs)
3717 (while (setq e (pop tags))
3718 (cond
3719 ((equal e "{") (push '(:startgroup) tgs))
3720 ((equal e "}") (push '(:endgroup) tgs))
3721 ((equal e "\\n") (push '(:newline) tgs))
3722 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3723 (push (cons (match-string 1 e)
3724 (string-to-char (match-string 2 e)))
3725 tgs))
3726 (t (push (list e) tgs))))
3727 (org-set-local 'org-tag-alist nil)
3728 (while (setq e (pop tgs))
3729 (or (and (stringp (car e))
3730 (assoc (car e) org-tag-alist))
3731 (push e org-tag-alist)))))
3733 ;; Compute the regular expressions and other local variables
3734 (if (not org-done-keywords)
3735 (setq org-done-keywords (and org-todo-keywords-1
3736 (list (org-last org-todo-keywords-1)))))
3737 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3738 (length org-scheduled-string)
3739 (length org-clock-string)
3740 (length org-closed-string)))
3741 org-drawer-regexp
3742 (concat "^[ \t]*:\\("
3743 (mapconcat 'regexp-quote org-drawers "\\|")
3744 "\\):[ \t]*$")
3745 org-not-done-keywords
3746 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3747 org-todo-regexp
3748 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3749 "\\|") "\\)\\>")
3750 org-not-done-regexp
3751 (concat "\\<\\("
3752 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3753 "\\)\\>")
3754 org-not-done-heading-regexp
3755 (concat "^\\(\\*+\\)[ \t]+\\("
3756 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3757 "\\)\\>")
3758 org-todo-line-regexp
3759 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3760 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3761 "\\)\\>\\)?[ \t]*\\(.*\\)")
3762 org-complex-heading-regexp
3763 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3764 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3765 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3766 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3767 org-nl-done-regexp
3768 (concat "\n\\*+[ \t]+"
3769 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3770 "\\)" "\\>")
3771 org-todo-line-tags-regexp
3772 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3773 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3774 (org-re
3775 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3776 org-looking-at-done-regexp
3777 (concat "^" "\\(?:"
3778 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3779 "\\>")
3780 org-deadline-regexp (concat "\\<" org-deadline-string)
3781 org-deadline-time-regexp
3782 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3783 org-deadline-line-regexp
3784 (concat "\\<\\(" org-deadline-string "\\).*")
3785 org-scheduled-regexp
3786 (concat "\\<" org-scheduled-string)
3787 org-scheduled-time-regexp
3788 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3789 org-closed-time-regexp
3790 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3791 org-keyword-time-regexp
3792 (concat "\\<\\(" org-scheduled-string
3793 "\\|" org-deadline-string
3794 "\\|" org-closed-string
3795 "\\|" org-clock-string "\\)"
3796 " *[[<]\\([^]>]+\\)[]>]")
3797 org-keyword-time-not-clock-regexp
3798 (concat "\\<\\(" org-scheduled-string
3799 "\\|" org-deadline-string
3800 "\\|" org-closed-string
3801 "\\)"
3802 " *[[<]\\([^]>]+\\)[]>]")
3803 org-maybe-keyword-time-regexp
3804 (concat "\\(\\<\\(" org-scheduled-string
3805 "\\|" org-deadline-string
3806 "\\|" org-closed-string
3807 "\\|" org-clock-string "\\)\\)?"
3808 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3809 org-planning-or-clock-line-re
3810 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3811 "\\|" org-deadline-string
3812 "\\|" org-closed-string "\\|" org-clock-string
3813 "\\)\\>\\)")
3815 (org-compute-latex-and-specials-regexp)
3816 (org-set-font-lock-defaults))))
3818 (defun org-file-contents (file &optional noerror)
3819 "Return the contents of FILE, as a string."
3820 (if (or (not file)
3821 (not (file-readable-p file)))
3822 (if noerror
3823 (progn
3824 (message "Cannot read file %s" file)
3825 (ding) (sit-for 2)
3827 (error "Cannot read file %s" file))
3828 (with-temp-buffer
3829 (insert-file-contents file)
3830 (buffer-string))))
3832 (defun org-extract-log-state-settings (x)
3833 "Extract the log state setting from a TODO keyword string.
3834 This will extract info from a string like \"WAIT(w@/!)\"."
3835 (let (kw key log1 log2)
3836 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3837 (setq kw (match-string 1 x)
3838 key (and (match-end 2) (match-string 2 x))
3839 log1 (and (match-end 3) (match-string 3 x))
3840 log2 (and (match-end 4) (match-string 4 x)))
3841 (and (or log1 log2)
3842 (list kw
3843 (and log1 (if (equal log1 "!") 'time 'note))
3844 (and log2 (if (equal log2 "!") 'time 'note)))))))
3846 (defun org-remove-keyword-keys (list)
3847 "Remove a pair of parenthesis at the end of each string in LIST."
3848 (mapcar (lambda (x)
3849 (if (string-match "(.*)$" x)
3850 (substring x 0 (match-beginning 0))
3852 list))
3854 ;; FIXME: this could be done much better, using second characters etc.
3855 (defun org-assign-fast-keys (alist)
3856 "Assign fast keys to a keyword-key alist.
3857 Respect keys that are already there."
3858 (let (new e k c c1 c2 (char ?a))
3859 (while (setq e (pop alist))
3860 (cond
3861 ((equal e '(:startgroup)) (push e new))
3862 ((equal e '(:endgroup)) (push e new))
3863 ((equal e '(:newline)) (push e new))
3865 (setq k (car e) c2 nil)
3866 (if (cdr e)
3867 (setq c (cdr e))
3868 ;; automatically assign a character.
3869 (setq c1 (string-to-char
3870 (downcase (substring
3871 k (if (= (string-to-char k) ?@) 1 0)))))
3872 (if (or (rassoc c1 new) (rassoc c1 alist))
3873 (while (or (rassoc char new) (rassoc char alist))
3874 (setq char (1+ char)))
3875 (setq c2 c1))
3876 (setq c (or c2 char)))
3877 (push (cons k c) new))))
3878 (nreverse new)))
3880 ;;; Some variables used in various places
3882 (defvar org-window-configuration nil
3883 "Used in various places to store a window configuration.")
3884 (defvar org-finish-function nil
3885 "Function to be called when `C-c C-c' is used.
3886 This is for getting out of special buffers like remember.")
3889 ;; FIXME: Occasionally check by commenting these, to make sure
3890 ;; no other functions uses these, forgetting to let-bind them.
3891 (defvar entry)
3892 (defvar last-state)
3893 (defvar date)
3895 ;; Defined somewhere in this file, but used before definition.
3896 (defvar org-html-entities)
3897 (defvar org-struct-menu)
3898 (defvar org-org-menu)
3899 (defvar org-tbl-menu)
3900 (defvar org-agenda-keymap)
3902 ;;;; Define the Org-mode
3904 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3905 (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."))
3908 ;; We use a before-change function to check if a table might need
3909 ;; an update.
3910 (defvar org-table-may-need-update t
3911 "Indicates that a table might need an update.
3912 This variable is set by `org-before-change-function'.
3913 `org-table-align' sets it back to nil.")
3914 (defun org-before-change-function (beg end)
3915 "Every change indicates that a table might need an update."
3916 (setq org-table-may-need-update t))
3917 (defvar org-mode-map)
3918 (defvar org-mode-hook nil
3919 "Mode hook for Org-mode, run after the mode was turned on.")
3920 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3921 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3922 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3923 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3924 (defvar org-table-buffer-is-an nil)
3925 (defconst org-outline-regexp "\\*+ ")
3927 ;;;###autoload
3928 (define-derived-mode org-mode outline-mode "Org"
3929 "Outline-based notes management and organizer, alias
3930 \"Carsten's outline-mode for keeping track of everything.\"
3932 Org-mode develops organizational tasks around a NOTES file which
3933 contains information about projects as plain text. Org-mode is
3934 implemented on top of outline-mode, which is ideal to keep the content
3935 of large files well structured. It supports ToDo items, deadlines and
3936 time stamps, which magically appear in the diary listing of the Emacs
3937 calendar. Tables are easily created with a built-in table editor.
3938 Plain text URL-like links connect to websites, emails (VM), Usenet
3939 messages (Gnus), BBDB entries, and any files related to the project.
3940 For printing and sharing of notes, an Org-mode file (or a part of it)
3941 can be exported as a structured ASCII or HTML file.
3943 The following commands are available:
3945 \\{org-mode-map}"
3947 ;; Get rid of Outline menus, they are not needed
3948 ;; Need to do this here because define-derived-mode sets up
3949 ;; the keymap so late. Still, it is a waste to call this each time
3950 ;; we switch another buffer into org-mode.
3951 (if (featurep 'xemacs)
3952 (when (boundp 'outline-mode-menu-heading)
3953 ;; Assume this is Greg's port, it used easymenu
3954 (easy-menu-remove outline-mode-menu-heading)
3955 (easy-menu-remove outline-mode-menu-show)
3956 (easy-menu-remove outline-mode-menu-hide))
3957 (define-key org-mode-map [menu-bar headings] 'undefined)
3958 (define-key org-mode-map [menu-bar hide] 'undefined)
3959 (define-key org-mode-map [menu-bar show] 'undefined))
3961 (org-load-modules-maybe)
3962 (easy-menu-add org-org-menu)
3963 (easy-menu-add org-tbl-menu)
3964 (org-install-agenda-files-menu)
3965 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3966 (org-add-to-invisibility-spec '(org-cwidth))
3967 (org-add-to-invisibility-spec '(org-hide-block . t))
3968 (when (featurep 'xemacs)
3969 (org-set-local 'line-move-ignore-invisible t))
3970 (org-set-local 'outline-regexp org-outline-regexp)
3971 (org-set-local 'outline-level 'org-outline-level)
3972 (when (and org-ellipsis
3973 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3974 (fboundp 'make-glyph-code))
3975 (unless org-display-table
3976 (setq org-display-table (make-display-table)))
3977 (set-display-table-slot
3978 org-display-table 4
3979 (vconcat (mapcar
3980 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3981 org-ellipsis)))
3982 (if (stringp org-ellipsis) org-ellipsis "..."))))
3983 (setq buffer-display-table org-display-table))
3984 (org-set-regexps-and-options)
3985 (when (and org-tag-faces (not org-tags-special-faces-re))
3986 ;; tag faces set outside customize.... force initialization.
3987 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3988 ;; Calc embedded
3989 (org-set-local 'calc-embedded-open-mode "# ")
3990 (modify-syntax-entry ?# "<")
3991 (modify-syntax-entry ?@ "w")
3992 (if org-startup-truncated (setq truncate-lines t))
3993 (org-set-local 'font-lock-unfontify-region-function
3994 'org-unfontify-region)
3995 ;; Activate before-change-function
3996 (org-set-local 'org-table-may-need-update t)
3997 (org-add-hook 'before-change-functions 'org-before-change-function nil
3998 'local)
3999 ;; Check for running clock before killing a buffer
4000 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4001 ;; Paragraphs and auto-filling
4002 (org-set-autofill-regexps)
4003 (setq indent-line-function 'org-indent-line-function)
4004 (org-update-radio-target-regexp)
4005 ;; Make sure dependence stuff works reliably, even for users who set it
4006 ;; too late :-(
4007 (if org-enforce-todo-dependencies
4008 (add-hook 'org-blocker-hook
4009 'org-block-todo-from-children-or-siblings-or-parent)
4010 (remove-hook 'org-blocker-hook
4011 'org-block-todo-from-children-or-siblings-or-parent))
4012 (if org-enforce-todo-checkbox-dependencies
4013 (add-hook 'org-blocker-hook
4014 'org-block-todo-from-checkboxes)
4015 (remove-hook 'org-blocker-hook
4016 'org-block-todo-from-checkboxes))
4018 ;; Comment characters
4019 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4020 (org-set-local 'comment-padding " ")
4022 ;; Align options lines
4023 (org-set-local
4024 'align-mode-rules-list
4025 '((org-in-buffer-settings
4026 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4027 (modes . '(org-mode)))))
4029 ;; Imenu
4030 (org-set-local 'imenu-create-index-function
4031 'org-imenu-get-tree)
4033 ;; Make isearch reveal context
4034 (if (or (featurep 'xemacs)
4035 (not (boundp 'outline-isearch-open-invisible-function)))
4036 ;; Emacs 21 and XEmacs make use of the hook
4037 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4038 ;; Emacs 22 deals with this through a special variable
4039 (org-set-local 'outline-isearch-open-invisible-function
4040 (lambda (&rest ignore) (org-show-context 'isearch))))
4042 ;; If empty file that did not turn on org-mode automatically, make it to.
4043 (if (and org-insert-mode-line-in-empty-file
4044 (interactive-p)
4045 (= (point-min) (point-max)))
4046 (insert "# -*- mode: org -*-\n\n"))
4048 (unless org-inhibit-startup
4049 (when org-startup-align-all-tables
4050 (let ((bmp (buffer-modified-p)))
4051 (org-table-map-tables 'org-table-align)
4052 (set-buffer-modified-p bmp)))
4053 (when org-startup-indented
4054 (require 'org-indent)
4055 (org-indent-mode 1))
4056 (org-set-startup-visibility)))
4058 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4060 (defun org-current-time ()
4061 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4062 (if (> (car org-time-stamp-rounding-minutes) 1)
4063 (let ((r (car org-time-stamp-rounding-minutes))
4064 (time (decode-time)))
4065 (apply 'encode-time
4066 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4067 (nthcdr 2 time))))
4068 (current-time)))
4070 ;;;; Font-Lock stuff, including the activators
4072 (defvar org-mouse-map (make-sparse-keymap))
4073 (org-defkey org-mouse-map
4074 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4075 (org-defkey org-mouse-map
4076 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4077 (when org-mouse-1-follows-link
4078 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4079 (when org-tab-follows-link
4080 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4081 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4083 (require 'font-lock)
4085 (defconst org-non-link-chars "]\t\n\r<>")
4086 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4087 "shell" "elisp"))
4088 (defvar org-link-types-re nil
4089 "Matches a link that has a url-like prefix like \"http:\"")
4090 (defvar org-link-re-with-space nil
4091 "Matches a link with spaces, optional angular brackets around it.")
4092 (defvar org-link-re-with-space2 nil
4093 "Matches a link with spaces, optional angular brackets around it.")
4094 (defvar org-link-re-with-space3 nil
4095 "Matches a link with spaces, only for internal part in bracket links.")
4096 (defvar org-angle-link-re nil
4097 "Matches link with angular brackets, spaces are allowed.")
4098 (defvar org-plain-link-re nil
4099 "Matches plain link, without spaces.")
4100 (defvar org-bracket-link-regexp nil
4101 "Matches a link in double brackets.")
4102 (defvar org-bracket-link-analytic-regexp nil
4103 "Regular expression used to analyze links.
4104 Here is what the match groups contain after a match:
4105 1: http:
4106 2: http
4107 3: path
4108 4: [desc]
4109 5: desc")
4110 (defvar org-bracket-link-analytic-regexp++ nil
4111 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4112 (defvar org-any-link-re nil
4113 "Regular expression matching any link.")
4115 (defun org-make-link-regexps ()
4116 "Update the link regular expressions.
4117 This should be called after the variable `org-link-types' has changed."
4118 (setq org-link-types-re
4119 (concat
4120 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4121 org-link-re-with-space
4122 (concat
4123 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4124 "\\([^" org-non-link-chars " ]"
4125 "[^" org-non-link-chars "]*"
4126 "[^" org-non-link-chars " ]\\)>?")
4127 org-link-re-with-space2
4128 (concat
4129 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4130 "\\([^" org-non-link-chars " ]"
4131 "[^\t\n\r]*"
4132 "[^" org-non-link-chars " ]\\)>?")
4133 org-link-re-with-space3
4134 (concat
4135 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4136 "\\([^" org-non-link-chars " ]"
4137 "[^\t\n\r]*\\)")
4138 org-angle-link-re
4139 (concat
4140 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4141 "\\([^" org-non-link-chars " ]"
4142 "[^" org-non-link-chars "]*"
4143 "\\)>")
4144 org-plain-link-re
4145 (concat
4146 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4147 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4148 org-bracket-link-regexp
4149 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4150 org-bracket-link-analytic-regexp
4151 (concat
4152 "\\[\\["
4153 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4154 "\\([^]]+\\)"
4155 "\\]"
4156 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4157 "\\]")
4158 org-bracket-link-analytic-regexp++
4159 (concat
4160 "\\[\\["
4161 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4162 "\\([^]]+\\)"
4163 "\\]"
4164 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4165 "\\]")
4166 org-any-link-re
4167 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4168 org-angle-link-re "\\)\\|\\("
4169 org-plain-link-re "\\)")))
4171 (org-make-link-regexps)
4173 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4174 "Regular expression for fast time stamp matching.")
4175 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4176 "Regular expression for fast time stamp matching.")
4177 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4178 "Regular expression matching time strings for analysis.
4179 This one does not require the space after the date, so it can be used
4180 on a string that terminates immediately after the date.")
4181 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4182 "Regular expression matching time strings for analysis.")
4183 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4184 "Regular expression matching time stamps, with groups.")
4185 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4186 "Regular expression matching time stamps (also [..]), with groups.")
4187 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4188 "Regular expression matching a time stamp range.")
4189 (defconst org-tr-regexp-both
4190 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4191 "Regular expression matching a time stamp range.")
4192 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4193 org-ts-regexp "\\)?")
4194 "Regular expression matching a time stamp or time stamp range.")
4195 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4196 org-ts-regexp-both "\\)?")
4197 "Regular expression matching a time stamp or time stamp range.
4198 The time stamps may be either active or inactive.")
4200 (defvar org-emph-face nil)
4202 (defun org-do-emphasis-faces (limit)
4203 "Run through the buffer and add overlays to links."
4204 (let (rtn a)
4205 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4206 (if (not (= (char-after (match-beginning 3))
4207 (char-after (match-beginning 4))))
4208 (progn
4209 (setq rtn t)
4210 (setq a (assoc (match-string 3) org-emphasis-alist))
4211 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4212 'face
4213 (nth 1 a))
4214 (and (nth 4 a)
4215 (org-remove-flyspell-overlays-in
4216 (match-beginning 0) (match-end 0)))
4217 (add-text-properties (match-beginning 2) (match-end 2)
4218 '(font-lock-multiline t))
4219 (when org-hide-emphasis-markers
4220 (add-text-properties (match-end 4) (match-beginning 5)
4221 '(invisible org-link))
4222 (add-text-properties (match-beginning 3) (match-end 3)
4223 '(invisible org-link)))))
4224 (backward-char 1))
4225 rtn))
4227 (defun org-emphasize (&optional char)
4228 "Insert or change an emphasis, i.e. a font like bold or italic.
4229 If there is an active region, change that region to a new emphasis.
4230 If there is no region, just insert the marker characters and position
4231 the cursor between them.
4232 CHAR should be either the marker character, or the first character of the
4233 HTML tag associated with that emphasis. If CHAR is a space, the means
4234 to remove the emphasis of the selected region.
4235 If char is not given (for example in an interactive call) it
4236 will be prompted for."
4237 (interactive)
4238 (let ((eal org-emphasis-alist) e det
4239 (erc org-emphasis-regexp-components)
4240 (prompt "")
4241 (string "") beg end move tag c s)
4242 (if (org-region-active-p)
4243 (setq beg (region-beginning) end (region-end)
4244 string (buffer-substring beg end))
4245 (setq move t))
4247 (while (setq e (pop eal))
4248 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4249 c (aref tag 0))
4250 (push (cons c (string-to-char (car e))) det)
4251 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4252 (substring tag 1)))))
4253 (setq det (nreverse det))
4254 (unless char
4255 (message "%s" (concat "Emphasis marker or tag:" prompt))
4256 (setq char (read-char-exclusive)))
4257 (setq char (or (cdr (assoc char det)) char))
4258 (if (equal char ?\ )
4259 (setq s "" move nil)
4260 (unless (assoc (char-to-string char) org-emphasis-alist)
4261 (error "No such emphasis marker: \"%c\"" char))
4262 (setq s (char-to-string char)))
4263 (while (and (> (length string) 1)
4264 (equal (substring string 0 1) (substring string -1))
4265 (assoc (substring string 0 1) org-emphasis-alist))
4266 (setq string (substring string 1 -1)))
4267 (setq string (concat s string s))
4268 (if beg (delete-region beg end))
4269 (unless (or (bolp)
4270 (string-match (concat "[" (nth 0 erc) "\n]")
4271 (char-to-string (char-before (point)))))
4272 (insert " "))
4273 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4274 (char-to-string (char-after (point))))
4275 (insert " ") (backward-char 1))
4276 (insert string)
4277 (and move (backward-char 1))))
4279 (defconst org-nonsticky-props
4280 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4282 (defsubst org-rear-nonsticky-at (pos)
4283 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4285 (defun org-activate-plain-links (limit)
4286 "Run through the buffer and add overlays to links."
4287 (catch 'exit
4288 (let (f)
4289 (if (re-search-forward org-plain-link-re limit t)
4290 (progn
4291 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4292 (setq f (get-text-property (match-beginning 0) 'face))
4293 (if (or (eq f 'org-tag)
4294 (and (listp f) (memq 'org-tag f)))
4296 (add-text-properties (match-beginning 0) (match-end 0)
4297 (list 'mouse-face 'highlight
4298 'keymap org-mouse-map))
4299 (org-rear-nonsticky-at (match-end 0)))
4300 t)))))
4302 (defun org-activate-code (limit)
4303 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4304 (progn
4305 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4306 (remove-text-properties (match-beginning 0) (match-end 0)
4307 '(display t invisible t intangible t))
4308 t)))
4310 (defun org-fontify-meta-lines-and-blocks (limit)
4311 "Fontify #+ lines and blocks, in the correct ways."
4312 (let ((case-fold-search t))
4313 (if (re-search-forward
4314 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4315 limit t)
4316 (let ((beg (match-beginning 0))
4317 (beg1 (line-beginning-position 2))
4318 (dc1 (downcase (match-string 2)))
4319 (dc3 (downcase (match-string 3)))
4320 end end1 quoting)
4321 (cond
4322 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4323 ;; a single line of backend-specific content
4324 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4325 (remove-text-properties (match-beginning 0) (match-end 0)
4326 '(display t invisible t intangible t))
4327 (add-text-properties (match-beginning 1) (match-end 3)
4328 '(font-lock-fontified t face org-meta-line))
4329 (add-text-properties (match-beginning 6) (match-end 6)
4330 '(font-lock-fontified t face org-block))
4332 ((and (match-end 4) (equal dc3 "begin"))
4333 ;; Truely a block
4334 (setq quoting (member (downcase (match-string 5))
4335 org-protecting-blocks))
4336 (when (re-search-forward
4337 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4338 nil t) ;; on purpose, we look further than LIMIT
4339 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4340 (when quoting
4341 (remove-text-properties beg end
4342 '(display t invisible t intangible t)))
4343 (add-text-properties
4344 beg end
4345 '(font-lock-fontified t font-lock-multiline t))
4346 (add-text-properties beg beg1 '(face org-meta-line))
4347 (add-text-properties end1 end '(face org-meta-line))
4348 (when quoting
4349 (add-text-properties beg1 end1 '(face org-block)))
4351 ((not (member (char-after beg) '(?\ ?\t)))
4352 ;; just any other in-buffer setting, but not indented
4353 (add-text-properties
4354 beg (match-end 0)
4355 '(font-lock-fontified t face org-meta-line))
4357 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:" "tblname:"))
4358 (and (match-end 4) (equal dc3 "attr")))
4359 (add-text-properties
4360 beg (match-end 0)
4361 '(font-lock-fontified t face org-meta-line))
4363 (t nil))))))
4365 (defun org-activate-angle-links (limit)
4366 "Run through the buffer and add overlays to links."
4367 (if (re-search-forward org-angle-link-re limit t)
4368 (progn
4369 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4370 (add-text-properties (match-beginning 0) (match-end 0)
4371 (list 'mouse-face 'highlight
4372 'keymap org-mouse-map))
4373 (org-rear-nonsticky-at (match-end 0))
4374 t)))
4376 (defun org-activate-footnote-links (limit)
4377 "Run through the buffer and add overlays to links."
4378 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4379 limit t)
4380 (progn
4381 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4382 (add-text-properties (match-beginning 2) (match-end 2)
4383 (list 'mouse-face 'highlight
4384 'keymap org-mouse-map
4385 'help-echo
4386 (if (= (point-at-bol) (match-beginning 2))
4387 "Footnote definition"
4388 "Footnote reference")
4390 (org-rear-nonsticky-at (match-end 2))
4391 t)))
4393 (defun org-activate-bracket-links (limit)
4394 "Run through the buffer and add overlays to bracketed links."
4395 (if (re-search-forward org-bracket-link-regexp limit t)
4396 (let* ((help (concat "LINK: "
4397 (org-match-string-no-properties 1)))
4398 ;; FIXME: above we should remove the escapes.
4399 ;; but that requires another match, protecting match data,
4400 ;; a lot of overhead for font-lock.
4401 (ip (org-maybe-intangible
4402 (list 'invisible 'org-link
4403 'keymap org-mouse-map 'mouse-face 'highlight
4404 'font-lock-multiline t 'help-echo help)))
4405 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4406 'font-lock-multiline t 'help-echo help)))
4407 ;; We need to remove the invisible property here. Table narrowing
4408 ;; may have made some of this invisible.
4409 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4410 (remove-text-properties (match-beginning 0) (match-end 0)
4411 '(invisible nil))
4412 (if (match-end 3)
4413 (progn
4414 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4415 (org-rear-nonsticky-at (match-beginning 3))
4416 (add-text-properties (match-beginning 3) (match-end 3) vp)
4417 (org-rear-nonsticky-at (match-end 3))
4418 (add-text-properties (match-end 3) (match-end 0) ip)
4419 (org-rear-nonsticky-at (match-end 0)))
4420 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4421 (org-rear-nonsticky-at (match-beginning 1))
4422 (add-text-properties (match-beginning 1) (match-end 1) vp)
4423 (org-rear-nonsticky-at (match-end 1))
4424 (add-text-properties (match-end 1) (match-end 0) ip)
4425 (org-rear-nonsticky-at (match-end 0)))
4426 t)))
4428 (defun org-activate-dates (limit)
4429 "Run through the buffer and add overlays to dates."
4430 (if (re-search-forward org-tsr-regexp-both limit t)
4431 (progn
4432 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4433 (add-text-properties (match-beginning 0) (match-end 0)
4434 (list 'mouse-face 'highlight
4435 'keymap org-mouse-map))
4436 (org-rear-nonsticky-at (match-end 0))
4437 (when org-display-custom-times
4438 (if (match-end 3)
4439 (org-display-custom-time (match-beginning 3) (match-end 3)))
4440 (org-display-custom-time (match-beginning 1) (match-end 1)))
4441 t)))
4443 (defvar org-target-link-regexp nil
4444 "Regular expression matching radio targets in plain text.")
4445 (make-variable-buffer-local 'org-target-link-regexp)
4446 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4447 "Regular expression matching a link target.")
4448 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4449 "Regular expression matching a radio target.")
4450 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4451 "Regular expression matching any target.")
4453 (defun org-activate-target-links (limit)
4454 "Run through the buffer and add overlays to target matches."
4455 (when org-target-link-regexp
4456 (let ((case-fold-search t))
4457 (if (re-search-forward org-target-link-regexp limit t)
4458 (progn
4459 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4460 (add-text-properties (match-beginning 0) (match-end 0)
4461 (list 'mouse-face 'highlight
4462 'keymap org-mouse-map
4463 'help-echo "Radio target link"
4464 'org-linked-text t))
4465 (org-rear-nonsticky-at (match-end 0))
4466 t)))))
4468 (defun org-update-radio-target-regexp ()
4469 "Find all radio targets in this file and update the regular expression."
4470 (interactive)
4471 (when (memq 'radio org-activate-links)
4472 (setq org-target-link-regexp
4473 (org-make-target-link-regexp (org-all-targets 'radio)))
4474 (org-restart-font-lock)))
4476 (defun org-hide-wide-columns (limit)
4477 (let (s e)
4478 (setq s (text-property-any (point) (or limit (point-max))
4479 'org-cwidth t))
4480 (when s
4481 (setq e (next-single-property-change s 'org-cwidth))
4482 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4483 (goto-char e)
4484 t)))
4486 (defvar org-latex-and-specials-regexp nil
4487 "Regular expression for highlighting export special stuff.")
4488 (defvar org-match-substring-regexp)
4489 (defvar org-match-substring-with-braces-regexp)
4491 ;; This should be with the exporter code, but we also use if for font-locking
4492 (defconst org-export-html-special-string-regexps
4493 '(("\\\\-" . "&shy;")
4494 ("---\\([^-]\\)" . "&mdash;\\1")
4495 ("--\\([^-]\\)" . "&ndash;\\1")
4496 ("\\.\\.\\." . "&hellip;"))
4497 "Regular expressions for special string conversion.")
4500 (defun org-compute-latex-and-specials-regexp ()
4501 "Compute regular expression for stuff treated specially by exporters."
4502 (if (not org-highlight-latex-fragments-and-specials)
4503 (org-set-local 'org-latex-and-specials-regexp nil)
4504 (require 'org-exp)
4505 (let*
4506 ((matchers (plist-get org-format-latex-options :matchers))
4507 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4508 org-latex-regexps)))
4509 (options (org-combine-plists (org-default-export-plist)
4510 (org-infile-export-plist)))
4511 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4512 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4513 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4514 (org-export-html-expand (plist-get options :expand-quoted-html))
4515 (org-export-with-special-strings (plist-get options :special-strings))
4516 (re-sub
4517 (cond
4518 ((equal org-export-with-sub-superscripts '{})
4519 (list org-match-substring-with-braces-regexp))
4520 (org-export-with-sub-superscripts
4521 (list org-match-substring-regexp))
4522 (t nil)))
4523 (re-latex
4524 (if org-export-with-LaTeX-fragments
4525 (mapcar (lambda (x) (nth 1 x)) latexs)))
4526 (re-macros
4527 (if org-export-with-TeX-macros
4528 (list (concat "\\\\"
4529 (regexp-opt
4530 (append (mapcar 'car org-html-entities)
4531 (if (boundp 'org-latex-entities)
4532 (mapcar (lambda (x)
4533 (or (car-safe x) x))
4534 org-latex-entities)
4535 nil))
4536 'words))) ; FIXME
4538 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4539 (re-special (if org-export-with-special-strings
4540 (mapcar (lambda (x) (car x))
4541 org-export-html-special-string-regexps)))
4542 (re-rest
4543 (delq nil
4544 (list
4545 (if org-export-html-expand "@<[^>\n]+>")
4546 ))))
4547 (org-set-local
4548 'org-latex-and-specials-regexp
4549 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4550 re-rest) "\\|")))))
4552 (defun org-do-latex-and-special-faces (limit)
4553 "Run through the buffer and add overlays to links."
4554 (when org-latex-and-specials-regexp
4555 (let (rtn d)
4556 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4557 limit t))
4558 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4559 'face))
4560 '(org-code org-verbatim underline)))
4561 (progn
4562 (setq rtn t
4563 d (cond ((member (char-after (1+ (match-beginning 0)))
4564 '(?_ ?^)) 1)
4565 (t 0)))
4566 (font-lock-prepend-text-property
4567 (+ d (match-beginning 0)) (match-end 0)
4568 'face 'org-latex-and-export-specials)
4569 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4570 '(font-lock-multiline t)))))
4571 rtn)))
4573 (defun org-restart-font-lock ()
4574 "Restart font-lock-mode, to force refontification."
4575 (when (and (boundp 'font-lock-mode) font-lock-mode)
4576 (font-lock-mode -1)
4577 (font-lock-mode 1)))
4579 (defun org-all-targets (&optional radio)
4580 "Return a list of all targets in this file.
4581 With optional argument RADIO, only find radio targets."
4582 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4583 rtn)
4584 (save-excursion
4585 (goto-char (point-min))
4586 (while (re-search-forward re nil t)
4587 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4588 rtn)))
4590 (defun org-make-target-link-regexp (targets)
4591 "Make regular expression matching all strings in TARGETS.
4592 The regular expression finds the targets also if there is a line break
4593 between words."
4594 (and targets
4595 (concat
4596 "\\<\\("
4597 (mapconcat
4598 (lambda (x)
4599 (while (string-match " +" x)
4600 (setq x (replace-match "\\s-+" t t x)))
4602 targets
4603 "\\|")
4604 "\\)\\>")))
4606 (defun org-activate-tags (limit)
4607 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4608 (progn
4609 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4610 (add-text-properties (match-beginning 1) (match-end 1)
4611 (list 'mouse-face 'highlight
4612 'keymap org-mouse-map))
4613 (org-rear-nonsticky-at (match-end 1))
4614 t)))
4616 (defun org-outline-level ()
4617 (save-excursion
4618 (looking-at outline-regexp)
4619 (if (match-beginning 1)
4620 (+ (org-get-string-indentation (match-string 1)) 1000)
4621 (1- (- (match-end 0) (match-beginning 0))))))
4623 (defvar org-font-lock-keywords nil)
4625 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4626 "Regular expression matching a property line.")
4628 (defvar org-font-lock-hook nil
4629 "Functions to be called for special font lock stuff.")
4631 (defun org-font-lock-hook (limit)
4632 (run-hook-with-args 'org-font-lock-hook limit))
4634 (defun org-set-font-lock-defaults ()
4635 (let* ((em org-fontify-emphasized-text)
4636 (lk org-activate-links)
4637 (org-font-lock-extra-keywords
4638 (list
4639 ;; Call the hook
4640 '(org-font-lock-hook)
4641 ;; Headlines
4642 `(,(if org-fontify-whole-heading-line
4643 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4644 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4645 (1 (org-get-level-face 1))
4646 (2 (org-get-level-face 2))
4647 (3 (org-get-level-face 3)))
4648 ;; Table lines
4649 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4650 (1 'org-table t))
4651 ;; Table internals
4652 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4653 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4654 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4655 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4656 ;; Drawers
4657 (list org-drawer-regexp '(0 'org-special-keyword t))
4658 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4659 ;; Properties
4660 (list org-property-re
4661 '(1 'org-special-keyword t)
4662 '(3 'org-property-value t))
4663 ;; Links
4664 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4665 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4666 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4667 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4668 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4669 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4670 (if (memq 'footnote lk) '(org-activate-footnote-links
4671 (2 'org-footnote t)))
4672 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4673 '(org-hide-wide-columns (0 nil append))
4674 ;; TODO lines
4675 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4676 '(1 (org-get-todo-face 1) t))
4677 ;; DONE
4678 (if org-fontify-done-headline
4679 (list (concat "^[*]+ +\\<\\("
4680 (mapconcat 'regexp-quote org-done-keywords "\\|")
4681 "\\)\\(.*\\)")
4682 '(2 'org-headline-done t))
4683 nil)
4684 ;; Priorities
4685 '(org-font-lock-add-priority-faces)
4686 ;; Tags
4687 '(org-font-lock-add-tag-faces)
4688 ;; Special keywords
4689 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4690 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4691 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4692 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4693 ;; Emphasis
4694 (if em
4695 (if (featurep 'xemacs)
4696 '(org-do-emphasis-faces (0 nil append))
4697 '(org-do-emphasis-faces)))
4698 ;; Checkboxes
4699 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4700 2 'org-checkbox prepend)
4701 (if org-provide-checkbox-statistics
4702 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4703 (0 (org-get-checkbox-statistics-face) t)))
4704 ;; Description list items
4705 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4706 2 'bold prepend)
4707 ;; ARCHIVEd headings
4708 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4709 '(1 'org-archived prepend))
4710 ;; Specials
4711 '(org-do-latex-and-special-faces)
4712 ;; Code
4713 '(org-activate-code (1 'org-code t))
4714 ;; COMMENT
4715 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4716 "\\|" org-quote-string "\\)\\>")
4717 '(1 'org-special-keyword t))
4718 '("^#.*" (0 'font-lock-comment-face t))
4719 ;; Blocks and meta lines
4720 '(org-fontify-meta-lines-and-blocks)
4722 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4723 ;; Now set the full font-lock-keywords
4724 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4725 (org-set-local 'font-lock-defaults
4726 '(org-font-lock-keywords t nil nil backward-paragraph))
4727 (kill-local-variable 'font-lock-keywords) nil))
4729 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4730 "Fontify string S like in Org-mode"
4731 (with-temp-buffer
4732 (insert s)
4733 (let ((org-odd-levels-only odd-levels))
4734 (org-mode)
4735 (font-lock-fontify-buffer)
4736 (buffer-string))))
4738 (defvar org-m nil)
4739 (defvar org-l nil)
4740 (defvar org-f nil)
4741 (defun org-get-level-face (n)
4742 "Get the right face for match N in font-lock matching of headlines."
4743 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4744 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4745 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4746 (cond
4747 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4748 ((eq n 2) org-f)
4749 (t (if org-level-color-stars-only nil org-f))))
4751 (defun org-get-todo-face (kwd)
4752 "Get the right face for a TODO keyword KWD.
4753 If KWD is a number, get the corresponding match group."
4754 (if (numberp kwd) (setq kwd (match-string kwd)))
4755 (or (cdr (assoc kwd org-todo-keyword-faces))
4756 (and (member kwd org-done-keywords) 'org-done)
4757 'org-todo))
4759 (defun org-font-lock-add-tag-faces (limit)
4760 "Add the special tag faces."
4761 (when (and org-tag-faces org-tags-special-faces-re)
4762 (while (re-search-forward org-tags-special-faces-re limit t)
4763 (add-text-properties (match-beginning 1) (match-end 1)
4764 (list 'face (org-get-tag-face 1)
4765 'font-lock-fontified t))
4766 (backward-char 1))))
4768 (defun org-font-lock-add-priority-faces (limit)
4769 "Add the special priority faces."
4770 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4771 (add-text-properties
4772 (match-beginning 0) (match-end 0)
4773 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4774 org-priority-faces))
4775 'org-special-keyword)
4776 'font-lock-fontified t))))
4778 (defun org-get-tag-face (kwd)
4779 "Get the right face for a TODO keyword KWD.
4780 If KWD is a number, get the corresponding match group."
4781 (if (numberp kwd) (setq kwd (match-string kwd)))
4782 (or (cdr (assoc kwd org-tag-faces))
4783 'org-tag))
4785 (defun org-unfontify-region (beg end &optional maybe_loudly)
4786 "Remove fontification and activation overlays from links."
4787 (font-lock-default-unfontify-region beg end)
4788 (let* ((buffer-undo-list t)
4789 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4790 (inhibit-modification-hooks t)
4791 deactivate-mark buffer-file-name buffer-file-truename)
4792 (remove-text-properties beg end
4793 '(mouse-face t keymap t org-linked-text t
4794 invisible t intangible t
4795 line-prefix t wrap-prefix t
4796 org-no-flyspell t))))
4798 ;;;; Visibility cycling, including org-goto and indirect buffer
4800 ;;; Cycling
4802 (defvar org-cycle-global-status nil)
4803 (make-variable-buffer-local 'org-cycle-global-status)
4804 (defvar org-cycle-subtree-status nil)
4805 (make-variable-buffer-local 'org-cycle-subtree-status)
4807 ;;;###autoload
4809 (defvar org-inlinetask-min-level)
4811 (defun org-cycle (&optional arg)
4812 "TAB-action and visibility cycling for Org-mode.
4814 This is the command invoked in Org-mode by the TAB key. Its main purpose
4815 is outine visibility cycling, but it also invokes other actions
4816 in special contexts.
4818 - When this function is called with a prefix argument, rotate the entire
4819 buffer through 3 states (global cycling)
4820 1. OVERVIEW: Show only top-level headlines.
4821 2. CONTENTS: Show all headlines of all levels, but no body text.
4822 3. SHOW ALL: Show everything.
4823 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4824 determined by the variable `org-startup-folded', and by any VISIBILITY
4825 properties in the buffer.
4826 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4827 including any drawers.
4829 - When inside a table, re-align the table and move to the next field.
4831 - When point is at the beginning of a headline, rotate the subtree started
4832 by this line through 3 different states (local cycling)
4833 1. FOLDED: Only the main headline is shown.
4834 2. CHILDREN: The main headline and the direct children are shown.
4835 From this state, you can move to one of the children
4836 and zoom in further.
4837 3. SUBTREE: Show the entire subtree, including body text.
4838 If there is no subtree, switch directly from CHILDREN to FOLDED.
4840 - When there is a numeric prefix, go up to a heading with level ARG, do
4841 a `show-subtree' and return to the previous cursor position. If ARG
4842 is negative, go up that many levels.
4844 - When point is not at the beginning of a headline, execute the global
4845 binding for TAB, which is re-indenting the line. See the option
4846 `org-cycle-emulate-tab' for details.
4848 - Special case: if point is at the beginning of the buffer and there is
4849 no headline in line 1, this function will act as if called with prefix arg.
4850 But only if also the variable `org-cycle-global-at-bob' is t."
4851 (interactive "P")
4852 (org-load-modules-maybe)
4853 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4854 (let* ((limit-level
4855 (or org-cycle-max-level
4856 (and (boundp 'org-inlinetask-min-level)
4857 org-inlinetask-min-level
4858 (1- org-inlinetask-min-level))))
4859 (nstars (and limit-level
4860 (if org-odd-levels-only
4861 (and limit-level (1- (* limit-level 2)))
4862 limit-level)))
4863 (outline-regexp
4864 (cond
4865 ((not (org-mode-p)) outline-regexp)
4866 ((or (eq org-cycle-include-plain-lists 'integrate)
4867 (and org-cycle-include-plain-lists (org-at-item-p)))
4868 (concat "\\(?:\\*"
4869 (if nstars (format "\\{1,%d\\}" nstars) "+")
4870 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4871 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4872 (bob-special (and org-cycle-global-at-bob (bobp)
4873 (not (looking-at outline-regexp))))
4874 (org-cycle-hook
4875 (if bob-special
4876 (delq 'org-optimize-window-after-visibility-change
4877 (copy-sequence org-cycle-hook))
4878 org-cycle-hook))
4879 (pos (point)))
4881 (if (or bob-special (equal arg '(4)))
4882 ;; special case: use global cycling
4883 (setq arg t))
4885 (cond
4887 ((equal arg '(16))
4888 (org-set-startup-visibility)
4889 (message "Startup visibility, plus VISIBILITY properties"))
4891 ((equal arg '(64))
4892 (show-all)
4893 (message "Entire buffer visible, including drawers"))
4895 ((org-at-table-p 'any)
4896 ;; Enter the table or move to the next field in the table
4897 (or (org-table-recognize-table.el)
4898 (progn
4899 (if arg (org-table-edit-field t)
4900 (org-table-justify-field-maybe)
4901 (call-interactively 'org-table-next-field)))))
4903 ((run-hook-with-args-until-success
4904 'org-tab-after-check-for-table-hook))
4906 ((eq arg t) ;; Global cycling
4907 (org-cycle-internal-global))
4909 ((and org-drawers org-drawer-regexp
4910 (save-excursion
4911 (beginning-of-line 1)
4912 (looking-at org-drawer-regexp)))
4913 ;; Toggle block visibility
4914 (org-flag-drawer
4915 (not (get-char-property (match-end 0) 'invisible))))
4917 ((integerp arg)
4918 ;; Show-subtree, ARG levels up from here.
4919 (save-excursion
4920 (org-back-to-heading)
4921 (outline-up-heading (if (< arg 0) (- arg)
4922 (- (funcall outline-level) arg)))
4923 (org-show-subtree)))
4925 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4926 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4928 (org-cycle-internal-local))
4930 ;; TAB emulation and template completion
4931 (buffer-read-only (org-back-to-heading))
4933 ((run-hook-with-args-until-success
4934 'org-tab-after-check-for-cycling-hook))
4936 ((org-try-structure-completion))
4938 ((org-try-cdlatex-tab))
4940 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4941 (or (not (bolp))
4942 (not (looking-at outline-regexp))))
4943 (call-interactively (global-key-binding "\t")))
4945 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4946 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4947 (or (and (eq org-cycle-emulate-tab 'white)
4948 (= (match-end 0) (point-at-eol)))
4949 (and (eq org-cycle-emulate-tab 'whitestart)
4950 (>= (match-end 0) pos))))
4952 (eq org-cycle-emulate-tab t))
4953 (call-interactively (global-key-binding "\t")))
4955 (t (save-excursion
4956 (org-back-to-heading)
4957 (org-cycle)))))))
4959 (defun org-cycle-internal-global ()
4960 "Do the global cycling action."
4961 (cond
4962 ((and (eq last-command this-command)
4963 (eq org-cycle-global-status 'overview))
4964 ;; We just created the overview - now do table of contents
4965 ;; This can be slow in very large buffers, so indicate action
4966 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4967 (message "CONTENTS...")
4968 (org-content)
4969 (message "CONTENTS...done")
4970 (setq org-cycle-global-status 'contents)
4971 (run-hook-with-args 'org-cycle-hook 'contents))
4973 ((and (eq last-command this-command)
4974 (eq org-cycle-global-status 'contents))
4975 ;; We just showed the table of contents - now show everything
4976 (run-hook-with-args 'org-pre-cycle-hook 'all)
4977 (show-all)
4978 (message "SHOW ALL")
4979 (setq org-cycle-global-status 'all)
4980 (run-hook-with-args 'org-cycle-hook 'all))
4983 ;; Default action: go to overview
4984 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4985 (org-overview)
4986 (message "OVERVIEW")
4987 (setq org-cycle-global-status 'overview)
4988 (run-hook-with-args 'org-cycle-hook 'overview))))
4990 (defun org-cycle-internal-local ()
4991 "Do the local cycling action."
4992 (org-back-to-heading)
4993 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
4994 ;; First, some boundaries
4995 (save-excursion
4996 (org-back-to-heading)
4997 (setq level (funcall outline-level))
4998 (save-excursion
4999 (beginning-of-line 2)
5000 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5001 ; XEmacs does not have `next-single-char-property-change'
5002 ; I'm not sure about Emacs 21.
5003 (while (and (not (eobp)) ;; this is like `next-line'
5004 (get-char-property (1- (point)) 'invisible))
5005 (beginning-of-line 2))
5006 (while (and (not (eobp)) ;; this is like `next-line'
5007 (get-char-property (1- (point)) 'invisible))
5008 (goto-char (next-single-char-property-change (point) 'invisible))
5009 ;;;??? (or (bolp) (beginning-of-line 2))))
5010 (and (eolp) (beginning-of-line 2))))
5011 (setq eol (point)))
5012 (outline-end-of-heading) (setq eoh (point))
5013 (save-excursion
5014 (outline-next-heading)
5015 (setq has-children (and (org-at-heading-p t)
5016 (> (funcall outline-level) level))))
5017 (org-end-of-subtree t)
5018 (unless (eobp)
5019 (skip-chars-forward " \t\n")
5020 (beginning-of-line 1) ; in case this is an item
5022 (setq eos (if (eobp) (point) (1- (point)))))
5023 ;; Find out what to do next and set `this-command'
5024 (cond
5025 ((= eos eoh)
5026 ;; Nothing is hidden behind this heading
5027 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5028 (message "EMPTY ENTRY")
5029 (setq org-cycle-subtree-status nil)
5030 (save-excursion
5031 (goto-char eos)
5032 (outline-next-heading)
5033 (if (org-invisible-p) (org-flag-heading nil))))
5034 ((and (or (>= eol eos)
5035 (not (string-match "\\S-" (buffer-substring eol eos))))
5036 (or has-children
5037 (not (setq children-skipped
5038 org-cycle-skip-children-state-if-no-children))))
5039 ;; Entire subtree is hidden in one line: children view
5040 (run-hook-with-args 'org-pre-cycle-hook 'children)
5041 (org-show-entry)
5042 (show-children)
5043 (message "CHILDREN")
5044 (save-excursion
5045 (goto-char eos)
5046 (outline-next-heading)
5047 (if (org-invisible-p) (org-flag-heading nil)))
5048 (setq org-cycle-subtree-status 'children)
5049 (run-hook-with-args 'org-cycle-hook 'children))
5050 ((or children-skipped
5051 (and (eq last-command this-command)
5052 (eq org-cycle-subtree-status 'children)))
5053 ;; We just showed the children, or no children are there,
5054 ;; now show everything.
5055 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5056 (org-show-subtree)
5057 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5058 (setq org-cycle-subtree-status 'subtree)
5059 (run-hook-with-args 'org-cycle-hook 'subtree))
5061 ;; Default action: hide the subtree.
5062 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5063 (hide-subtree)
5064 (message "FOLDED")
5065 (setq org-cycle-subtree-status 'folded)
5066 (run-hook-with-args 'org-cycle-hook 'folded)))))
5068 ;;;###autoload
5069 (defun org-global-cycle (&optional arg)
5070 "Cycle the global visibility. For details see `org-cycle'.
5071 With C-u prefix arg, switch to startup visibility.
5072 With a numeric prefix, show all headlines up to that level."
5073 (interactive "P")
5074 (let ((org-cycle-include-plain-lists
5075 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5076 (cond
5077 ((integerp arg)
5078 (show-all)
5079 (hide-sublevels arg)
5080 (setq org-cycle-global-status 'contents))
5081 ((equal arg '(4))
5082 (org-set-startup-visibility)
5083 (message "Startup visibility, plus VISIBILITY properties."))
5085 (org-cycle '(4))))))
5087 (defun org-set-startup-visibility ()
5088 "Set the visibility required by startup options and properties."
5089 (cond
5090 ((eq org-startup-folded t)
5091 (org-cycle '(4)))
5092 ((eq org-startup-folded 'content)
5093 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5094 (org-cycle '(4)) (org-cycle '(4)))))
5095 (if org-hide-block-startup (org-hide-block-all))
5096 (org-set-visibility-according-to-property 'no-cleanup)
5097 (org-cycle-hide-archived-subtrees 'all)
5098 (org-cycle-hide-drawers 'all)
5099 (org-cycle-show-empty-lines 'all))
5101 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5102 "Switch subtree visibilities according to :VISIBILITY: property."
5103 (interactive)
5104 (let (org-show-entry-below state)
5105 (save-excursion
5106 (goto-char (point-min))
5107 (while (re-search-forward
5108 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5109 nil t)
5110 (setq state (match-string 1))
5111 (save-excursion
5112 (org-back-to-heading t)
5113 (hide-subtree)
5114 (org-reveal)
5115 (cond
5116 ((equal state '("fold" "folded"))
5117 (hide-subtree))
5118 ((equal state "children")
5119 (org-show-hidden-entry)
5120 (show-children))
5121 ((equal state "content")
5122 (save-excursion
5123 (save-restriction
5124 (org-narrow-to-subtree)
5125 (org-content))))
5126 ((member state '("all" "showall"))
5127 (show-subtree)))))
5128 (unless no-cleanup
5129 (org-cycle-hide-archived-subtrees 'all)
5130 (org-cycle-hide-drawers 'all)
5131 (org-cycle-show-empty-lines 'all)))))
5133 (defun org-overview ()
5134 "Switch to overview mode, showing only top-level headlines.
5135 Really, this shows all headlines with level equal or greater than the level
5136 of the first headline in the buffer. This is important, because if the
5137 first headline is not level one, then (hide-sublevels 1) gives confusing
5138 results."
5139 (interactive)
5140 (let ((level (save-excursion
5141 (goto-char (point-min))
5142 (if (re-search-forward (concat "^" outline-regexp) nil t)
5143 (progn
5144 (goto-char (match-beginning 0))
5145 (funcall outline-level))))))
5146 (and level (hide-sublevels level))))
5148 (defun org-content (&optional arg)
5149 "Show all headlines in the buffer, like a table of contents.
5150 With numerical argument N, show content up to level N."
5151 (interactive "P")
5152 (save-excursion
5153 ;; Visit all headings and show their offspring
5154 (and (integerp arg) (org-overview))
5155 (goto-char (point-max))
5156 (catch 'exit
5157 (while (and (progn (condition-case nil
5158 (outline-previous-visible-heading 1)
5159 (error (goto-char (point-min))))
5161 (looking-at outline-regexp))
5162 (if (integerp arg)
5163 (show-children (1- arg))
5164 (show-branches))
5165 (if (bobp) (throw 'exit nil))))))
5168 (defun org-optimize-window-after-visibility-change (state)
5169 "Adjust the window after a change in outline visibility.
5170 This function is the default value of the hook `org-cycle-hook'."
5171 (when (get-buffer-window (current-buffer))
5172 (cond
5173 ((eq state 'content) nil)
5174 ((eq state 'all) nil)
5175 ((eq state 'folded) nil)
5176 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5177 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5179 ;; FIXME: no longer in use
5180 (defun org-compact-display-after-subtree-move ()
5181 "Show a compacter version of the tree of the entry's parent."
5182 (save-excursion
5183 (if (org-up-heading-safe)
5184 (progn
5185 (hide-subtree)
5186 (show-entry)
5187 (show-children)
5188 (org-cycle-show-empty-lines 'children)
5189 (org-cycle-hide-drawers 'children))
5190 (org-overview))))
5192 (defun org-remove-empty-overlays-at (pos)
5193 "Remove outline overlays that do not contain non-white stuff."
5194 (mapc
5195 (lambda (o)
5196 (and (eq 'outline (org-overlay-get o 'invisible))
5197 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5198 (org-overlay-end o))))
5199 (org-delete-overlay o)))
5200 (org-overlays-at pos)))
5202 (defun org-clean-visibility-after-subtree-move ()
5203 "Fix visibility issues after moving a subtree."
5204 ;; First, find a reasonable region to look at:
5205 ;; Start two siblings above, end three below
5206 (let* ((beg (save-excursion
5207 (and (outline-get-last-sibling)
5208 (outline-get-last-sibling))
5209 (point)))
5210 (end (save-excursion
5211 (and (outline-get-next-sibling)
5212 (outline-get-next-sibling)
5213 (outline-get-next-sibling))
5214 (if (org-at-heading-p)
5215 (point-at-eol)
5216 (point))))
5217 (level (looking-at "\\*+"))
5218 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5219 (save-excursion
5220 (save-restriction
5221 (narrow-to-region beg end)
5222 (when re
5223 ;; Properly fold already folded siblings
5224 (goto-char (point-min))
5225 (while (re-search-forward re nil t)
5226 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5227 (hide-entry))))
5228 (org-cycle-show-empty-lines 'overview)
5229 (org-cycle-hide-drawers 'overview)))))
5231 (defun org-cycle-show-empty-lines (state)
5232 "Show empty lines above all visible headlines.
5233 The region to be covered depends on STATE when called through
5234 `org-cycle-hook'. Lisp program can use t for STATE to get the
5235 entire buffer covered. Note that an empty line is only shown if there
5236 are at least `org-cycle-separator-lines' empty lines before the headline."
5237 (when (not (= org-cycle-separator-lines 0))
5238 (save-excursion
5239 (let* ((n (abs org-cycle-separator-lines))
5240 (re (cond
5241 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5242 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5243 (t (let ((ns (number-to-string (- n 2))))
5244 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5245 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5246 beg end b e)
5247 (cond
5248 ((memq state '(overview contents t))
5249 (setq beg (point-min) end (point-max)))
5250 ((memq state '(children folded))
5251 (setq beg (point) end (progn (org-end-of-subtree t t)
5252 (beginning-of-line 2)
5253 (point)))))
5254 (when beg
5255 (goto-char beg)
5256 (while (re-search-forward re end t)
5257 (unless (get-char-property (match-end 1) 'invisible)
5258 (setq e (match-end 1))
5259 (if (< org-cycle-separator-lines 0)
5260 (setq b (save-excursion
5261 (goto-char (match-beginning 0))
5262 (org-back-over-empty-lines)
5263 (point)))
5264 (setq b (match-beginning 1)))
5265 (outline-flag-region b e nil)))))))
5266 ;; Never hide empty lines at the end of the file.
5267 (save-excursion
5268 (goto-char (point-max))
5269 (outline-previous-heading)
5270 (outline-end-of-heading)
5271 (if (and (looking-at "[ \t\n]+")
5272 (= (match-end 0) (point-max)))
5273 (outline-flag-region (point) (match-end 0) nil))))
5275 (defun org-show-empty-lines-in-parent ()
5276 "Move to the parent and re-show empty lines before visible headlines."
5277 (save-excursion
5278 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5279 (org-cycle-show-empty-lines context))))
5281 (defun org-cycle-hide-drawers (state)
5282 "Re-hide all drawers after a visibility state change."
5283 (when (and (org-mode-p)
5284 (not (memq state '(overview folded contents))))
5285 (save-excursion
5286 (let* ((globalp (memq state '(contents all)))
5287 (beg (if globalp (point-min) (point)))
5288 (end (if globalp (point-max)
5289 (if (eq state 'children)
5290 (save-excursion (outline-next-heading) (point))
5291 (org-end-of-subtree t)))))
5292 (goto-char beg)
5293 (while (re-search-forward org-drawer-regexp end t)
5294 (org-flag-drawer t))))))
5296 (defun org-flag-drawer (flag)
5297 (save-excursion
5298 (beginning-of-line 1)
5299 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5300 (let ((b (match-end 0))
5301 (outline-regexp org-outline-regexp))
5302 (if (re-search-forward
5303 "^[ \t]*:END:"
5304 (save-excursion (outline-next-heading) (point)) t)
5305 (outline-flag-region b (point-at-eol) flag)
5306 (error ":END: line missing at position %s" b))))))
5308 (defun org-subtree-end-visible-p ()
5309 "Is the end of the current subtree visible?"
5310 (pos-visible-in-window-p
5311 (save-excursion (org-end-of-subtree t) (point))))
5313 (defun org-first-headline-recenter (&optional N)
5314 "Move cursor to the first headline and recenter the headline.
5315 Optional argument N means, put the headline into the Nth line of the window."
5316 (goto-char (point-min))
5317 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5318 (beginning-of-line)
5319 (recenter (prefix-numeric-value N))))
5321 ;;; Folding of blocks
5323 (defconst org-block-regexp
5325 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5326 "Regular expression for hiding blocks.")
5328 (defvar org-hide-block-overlays nil
5329 "Overays hiding blocks.")
5330 (make-variable-buffer-local 'org-hide-block-overlays)
5332 (defun org-block-map (function &optional start end)
5333 "Call func at the head of all source blocks in the current
5334 buffer. Optional arguments START and END can be used to limit
5335 the range."
5336 (let ((start (or start (point-min)))
5337 (end (or end (point-max))))
5338 (save-excursion
5339 (goto-char start)
5340 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5341 (save-excursion
5342 (save-match-data
5343 (goto-char (match-beginning 0))
5344 (funcall function)))))))
5346 (defun org-hide-block-toggle-all ()
5347 "Toggle the visibility of all blocks in the current buffer."
5348 (org-block-map #'org-hide-block-toggle))
5350 (defun org-hide-block-all ()
5351 "Fold all blocks in the current buffer."
5352 (interactive)
5353 (org-show-block-all)
5354 (org-block-map #'org-hide-block-toggle-maybe))
5356 (defun org-show-block-all ()
5357 "Unfold all blocks in the current buffer."
5358 (mapc 'org-delete-overlay org-hide-block-overlays)
5359 (setq org-hide-block-overlays nil))
5361 (defun org-hide-block-toggle-maybe ()
5362 "Toggle visibility of block at point."
5363 (interactive)
5364 (let ((case-fold-search t))
5365 (if (save-excursion
5366 (beginning-of-line 1)
5367 (looking-at org-block-regexp))
5368 (progn (org-hide-block-toggle)
5369 t) ;; to signal that we took action
5370 nil))) ;; to signal that we did not
5372 (defun org-hide-block-toggle (&optional force)
5373 "Toggle the visibility of the current block."
5374 (interactive)
5375 (save-excursion
5376 (beginning-of-line)
5377 (if (re-search-forward org-block-regexp nil t)
5378 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5379 (end (match-end 0)) ;; end of entire body
5381 (if (memq t (mapcar (lambda (overlay)
5382 (eq (org-overlay-get overlay 'invisible)
5383 'org-hide-block))
5384 (org-overlays-at start)))
5385 (if (or (not force) (eq force 'off))
5386 (mapc (lambda (ov)
5387 (when (member ov org-hide-block-overlays)
5388 (setq org-hide-block-overlays
5389 (delq ov org-hide-block-overlays)))
5390 (when (eq (org-overlay-get ov 'invisible)
5391 'org-hide-block)
5392 (org-delete-overlay ov)))
5393 (org-overlays-at start)))
5394 (setq ov (org-make-overlay start end))
5395 (org-overlay-put ov 'invisible 'org-hide-block)
5396 ;; make the block accessible to isearch
5397 (org-overlay-put
5398 ov 'isearch-open-invisible
5399 (lambda (ov)
5400 (when (member ov org-hide-block-overlays)
5401 (setq org-hide-block-overlays
5402 (delq ov org-hide-block-overlays)))
5403 (when (eq (org-overlay-get ov 'invisible)
5404 'org-hide-block)
5405 (org-delete-overlay ov))))
5406 (push ov org-hide-block-overlays)))
5407 (error "Not looking at a source block"))))
5409 ;; org-tab-after-check-for-cycling-hook
5410 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5411 ;; Remove overlays when changing major mode
5412 (add-hook 'org-mode-hook
5413 (lambda () (org-add-hook 'change-major-mode-hook
5414 'org-show-block-all 'append 'local)))
5416 ;;; Org-goto
5418 (defvar org-goto-window-configuration nil)
5419 (defvar org-goto-marker nil)
5420 (defvar org-goto-map
5421 (let ((map (make-sparse-keymap)))
5422 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5423 (while (setq cmd (pop cmds))
5424 (substitute-key-definition cmd cmd map global-map)))
5425 (suppress-keymap map)
5426 (org-defkey map "\C-m" 'org-goto-ret)
5427 (org-defkey map [(return)] 'org-goto-ret)
5428 (org-defkey map [(left)] 'org-goto-left)
5429 (org-defkey map [(right)] 'org-goto-right)
5430 (org-defkey map [(control ?g)] 'org-goto-quit)
5431 (org-defkey map "\C-i" 'org-cycle)
5432 (org-defkey map [(tab)] 'org-cycle)
5433 (org-defkey map [(down)] 'outline-next-visible-heading)
5434 (org-defkey map [(up)] 'outline-previous-visible-heading)
5435 (if org-goto-auto-isearch
5436 (if (fboundp 'define-key-after)
5437 (define-key-after map [t] 'org-goto-local-auto-isearch)
5438 nil)
5439 (org-defkey map "q" 'org-goto-quit)
5440 (org-defkey map "n" 'outline-next-visible-heading)
5441 (org-defkey map "p" 'outline-previous-visible-heading)
5442 (org-defkey map "f" 'outline-forward-same-level)
5443 (org-defkey map "b" 'outline-backward-same-level)
5444 (org-defkey map "u" 'outline-up-heading))
5445 (org-defkey map "/" 'org-occur)
5446 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5447 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5448 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5449 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5450 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5451 map))
5453 (defconst org-goto-help
5454 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5455 RET=jump to location [Q]uit and return to previous location
5456 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5458 (defvar org-goto-start-pos) ; dynamically scoped parameter
5460 ;; FIXME: Docstring doe not mention both interfaces
5461 (defun org-goto (&optional alternative-interface)
5462 "Look up a different location in the current file, keeping current visibility.
5464 When you want look-up or go to a different location in a document, the
5465 fastest way is often to fold the entire buffer and then dive into the tree.
5466 This method has the disadvantage, that the previous location will be folded,
5467 which may not be what you want.
5469 This command works around this by showing a copy of the current buffer
5470 in an indirect buffer, in overview mode. You can dive into the tree in
5471 that copy, use org-occur and incremental search to find a location.
5472 When pressing RET or `Q', the command returns to the original buffer in
5473 which the visibility is still unchanged. After RET is will also jump to
5474 the location selected in the indirect buffer and expose the
5475 the headline hierarchy above."
5476 (interactive "P")
5477 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5478 (org-refile-use-outline-path t)
5479 (org-refile-target-verify-function nil)
5480 (interface
5481 (if (not alternative-interface)
5482 org-goto-interface
5483 (if (eq org-goto-interface 'outline)
5484 'outline-path-completion
5485 'outline)))
5486 (org-goto-start-pos (point))
5487 (selected-point
5488 (if (eq interface 'outline)
5489 (car (org-get-location (current-buffer) org-goto-help))
5490 (nth 3 (org-refile-get-location "Goto: ")))))
5491 (if selected-point
5492 (progn
5493 (org-mark-ring-push org-goto-start-pos)
5494 (goto-char selected-point)
5495 (if (or (org-invisible-p) (org-invisible-p2))
5496 (org-show-context 'org-goto)))
5497 (message "Quit"))))
5499 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5500 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5501 (defvar org-goto-local-auto-isearch-map) ; defined below
5503 (defun org-get-location (buf help)
5504 "Let the user select a location in the Org-mode buffer BUF.
5505 This function uses a recursive edit. It returns the selected position
5506 or nil."
5507 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5508 (isearch-hide-immediately nil)
5509 (isearch-search-fun-function
5510 (lambda () 'org-goto-local-search-headings))
5511 (org-goto-selected-point org-goto-exit-command))
5512 (save-excursion
5513 (save-window-excursion
5514 (delete-other-windows)
5515 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5516 (switch-to-buffer
5517 (condition-case nil
5518 (make-indirect-buffer (current-buffer) "*org-goto*")
5519 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5520 (with-output-to-temp-buffer "*Help*"
5521 (princ help))
5522 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5523 (setq buffer-read-only nil)
5524 (let ((org-startup-truncated t)
5525 (org-startup-folded nil)
5526 (org-startup-align-all-tables nil))
5527 (org-mode)
5528 (org-overview))
5529 (setq buffer-read-only t)
5530 (if (and (boundp 'org-goto-start-pos)
5531 (integer-or-marker-p org-goto-start-pos))
5532 (let ((org-show-hierarchy-above t)
5533 (org-show-siblings t)
5534 (org-show-following-heading t))
5535 (goto-char org-goto-start-pos)
5536 (and (org-invisible-p) (org-show-context)))
5537 (goto-char (point-min)))
5538 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5539 (message "Select location and press RET")
5540 (use-local-map org-goto-map)
5541 (recursive-edit)
5543 (kill-buffer "*org-goto*")
5544 (cons org-goto-selected-point org-goto-exit-command)))
5546 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5547 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5548 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5549 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5551 (defun org-goto-local-search-headings (string bound noerror)
5552 "Search and make sure that any matches are in headlines."
5553 (catch 'return
5554 (while (if isearch-forward
5555 (search-forward string bound noerror)
5556 (search-backward string bound noerror))
5557 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5558 (and (member :headline context)
5559 (not (member :tags context))))
5560 (throw 'return (point))))))
5562 (defun org-goto-local-auto-isearch ()
5563 "Start isearch."
5564 (interactive)
5565 (goto-char (point-min))
5566 (let ((keys (this-command-keys)))
5567 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5568 (isearch-mode t)
5569 (isearch-process-search-char (string-to-char keys)))))
5571 (defun org-goto-ret (&optional arg)
5572 "Finish `org-goto' by going to the new location."
5573 (interactive "P")
5574 (setq org-goto-selected-point (point)
5575 org-goto-exit-command 'return)
5576 (throw 'exit nil))
5578 (defun org-goto-left ()
5579 "Finish `org-goto' by going to the new location."
5580 (interactive)
5581 (if (org-on-heading-p)
5582 (progn
5583 (beginning-of-line 1)
5584 (setq org-goto-selected-point (point)
5585 org-goto-exit-command 'left)
5586 (throw 'exit nil))
5587 (error "Not on a heading")))
5589 (defun org-goto-right ()
5590 "Finish `org-goto' by going to the new location."
5591 (interactive)
5592 (if (org-on-heading-p)
5593 (progn
5594 (setq org-goto-selected-point (point)
5595 org-goto-exit-command 'right)
5596 (throw 'exit nil))
5597 (error "Not on a heading")))
5599 (defun org-goto-quit ()
5600 "Finish `org-goto' without cursor motion."
5601 (interactive)
5602 (setq org-goto-selected-point nil)
5603 (setq org-goto-exit-command 'quit)
5604 (throw 'exit nil))
5606 ;;; Indirect buffer display of subtrees
5608 (defvar org-indirect-dedicated-frame nil
5609 "This is the frame being used for indirect tree display.")
5610 (defvar org-last-indirect-buffer nil)
5612 (defun org-tree-to-indirect-buffer (&optional arg)
5613 "Create indirect buffer and narrow it to current subtree.
5614 With numerical prefix ARG, go up to this level and then take that tree.
5615 If ARG is negative, go up that many levels.
5616 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5617 indirect buffer previously made with this command, to avoid proliferation of
5618 indirect buffers. However, when you call the command with a `C-u' prefix, or
5619 when `org-indirect-buffer-display' is `new-frame', the last buffer
5620 is kept so that you can work with several indirect buffers at the same time.
5621 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5622 requests that a new frame be made for the new buffer, so that the dedicated
5623 frame is not changed."
5624 (interactive "P")
5625 (let ((cbuf (current-buffer))
5626 (cwin (selected-window))
5627 (pos (point))
5628 beg end level heading ibuf)
5629 (save-excursion
5630 (org-back-to-heading t)
5631 (when (numberp arg)
5632 (setq level (org-outline-level))
5633 (if (< arg 0) (setq arg (+ level arg)))
5634 (while (> (setq level (org-outline-level)) arg)
5635 (outline-up-heading 1 t)))
5636 (setq beg (point)
5637 heading (org-get-heading))
5638 (org-end-of-subtree t) (setq end (point)))
5639 (if (and (buffer-live-p org-last-indirect-buffer)
5640 (not (eq org-indirect-buffer-display 'new-frame))
5641 (not arg))
5642 (kill-buffer org-last-indirect-buffer))
5643 (setq ibuf (org-get-indirect-buffer cbuf)
5644 org-last-indirect-buffer ibuf)
5645 (cond
5646 ((or (eq org-indirect-buffer-display 'new-frame)
5647 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5648 (select-frame (make-frame))
5649 (delete-other-windows)
5650 (switch-to-buffer ibuf)
5651 (org-set-frame-title heading))
5652 ((eq org-indirect-buffer-display 'dedicated-frame)
5653 (raise-frame
5654 (select-frame (or (and org-indirect-dedicated-frame
5655 (frame-live-p org-indirect-dedicated-frame)
5656 org-indirect-dedicated-frame)
5657 (setq org-indirect-dedicated-frame (make-frame)))))
5658 (delete-other-windows)
5659 (switch-to-buffer ibuf)
5660 (org-set-frame-title (concat "Indirect: " heading)))
5661 ((eq org-indirect-buffer-display 'current-window)
5662 (switch-to-buffer ibuf))
5663 ((eq org-indirect-buffer-display 'other-window)
5664 (pop-to-buffer ibuf))
5665 (t (error "Invalid value.")))
5666 (if (featurep 'xemacs)
5667 (save-excursion (org-mode) (turn-on-font-lock)))
5668 (narrow-to-region beg end)
5669 (show-all)
5670 (goto-char pos)
5671 (and (window-live-p cwin) (select-window cwin))))
5673 (defun org-get-indirect-buffer (&optional buffer)
5674 (setq buffer (or buffer (current-buffer)))
5675 (let ((n 1) (base (buffer-name buffer)) bname)
5676 (while (buffer-live-p
5677 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5678 (setq n (1+ n)))
5679 (condition-case nil
5680 (make-indirect-buffer buffer bname 'clone)
5681 (error (make-indirect-buffer buffer bname)))))
5683 (defun org-set-frame-title (title)
5684 "Set the title of the current frame to the string TITLE."
5685 ;; FIXME: how to name a single frame in XEmacs???
5686 (unless (featurep 'xemacs)
5687 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5689 ;;;; Structure editing
5691 ;;; Inserting headlines
5693 (defun org-previous-line-empty-p ()
5694 (save-excursion
5695 (and (not (bobp))
5696 (or (beginning-of-line 0) t)
5697 (save-match-data
5698 (looking-at "[ \t]*$")))))
5700 (defun org-insert-heading (&optional force-heading)
5701 "Insert a new heading or item with same depth at point.
5702 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5703 If point is at the beginning of a headline, insert a sibling before the
5704 current headline. If point is not at the beginning, do not split the line,
5705 but create the new headline after the current line."
5706 (interactive "P")
5707 (if (= (buffer-size) 0)
5708 (insert "\n* ")
5709 (when (or force-heading (not (org-insert-item)))
5710 (let* ((empty-line-p nil)
5711 (head (save-excursion
5712 (condition-case nil
5713 (progn
5714 (org-back-to-heading)
5715 (setq empty-line-p (org-previous-line-empty-p))
5716 (match-string 0))
5717 (error "*"))))
5718 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5719 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5720 pos hide-previous previous-pos)
5721 (cond
5722 ((and (org-on-heading-p) (bolp)
5723 (or (bobp)
5724 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5725 ;; insert before the current line
5726 (open-line (if blank 2 1)))
5727 ((and (bolp)
5728 (not org-insert-heading-respect-content)
5729 (or (bobp)
5730 (save-excursion
5731 (backward-char 1) (not (org-invisible-p)))))
5732 ;; insert right here
5733 nil)
5735 ;; somewhere in the line
5736 (save-excursion
5737 (setq previous-pos (point-at-bol))
5738 (end-of-line)
5739 (setq hide-previous (org-invisible-p)))
5740 (and org-insert-heading-respect-content (org-show-subtree))
5741 (let ((split
5742 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5743 (save-excursion
5744 (let ((p (point)))
5745 (goto-char (point-at-bol))
5746 (and (looking-at org-complex-heading-regexp)
5747 (> p (match-beginning 4)))))))
5748 tags pos)
5749 (cond
5750 (org-insert-heading-respect-content
5751 (org-end-of-subtree nil t)
5752 (or (bolp) (newline))
5753 (or (org-previous-line-empty-p)
5754 (and blank (newline)))
5755 (open-line 1))
5756 ((org-on-heading-p)
5757 (when hide-previous
5758 (show-children)
5759 (org-show-entry))
5760 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5761 (setq tags (and (match-end 2) (match-string 2)))
5762 (and (match-end 1)
5763 (delete-region (match-beginning 1) (match-end 1)))
5764 (setq pos (point-at-bol))
5765 (or split (end-of-line 1))
5766 (delete-horizontal-space)
5767 (newline (if blank 2 1))
5768 (when tags
5769 (save-excursion
5770 (goto-char pos)
5771 (end-of-line 1)
5772 (insert " " tags)
5773 (org-set-tags nil 'align))))
5775 (or split (end-of-line 1))
5776 (newline (if blank 2 1)))))))
5777 (insert head) (just-one-space)
5778 (setq pos (point))
5779 (end-of-line 1)
5780 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5781 (when (and org-insert-heading-respect-content hide-previous)
5782 (save-excursion
5783 (goto-char previous-pos)
5784 (hide-subtree)))
5785 (run-hooks 'org-insert-heading-hook)))))
5787 (defun org-get-heading (&optional no-tags)
5788 "Return the heading of the current entry, without the stars."
5789 (save-excursion
5790 (org-back-to-heading t)
5791 (if (looking-at
5792 (if no-tags
5793 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5794 "\\*+[ \t]+\\([^\r\n]*\\)"))
5795 (match-string 1) "")))
5797 (defun org-heading-components ()
5798 "Return the components of the current heading.
5799 This is a list with the following elements:
5800 - the level as an integer
5801 - the reduced level, different if `org-odd-levels-only' is set.
5802 - the TODO keyword, or nil
5803 - the priority character, like ?A, or nil if no priority is given
5804 - the headline text itself, or the tags string if no headline text
5805 - the tags string, or nil."
5806 (save-excursion
5807 (org-back-to-heading t)
5808 (if (looking-at org-complex-heading-regexp)
5809 (list (length (match-string 1))
5810 (org-reduced-level (length (match-string 1)))
5811 (org-match-string-no-properties 2)
5812 (and (match-end 3) (aref (match-string 3) 2))
5813 (org-match-string-no-properties 4)
5814 (org-match-string-no-properties 5)))))
5816 (defun org-get-entry ()
5817 "Get the entry text, after heading, entire subtree."
5818 (save-excursion
5819 (org-back-to-heading t)
5820 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5822 (defun org-insert-heading-after-current ()
5823 "Insert a new heading with same level as current, after current subtree."
5824 (interactive)
5825 (org-back-to-heading)
5826 (org-insert-heading)
5827 (org-move-subtree-down)
5828 (end-of-line 1))
5830 (defun org-insert-heading-respect-content ()
5831 (interactive)
5832 (let ((org-insert-heading-respect-content t))
5833 (org-insert-heading t)))
5835 (defun org-insert-todo-heading-respect-content (&optional force-state)
5836 (interactive "P")
5837 (let ((org-insert-heading-respect-content t))
5838 (org-insert-todo-heading force-state t)))
5840 (defun org-insert-todo-heading (arg &optional force-heading)
5841 "Insert a new heading with the same level and TODO state as current heading.
5842 If the heading has no TODO state, or if the state is DONE, use the first
5843 state (TODO by default). Also with prefix arg, force first state."
5844 (interactive "P")
5845 (when (or force-heading (not (org-insert-item 'checkbox)))
5846 (org-insert-heading force-heading)
5847 (save-excursion
5848 (org-back-to-heading)
5849 (outline-previous-heading)
5850 (looking-at org-todo-line-regexp))
5851 (let*
5852 ((new-mark-x
5853 (if (or arg
5854 (not (match-beginning 2))
5855 (member (match-string 2) org-done-keywords))
5856 (car org-todo-keywords-1)
5857 (match-string 2)))
5858 (new-mark
5860 (run-hook-with-args-until-success
5861 'org-todo-get-default-hook new-mark-x nil)
5862 new-mark-x)))
5863 (beginning-of-line 1)
5864 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5865 (if org-treat-insert-todo-heading-as-state-change
5866 (org-todo new-mark)
5867 (insert new-mark " "))))
5868 (when org-provide-todo-statistics
5869 (org-update-parent-todo-statistics))))
5871 (defun org-insert-subheading (arg)
5872 "Insert a new subheading and demote it.
5873 Works for outline headings and for plain lists alike."
5874 (interactive "P")
5875 (org-insert-heading arg)
5876 (cond
5877 ((org-on-heading-p) (org-do-demote))
5878 ((org-at-item-p) (org-indent-item 1))))
5880 (defun org-insert-todo-subheading (arg)
5881 "Insert a new subheading with TODO keyword or checkbox and demote it.
5882 Works for outline headings and for plain lists alike."
5883 (interactive "P")
5884 (org-insert-todo-heading arg)
5885 (cond
5886 ((org-on-heading-p) (org-do-demote))
5887 ((org-at-item-p) (org-indent-item 1))))
5889 ;;; Promotion and Demotion
5891 (defvar org-after-demote-entry-hook nil
5892 "Hook run after an entry has been demoted.
5893 The cursor will be at the beginning of the entry.
5894 When a subtree is being demoted, the hook will be called for each node.")
5896 (defvar org-after-promote-entry-hook nil
5897 "Hook run after an entry has been promoted.
5898 The cursor will be at the beginning of the entry.
5899 When a subtree is being promoted, the hook will be called for each node.")
5901 (defun org-promote-subtree ()
5902 "Promote the entire subtree.
5903 See also `org-promote'."
5904 (interactive)
5905 (save-excursion
5906 (org-map-tree 'org-promote))
5907 (org-fix-position-after-promote))
5909 (defun org-demote-subtree ()
5910 "Demote the entire subtree. See `org-demote'.
5911 See also `org-promote'."
5912 (interactive)
5913 (save-excursion
5914 (org-map-tree 'org-demote))
5915 (org-fix-position-after-promote))
5918 (defun org-do-promote ()
5919 "Promote the current heading higher up the tree.
5920 If the region is active in `transient-mark-mode', promote all headings
5921 in the region."
5922 (interactive)
5923 (save-excursion
5924 (if (org-region-active-p)
5925 (org-map-region 'org-promote (region-beginning) (region-end))
5926 (org-promote)))
5927 (org-fix-position-after-promote))
5929 (defun org-do-demote ()
5930 "Demote the current heading lower down the tree.
5931 If the region is active in `transient-mark-mode', demote all headings
5932 in the region."
5933 (interactive)
5934 (save-excursion
5935 (if (org-region-active-p)
5936 (org-map-region 'org-demote (region-beginning) (region-end))
5937 (org-demote)))
5938 (org-fix-position-after-promote))
5940 (defun org-fix-position-after-promote ()
5941 "Make sure that after pro/demotion cursor position is right."
5942 (let ((pos (point)))
5943 (when (save-excursion
5944 (beginning-of-line 1)
5945 (looking-at org-todo-line-regexp)
5946 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5947 (cond ((eobp) (insert " "))
5948 ((eolp) (insert " "))
5949 ((equal (char-after) ?\ ) (forward-char 1))))))
5951 (defun org-reduced-level (l)
5952 "Compute the effective level of a heading.
5953 This takes into account the setting of `org-odd-levels-only'."
5954 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5956 (defun org-get-valid-level (level &optional change)
5957 "Rectify a level change under the influence of `org-odd-levels-only'
5958 LEVEL is a current level, CHANGE is by how much the level should be
5959 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5960 even level numbers will become the next higher odd number."
5961 (if org-odd-levels-only
5962 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5963 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5964 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5965 (max 1 (+ level (or change 0)))))
5967 (if (boundp 'define-obsolete-function-alias)
5968 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5969 (define-obsolete-function-alias 'org-get-legal-level
5970 'org-get-valid-level)
5971 (define-obsolete-function-alias 'org-get-legal-level
5972 'org-get-valid-level "23.1")))
5974 (defun org-promote ()
5975 "Promote the current heading higher up the tree.
5976 If the region is active in `transient-mark-mode', promote all headings
5977 in the region."
5978 (org-back-to-heading t)
5979 (let* ((level (save-match-data (funcall outline-level)))
5980 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5981 (diff (abs (- level (length up-head) -1))))
5982 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5983 (replace-match up-head nil t)
5984 ;; Fixup tag positioning
5985 (and org-auto-align-tags (org-set-tags nil t))
5986 (if org-adapt-indentation (org-fixup-indentation (- diff)))
5987 (run-hooks 'org-after-promote-entry-hook)))
5989 (defun org-demote ()
5990 "Demote the current heading lower down the tree.
5991 If the region is active in `transient-mark-mode', demote all headings
5992 in the region."
5993 (org-back-to-heading t)
5994 (let* ((level (save-match-data (funcall outline-level)))
5995 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5996 (diff (abs (- level (length down-head) -1))))
5997 (replace-match down-head nil t)
5998 ;; Fixup tag positioning
5999 (and org-auto-align-tags (org-set-tags nil t))
6000 (if org-adapt-indentation (org-fixup-indentation diff))
6001 (run-hooks 'org-after-demote-entry-hook)))
6003 (defun org-map-tree (fun)
6004 "Call FUN for every heading underneath the current one."
6005 (org-back-to-heading)
6006 (let ((level (funcall outline-level)))
6007 (save-excursion
6008 (funcall fun)
6009 (while (and (progn
6010 (outline-next-heading)
6011 (> (funcall outline-level) level))
6012 (not (eobp)))
6013 (funcall fun)))))
6015 (defun org-map-region (fun beg end)
6016 "Call FUN for every heading between BEG and END."
6017 (let ((org-ignore-region t))
6018 (save-excursion
6019 (setq end (copy-marker end))
6020 (goto-char beg)
6021 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6022 (< (point) end))
6023 (funcall fun))
6024 (while (and (progn
6025 (outline-next-heading)
6026 (< (point) end))
6027 (not (eobp)))
6028 (funcall fun)))))
6030 (defun org-fixup-indentation (diff)
6031 "Change the indentation in the current entry by DIFF
6032 However, if any line in the current entry has no indentation, or if it
6033 would end up with no indentation after the change, nothing at all is done."
6034 (save-excursion
6035 (let ((end (save-excursion (outline-next-heading)
6036 (point-marker)))
6037 (prohibit (if (> diff 0)
6038 "^\\S-"
6039 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6040 col)
6041 (unless (save-excursion (end-of-line 1)
6042 (re-search-forward prohibit end t))
6043 (while (and (< (point) end)
6044 (re-search-forward "^[ \t]+" end t))
6045 (goto-char (match-end 0))
6046 (setq col (current-column))
6047 (if (< diff 0) (replace-match ""))
6048 (org-indent-to-column (+ diff col))))
6049 (move-marker end nil))))
6051 (defun org-convert-to-odd-levels ()
6052 "Convert an org-mode file with all levels allowed to one with odd levels.
6053 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6054 level 5 etc."
6055 (interactive)
6056 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6057 (let ((org-odd-levels-only nil) n)
6058 (save-excursion
6059 (goto-char (point-min))
6060 (while (re-search-forward "^\\*\\*+ " nil t)
6061 (setq n (- (length (match-string 0)) 2))
6062 (while (>= (setq n (1- n)) 0)
6063 (org-demote))
6064 (end-of-line 1))))))
6067 (defun org-convert-to-oddeven-levels ()
6068 "Convert an org-mode file with only odd levels to one with odd and even levels.
6069 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6070 section with an even level, conversion would destroy the structure of the file. An error
6071 is signaled in this case."
6072 (interactive)
6073 (goto-char (point-min))
6074 ;; First check if there are no even levels
6075 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6076 (org-show-context t)
6077 (error "Not all levels are odd in this file. Conversion not possible."))
6078 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6079 (let ((org-odd-levels-only nil) n)
6080 (save-excursion
6081 (goto-char (point-min))
6082 (while (re-search-forward "^\\*\\*+ " nil t)
6083 (setq n (/ (1- (length (match-string 0))) 2))
6084 (while (>= (setq n (1- n)) 0)
6085 (org-promote))
6086 (end-of-line 1))))))
6088 (defun org-tr-level (n)
6089 "Make N odd if required."
6090 (if org-odd-levels-only (1+ (/ n 2)) n))
6092 ;;; Vertical tree motion, cutting and pasting of subtrees
6094 (defun org-move-subtree-up (&optional arg)
6095 "Move the current subtree up past ARG headlines of the same level."
6096 (interactive "p")
6097 (org-move-subtree-down (- (prefix-numeric-value arg))))
6099 (defun org-move-subtree-down (&optional arg)
6100 "Move the current subtree down past ARG headlines of the same level."
6101 (interactive "p")
6102 (setq arg (prefix-numeric-value arg))
6103 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6104 'outline-get-last-sibling))
6105 (ins-point (make-marker))
6106 (cnt (abs arg))
6107 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6108 ;; Select the tree
6109 (org-back-to-heading)
6110 (setq beg0 (point))
6111 (save-excursion
6112 (setq ne-beg (org-back-over-empty-lines))
6113 (setq beg (point)))
6114 (save-match-data
6115 (save-excursion (outline-end-of-heading)
6116 (setq folded (org-invisible-p)))
6117 (outline-end-of-subtree))
6118 (outline-next-heading)
6119 (setq ne-end (org-back-over-empty-lines))
6120 (setq end (point))
6121 (goto-char beg0)
6122 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6123 ;; include less whitespace
6124 (save-excursion
6125 (goto-char beg)
6126 (forward-line (- ne-beg ne-end))
6127 (setq beg (point))))
6128 ;; Find insertion point, with error handling
6129 (while (> cnt 0)
6130 (or (and (funcall movfunc) (looking-at outline-regexp))
6131 (progn (goto-char beg0)
6132 (error "Cannot move past superior level or buffer limit")))
6133 (setq cnt (1- cnt)))
6134 (if (> arg 0)
6135 ;; Moving forward - still need to move over subtree
6136 (progn (org-end-of-subtree t t)
6137 (save-excursion
6138 (org-back-over-empty-lines)
6139 (or (bolp) (newline)))))
6140 (setq ne-ins (org-back-over-empty-lines))
6141 (move-marker ins-point (point))
6142 (setq txt (buffer-substring beg end))
6143 (org-save-markers-in-region beg end)
6144 (delete-region beg end)
6145 (org-remove-empty-overlays-at beg)
6146 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6147 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6148 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6149 (let ((bbb (point)))
6150 (insert-before-markers txt)
6151 (org-reinstall-markers-in-region bbb)
6152 (move-marker ins-point bbb))
6153 (or (bolp) (insert "\n"))
6154 (setq ins-end (point))
6155 (goto-char ins-point)
6156 (org-skip-whitespace)
6157 (when (and (< arg 0)
6158 (org-first-sibling-p)
6159 (> ne-ins ne-beg))
6160 ;; Move whitespace back to beginning
6161 (save-excursion
6162 (goto-char ins-end)
6163 (let ((kill-whole-line t))
6164 (kill-line (- ne-ins ne-beg)) (point)))
6165 (insert (make-string (- ne-ins ne-beg) ?\n)))
6166 (move-marker ins-point nil)
6167 (if folded
6168 (hide-subtree)
6169 (org-show-entry)
6170 (show-children)
6171 (org-cycle-hide-drawers 'children))
6172 (org-clean-visibility-after-subtree-move)))
6174 (defvar org-subtree-clip ""
6175 "Clipboard for cut and paste of subtrees.
6176 This is actually only a copy of the kill, because we use the normal kill
6177 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6179 (defvar org-subtree-clip-folded nil
6180 "Was the last copied subtree folded?
6181 This is used to fold the tree back after pasting.")
6183 (defun org-cut-subtree (&optional n)
6184 "Cut the current subtree into the clipboard.
6185 With prefix arg N, cut this many sequential subtrees.
6186 This is a short-hand for marking the subtree and then cutting it."
6187 (interactive "p")
6188 (org-copy-subtree n 'cut))
6190 (defun org-copy-subtree (&optional n cut force-store-markers)
6191 "Cut the current subtree into the clipboard.
6192 With prefix arg N, cut this many sequential subtrees.
6193 This is a short-hand for marking the subtree and then copying it.
6194 If CUT is non-nil, actually cut the subtree.
6195 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6196 of some markers in the region, even if CUT is non-nil. This is
6197 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6198 (interactive "p")
6199 (let (beg end folded (beg0 (point)))
6200 (if (interactive-p)
6201 (org-back-to-heading nil) ; take what looks like a subtree
6202 (org-back-to-heading t)) ; take what is really there
6203 (org-back-over-empty-lines)
6204 (setq beg (point))
6205 (skip-chars-forward " \t\r\n")
6206 (save-match-data
6207 (save-excursion (outline-end-of-heading)
6208 (setq folded (org-invisible-p)))
6209 (condition-case nil
6210 (org-forward-same-level (1- n) t)
6211 (error nil))
6212 (org-end-of-subtree t t))
6213 (org-back-over-empty-lines)
6214 (setq end (point))
6215 (goto-char beg0)
6216 (when (> end beg)
6217 (setq org-subtree-clip-folded folded)
6218 (when (or cut force-store-markers)
6219 (org-save-markers-in-region beg end))
6220 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6221 (setq org-subtree-clip (current-kill 0))
6222 (message "%s: Subtree(s) with %d characters"
6223 (if cut "Cut" "Copied")
6224 (length org-subtree-clip)))))
6226 (defun org-paste-subtree (&optional level tree for-yank)
6227 "Paste the clipboard as a subtree, with modification of headline level.
6228 The entire subtree is promoted or demoted in order to match a new headline
6229 level.
6231 If the cursor is at the beginning of a headline, the same level as
6232 that headline is used to paste the tree
6234 If not, the new level is derived from the *visible* headings
6235 before and after the insertion point, and taken to be the inferior headline
6236 level of the two. So if the previous visible heading is level 3 and the
6237 next is level 4 (or vice versa), level 4 will be used for insertion.
6238 This makes sure that the subtree remains an independent subtree and does
6239 not swallow low level entries.
6241 You can also force a different level, either by using a numeric prefix
6242 argument, or by inserting the heading marker by hand. For example, if the
6243 cursor is after \"*****\", then the tree will be shifted to level 5.
6245 If optional TREE is given, use this text instead of the kill ring.
6247 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6248 move back over whitespace before inserting, and move point to the end of
6249 the inserted text when done."
6250 (interactive "P")
6251 (setq tree (or tree (and kill-ring (current-kill 0))))
6252 (unless (org-kill-is-subtree-p tree)
6253 (error "%s"
6254 (substitute-command-keys
6255 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6256 (let* ((visp (not (org-invisible-p)))
6257 (txt tree)
6258 (^re (concat "^\\(" outline-regexp "\\)"))
6259 (re (concat "\\(" outline-regexp "\\)"))
6260 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6262 (old-level (if (string-match ^re txt)
6263 (- (match-end 0) (match-beginning 0) 1)
6264 -1))
6265 (force-level (cond (level (prefix-numeric-value level))
6266 ((and (looking-at "[ \t]*$")
6267 (string-match
6268 ^re_ (buffer-substring
6269 (point-at-bol) (point))))
6270 (- (match-end 1) (match-beginning 1)))
6271 ((and (bolp)
6272 (looking-at org-outline-regexp))
6273 (- (match-end 0) (point) 1))
6274 (t nil)))
6275 (previous-level (save-excursion
6276 (condition-case nil
6277 (progn
6278 (outline-previous-visible-heading 1)
6279 (if (looking-at re)
6280 (- (match-end 0) (match-beginning 0) 1)
6282 (error 1))))
6283 (next-level (save-excursion
6284 (condition-case nil
6285 (progn
6286 (or (looking-at outline-regexp)
6287 (outline-next-visible-heading 1))
6288 (if (looking-at re)
6289 (- (match-end 0) (match-beginning 0) 1)
6291 (error 1))))
6292 (new-level (or force-level (max previous-level next-level)))
6293 (shift (if (or (= old-level -1)
6294 (= new-level -1)
6295 (= old-level new-level))
6297 (- new-level old-level)))
6298 (delta (if (> shift 0) -1 1))
6299 (func (if (> shift 0) 'org-demote 'org-promote))
6300 (org-odd-levels-only nil)
6301 beg end newend)
6302 ;; Remove the forced level indicator
6303 (if force-level
6304 (delete-region (point-at-bol) (point)))
6305 ;; Paste
6306 (beginning-of-line 1)
6307 (unless for-yank (org-back-over-empty-lines))
6308 (setq beg (point))
6309 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6310 (insert-before-markers txt)
6311 (unless (string-match "\n\\'" txt) (insert "\n"))
6312 (setq newend (point))
6313 (org-reinstall-markers-in-region beg)
6314 (setq end (point))
6315 (goto-char beg)
6316 (skip-chars-forward " \t\n\r")
6317 (setq beg (point))
6318 (if (and (org-invisible-p) visp)
6319 (save-excursion (outline-show-heading)))
6320 ;; Shift if necessary
6321 (unless (= shift 0)
6322 (save-restriction
6323 (narrow-to-region beg end)
6324 (while (not (= shift 0))
6325 (org-map-region func (point-min) (point-max))
6326 (setq shift (+ delta shift)))
6327 (goto-char (point-min))
6328 (setq newend (point-max))))
6329 (when (or (interactive-p) for-yank)
6330 (message "Clipboard pasted as level %d subtree" new-level))
6331 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6332 kill-ring
6333 (eq org-subtree-clip (current-kill 0))
6334 org-subtree-clip-folded)
6335 ;; The tree was folded before it was killed/copied
6336 (hide-subtree))
6337 (and for-yank (goto-char newend))))
6339 (defun org-kill-is-subtree-p (&optional txt)
6340 "Check if the current kill is an outline subtree, or a set of trees.
6341 Returns nil if kill does not start with a headline, or if the first
6342 headline level is not the largest headline level in the tree.
6343 So this will actually accept several entries of equal levels as well,
6344 which is OK for `org-paste-subtree'.
6345 If optional TXT is given, check this string instead of the current kill."
6346 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6347 (start-level (and kill
6348 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6349 org-outline-regexp "\\)")
6350 kill)
6351 (- (match-end 2) (match-beginning 2) 1)))
6352 (re (concat "^" org-outline-regexp))
6353 (start (1+ (or (match-beginning 2) -1))))
6354 (if (not start-level)
6355 (progn
6356 nil) ;; does not even start with a heading
6357 (catch 'exit
6358 (while (setq start (string-match re kill (1+ start)))
6359 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6360 (throw 'exit nil)))
6361 t))))
6363 (defvar org-markers-to-move nil
6364 "Markers that should be moved with a cut-and-paste operation.
6365 Those markers are stored together with their positions relative to
6366 the start of the region.")
6368 (defun org-save-markers-in-region (beg end)
6369 "Check markers in region.
6370 If these markers are between BEG and END, record their position relative
6371 to BEG, so that after moving the block of text, we can put the markers back
6372 into place.
6373 This function gets called just before an entry or tree gets cut from the
6374 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6375 called immediately, to move the markers with the entries."
6376 (setq org-markers-to-move nil)
6377 (when (featurep 'org-clock)
6378 (org-clock-save-markers-for-cut-and-paste beg end))
6379 (when (featurep 'org-agenda)
6380 (org-agenda-save-markers-for-cut-and-paste beg end)))
6382 (defun org-check-and-save-marker (marker beg end)
6383 "Check if MARKER is between BEG and END.
6384 If yes, remember the marker and the distance to BEG."
6385 (when (and (marker-buffer marker)
6386 (equal (marker-buffer marker) (current-buffer)))
6387 (if (and (>= marker beg) (< marker end))
6388 (push (cons marker (- marker beg)) org-markers-to-move))))
6390 (defun org-reinstall-markers-in-region (beg)
6391 "Move all remembered markers to their position relative to BEG."
6392 (mapc (lambda (x)
6393 (move-marker (car x) (+ beg (cdr x))))
6394 org-markers-to-move)
6395 (setq org-markers-to-move nil))
6397 (defun org-narrow-to-subtree ()
6398 "Narrow buffer to the current subtree."
6399 (interactive)
6400 (save-excursion
6401 (save-match-data
6402 (narrow-to-region
6403 (progn (org-back-to-heading t) (point))
6404 (progn (org-end-of-subtree t) (point))))))
6406 (defun org-clone-subtree-with-time-shift (n &optional shift)
6407 "Clone the task (subtree) at point N times.
6408 The clones will be inserted as siblings.
6410 In interactive use, the user will be prompted for the number of clones
6411 to be produced, and for a time SHIFT, which may be a repeater as used
6412 in time stamps, for example `+3d'.
6414 When a valid repeater is given and the entry contains any time stamps,
6415 the clones will become a sequence in time, with time stamps in the
6416 subtree shifted for each clone produced. If SHIFT is nil or the
6417 empty string, time stamps will be left alone.
6419 If the original subtree did contain time stamps with a repeater,
6420 the following will happen:
6421 - the repeater will be removed in each clone
6422 - an additional clone will be produced, with the current, unshifted
6423 date(s) in the entry.
6424 - the original entry will be placed *after* all the clones, with
6425 repeater intact.
6426 - the start days in the repeater in the original entry will be shifted
6427 to past the last clone.
6428 I this way you can spell out a number of instances of a repeating task,
6429 and still retain the repeater to cover future instances of the task."
6430 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6431 (let (beg end template task
6432 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6433 (if (not (and (integerp n) (> n 0)))
6434 (error "Invalid number of replications %s" n))
6435 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6436 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6437 shift)))
6438 (error "Invalid shift specification %s" shift))
6439 (when doshift
6440 (setq shift-n (string-to-number (match-string 1 shift))
6441 shift-what (cdr (assoc (match-string 2 shift)
6442 '(("d" . day) ("w" . week)
6443 ("m" . month) ("y" . year))))))
6444 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6445 (setq nmin 1 nmax n)
6446 (org-back-to-heading t)
6447 (setq beg (point))
6448 (org-end-of-subtree t t)
6449 (setq end (point))
6450 (setq template (buffer-substring beg end))
6451 (when (and doshift
6452 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6453 (delete-region beg end)
6454 (setq end beg)
6455 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6456 (goto-char end)
6457 (loop for n from nmin to nmax do
6458 (if (not doshift)
6459 (setq task template)
6460 (with-temp-buffer
6461 (insert template)
6462 (org-mode)
6463 (goto-char (point-min))
6464 (while (re-search-forward org-ts-regexp-both nil t)
6465 (org-timestamp-change (* n shift-n) shift-what))
6466 (unless (= n n-no-remove)
6467 (goto-char (point-min))
6468 (while (re-search-forward org-ts-regexp nil t)
6469 (save-excursion
6470 (goto-char (match-beginning 0))
6471 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6472 (delete-region (match-beginning 1) (match-end 1))))))
6473 (setq task (buffer-string))))
6474 (insert task))
6475 (goto-char beg)))
6477 ;;; Outline Sorting
6479 (defun org-sort (with-case)
6480 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6481 Optional argument WITH-CASE means sort case-sensitively.
6482 With a double prefix argument, also remove duplicate entries."
6483 (interactive "P")
6484 (if (org-at-table-p)
6485 (org-call-with-arg 'org-table-sort-lines with-case)
6486 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6488 (defun org-sort-remove-invisible (s)
6489 (remove-text-properties 0 (length s) org-rm-props s)
6490 (while (string-match org-bracket-link-regexp s)
6491 (setq s (replace-match (if (match-end 2)
6492 (match-string 3 s)
6493 (match-string 1 s)) t t s)))
6496 (defvar org-priority-regexp) ; defined later in the file
6498 (defvar org-after-sorting-entries-or-items-hook nil
6499 "Hook that is run after a bunch of entries or items have been sorted.
6500 When children are sorted, the cursor is in the parent line when this
6501 hook gets called. When a region or a plain list is sorted, the cursor
6502 will be in the first entry of the sorted region/list.")
6504 (defun org-sort-entries-or-items
6505 (&optional with-case sorting-type getkey-func compare-func property)
6506 "Sort entries on a certain level of an outline tree, or plain list items.
6507 If there is an active region, the entries in the region are sorted.
6508 Else, if the cursor is before the first entry, sort the top-level items.
6509 Else, the children of the entry at point are sorted.
6510 If the cursor is at the first item in a plain list, the list items will be
6511 sorted.
6513 Sorting can be alphabetically, numerically, by date/time as given by
6514 a time stamp, by a property or by priority.
6516 The command prompts for the sorting type unless it has been given to the
6517 function through the SORTING-TYPE argument, which needs to a character,
6518 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6519 precise meaning of each character:
6521 n Numerically, by converting the beginning of the entry/item to a number.
6522 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6523 t By date/time, either the first active time stamp in the entry, or, if
6524 none exist, by the first inactive one.
6525 In items, only the first line will be chekced.
6526 s By the scheduled date/time.
6527 d By deadline date/time.
6528 c By creation time, which is assumed to be the first inactive time stamp
6529 at the beginning of a line.
6530 p By priority according to the cookie.
6531 r By the value of a property.
6533 Capital letters will reverse the sort order.
6535 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6536 called with point at the beginning of the record. It must return either
6537 a string or a number that should serve as the sorting key for that record.
6539 Comparing entries ignores case by default. However, with an optional argument
6540 WITH-CASE, the sorting considers case as well."
6541 (interactive "P")
6542 (let ((case-func (if with-case 'identity 'downcase))
6543 start beg end stars re re2
6544 txt what tmp plain-list-p)
6545 ;; Find beginning and end of region to sort
6546 (cond
6547 ((org-region-active-p)
6548 ;; we will sort the region
6549 (setq end (region-end)
6550 what "region")
6551 (goto-char (region-beginning))
6552 (if (not (org-on-heading-p)) (outline-next-heading))
6553 (setq start (point)))
6554 ((org-at-item-p)
6555 ;; we will sort this plain list
6556 (org-beginning-of-item-list) (setq start (point))
6557 (org-end-of-item-list) (setq end (point))
6558 (goto-char start)
6559 (setq plain-list-p t
6560 what "plain list"))
6561 ((or (org-on-heading-p)
6562 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6563 ;; we will sort the children of the current headline
6564 (org-back-to-heading)
6565 (setq start (point)
6566 end (progn (org-end-of-subtree t t)
6567 (org-back-over-empty-lines)
6568 (point))
6569 what "children")
6570 (goto-char start)
6571 (show-subtree)
6572 (outline-next-heading))
6574 ;; we will sort the top-level entries in this file
6575 (goto-char (point-min))
6576 (or (org-on-heading-p) (outline-next-heading))
6577 (setq start (point) end (point-max) what "top-level")
6578 (goto-char start)
6579 (show-all)))
6581 (setq beg (point))
6582 (if (>= beg end) (error "Nothing to sort"))
6584 (unless plain-list-p
6585 (looking-at "\\(\\*+\\)")
6586 (setq stars (match-string 1)
6587 re (concat "^" (regexp-quote stars) " +")
6588 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6589 txt (buffer-substring beg end))
6590 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6591 (if (and (not (equal stars "*")) (string-match re2 txt))
6592 (error "Region to sort contains a level above the first entry")))
6594 (unless sorting-type
6595 (message
6596 (if plain-list-p
6597 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6598 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6599 [t]ime [s]cheduled [d]eadline [c]reated
6600 A/N/T/S/D/C/P/O/F means reversed:")
6601 what)
6602 (setq sorting-type (read-char-exclusive))
6604 (and (= (downcase sorting-type) ?f)
6605 (setq getkey-func
6606 (org-icompleting-read "Sort using function: "
6607 obarray 'fboundp t nil nil))
6608 (setq getkey-func (intern getkey-func)))
6610 (and (= (downcase sorting-type) ?r)
6611 (setq property
6612 (org-icompleting-read "Property: "
6613 (mapcar 'list (org-buffer-property-keys t))
6614 nil t))))
6616 (message "Sorting entries...")
6618 (save-restriction
6619 (narrow-to-region start end)
6621 (let ((dcst (downcase sorting-type))
6622 (case-fold-search nil)
6623 (now (current-time)))
6624 (sort-subr
6625 (/= dcst sorting-type)
6626 ;; This function moves to the beginning character of the "record" to
6627 ;; be sorted.
6628 (if plain-list-p
6629 (lambda nil
6630 (if (org-at-item-p) t (goto-char (point-max))))
6631 (lambda nil
6632 (if (re-search-forward re nil t)
6633 (goto-char (match-beginning 0))
6634 (goto-char (point-max)))))
6635 ;; This function moves to the last character of the "record" being
6636 ;; sorted.
6637 (if plain-list-p
6638 'org-end-of-item
6639 (lambda nil
6640 (save-match-data
6641 (condition-case nil
6642 (outline-forward-same-level 1)
6643 (error
6644 (goto-char (point-max)))))))
6646 ;; This function returns the value that gets sorted against.
6647 (if plain-list-p
6648 (lambda nil
6649 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6650 (cond
6651 ((= dcst ?n)
6652 (string-to-number (buffer-substring (match-end 0)
6653 (point-at-eol))))
6654 ((= dcst ?a)
6655 (buffer-substring (match-end 0) (point-at-eol)))
6656 ((= dcst ?t)
6657 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6658 (re-search-forward org-ts-regexp-both
6659 (point-at-eol) t))
6660 (org-time-string-to-seconds (match-string 0))
6661 (time-to-seconds now)))
6662 ((= dcst ?f)
6663 (if getkey-func
6664 (progn
6665 (setq tmp (funcall getkey-func))
6666 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6667 tmp)
6668 (error "Invalid key function `%s'" getkey-func)))
6669 (t (error "Invalid sorting type `%c'" sorting-type)))))
6670 (lambda nil
6671 (cond
6672 ((= dcst ?n)
6673 (if (looking-at org-complex-heading-regexp)
6674 (string-to-number (match-string 4))
6675 nil))
6676 ((= dcst ?a)
6677 (if (looking-at org-complex-heading-regexp)
6678 (funcall case-func (match-string 4))
6679 nil))
6680 ((= dcst ?t)
6681 (let ((end (save-excursion (outline-next-heading) (point))))
6682 (if (or (re-search-forward org-ts-regexp end t)
6683 (re-search-forward org-ts-regexp-both end t))
6684 (org-time-string-to-seconds (match-string 0))
6685 (time-to-seconds now))))
6686 ((= dcst ?c)
6687 (let ((end (save-excursion (outline-next-heading) (point))))
6688 (if (re-search-forward
6689 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6690 end t)
6691 (org-time-string-to-seconds (match-string 0))
6692 (time-to-seconds now))))
6693 ((= dcst ?s)
6694 (let ((end (save-excursion (outline-next-heading) (point))))
6695 (if (re-search-forward org-scheduled-time-regexp end t)
6696 (org-time-string-to-seconds (match-string 1))
6697 (time-to-seconds now))))
6698 ((= dcst ?d)
6699 (let ((end (save-excursion (outline-next-heading) (point))))
6700 (if (re-search-forward org-deadline-time-regexp end t)
6701 (org-time-string-to-seconds (match-string 1))
6702 (time-to-seconds now))))
6703 ((= dcst ?p)
6704 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6705 (string-to-char (match-string 2))
6706 org-default-priority))
6707 ((= dcst ?r)
6708 (or (org-entry-get nil property) ""))
6709 ((= dcst ?o)
6710 (if (looking-at org-complex-heading-regexp)
6711 (- 9999 (length (member (match-string 2)
6712 org-todo-keywords-1)))))
6713 ((= dcst ?f)
6714 (if getkey-func
6715 (progn
6716 (setq tmp (funcall getkey-func))
6717 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6718 tmp)
6719 (error "Invalid key function `%s'" getkey-func)))
6720 (t (error "Invalid sorting type `%c'" sorting-type)))))
6722 (cond
6723 ((= dcst ?a) 'string<)
6724 ((= dcst ?f) compare-func)
6725 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6726 (t nil)))))
6727 (run-hooks 'org-after-sorting-entries-or-items-hook)
6728 (message "Sorting entries...done")))
6730 (defun org-do-sort (table what &optional with-case sorting-type)
6731 "Sort TABLE of WHAT according to SORTING-TYPE.
6732 The user will be prompted for the SORTING-TYPE if the call to this
6733 function does not specify it. WHAT is only for the prompt, to indicate
6734 what is being sorted. The sorting key will be extracted from
6735 the car of the elements of the table.
6736 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6737 (unless sorting-type
6738 (message
6739 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6740 what)
6741 (setq sorting-type (read-char-exclusive)))
6742 (let ((dcst (downcase sorting-type))
6743 extractfun comparefun)
6744 ;; Define the appropriate functions
6745 (cond
6746 ((= dcst ?n)
6747 (setq extractfun 'string-to-number
6748 comparefun (if (= dcst sorting-type) '< '>)))
6749 ((= dcst ?a)
6750 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6751 (lambda(x) (downcase (org-sort-remove-invisible x))))
6752 comparefun (if (= dcst sorting-type)
6753 'string<
6754 (lambda (a b) (and (not (string< a b))
6755 (not (string= a b)))))))
6756 ((= dcst ?t)
6757 (setq extractfun
6758 (lambda (x)
6759 (if (or (string-match org-ts-regexp x)
6760 (string-match org-ts-regexp-both x))
6761 (time-to-seconds
6762 (org-time-string-to-time (match-string 0 x)))
6764 comparefun (if (= dcst sorting-type) '< '>)))
6765 (t (error "Invalid sorting type `%c'" sorting-type)))
6767 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6768 table)
6769 (lambda (a b) (funcall comparefun (car a) (car b))))))
6772 ;;; The orgstruct minor mode
6774 ;; Define a minor mode which can be used in other modes in order to
6775 ;; integrate the org-mode structure editing commands.
6777 ;; This is really a hack, because the org-mode structure commands use
6778 ;; keys which normally belong to the major mode. Here is how it
6779 ;; works: The minor mode defines all the keys necessary to operate the
6780 ;; structure commands, but wraps the commands into a function which
6781 ;; tests if the cursor is currently at a headline or a plain list
6782 ;; item. If that is the case, the structure command is used,
6783 ;; temporarily setting many Org-mode variables like regular
6784 ;; expressions for filling etc. However, when any of those keys is
6785 ;; used at a different location, function uses `key-binding' to look
6786 ;; up if the key has an associated command in another currently active
6787 ;; keymap (minor modes, major mode, global), and executes that
6788 ;; command. There might be problems if any of the keys is otherwise
6789 ;; used as a prefix key.
6791 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6792 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6793 ;; addresses this by checking explicitly for both bindings.
6795 (defvar orgstruct-mode-map (make-sparse-keymap)
6796 "Keymap for the minor `orgstruct-mode'.")
6798 (defvar org-local-vars nil
6799 "List of local variables, for use by `orgstruct-mode'")
6801 ;;;###autoload
6802 (define-minor-mode orgstruct-mode
6803 "Toggle the minor more `orgstruct-mode'.
6804 This mode is for using Org-mode structure commands in other modes.
6805 The following key behave as if Org-mode was active, if the cursor
6806 is on a headline, or on a plain list item (both in the definition
6807 of Org-mode).
6809 M-up Move entry/item up
6810 M-down Move entry/item down
6811 M-left Promote
6812 M-right Demote
6813 M-S-up Move entry/item up
6814 M-S-down Move entry/item down
6815 M-S-left Promote subtree
6816 M-S-right Demote subtree
6817 M-q Fill paragraph and items like in Org-mode
6818 C-c ^ Sort entries
6819 C-c - Cycle list bullet
6820 TAB Cycle item visibility
6821 M-RET Insert new heading/item
6822 S-M-RET Insert new TODO heading / Checkbox item
6823 C-c C-c Set tags / toggle checkbox"
6824 nil " OrgStruct" nil
6825 (org-load-modules-maybe)
6826 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6828 ;;;###autoload
6829 (defun turn-on-orgstruct ()
6830 "Unconditionally turn on `orgstruct-mode'."
6831 (orgstruct-mode 1))
6833 (defun orgstruct++-mode (&optional arg)
6834 "Toggle `orgstruct-mode', the enhanced version of it.
6835 In addition to setting orgstruct-mode, this also exports all indentation
6836 and autofilling variables from org-mode into the buffer. It will also
6837 recognize item context in multiline items.
6838 Note that turning off orgstruct-mode will *not* remove the
6839 indentation/paragraph settings. This can only be done by refreshing the
6840 major mode, for example with \\[normal-mode]."
6841 (interactive "P")
6842 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6843 (if (< arg 1)
6844 (orgstruct-mode -1)
6845 (orgstruct-mode 1)
6846 (let (var val)
6847 (mapc
6848 (lambda (x)
6849 (when (string-match
6850 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6851 (symbol-name (car x)))
6852 (setq var (car x) val (nth 1 x))
6853 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6854 org-local-vars)
6855 (org-set-local 'orgstruct-is-++ t))))
6857 (defvar orgstruct-is-++ nil
6858 "Is orgstruct-mode in ++ version in the current-buffer?")
6859 (make-variable-buffer-local 'orgstruct-is-++)
6861 ;;;###autoload
6862 (defun turn-on-orgstruct++ ()
6863 "Unconditionally turn on `orgstruct++-mode'."
6864 (orgstruct++-mode 1))
6866 (defun orgstruct-error ()
6867 "Error when there is no default binding for a structure key."
6868 (interactive)
6869 (error "This key has no function outside structure elements"))
6871 (defun orgstruct-setup ()
6872 "Setup orgstruct keymaps."
6873 (let ((nfunc 0)
6874 (bindings
6875 (list
6876 '([(meta up)] org-metaup)
6877 '([(meta down)] org-metadown)
6878 '([(meta left)] org-metaleft)
6879 '([(meta right)] org-metaright)
6880 '([(meta shift up)] org-shiftmetaup)
6881 '([(meta shift down)] org-shiftmetadown)
6882 '([(meta shift left)] org-shiftmetaleft)
6883 '([(meta shift right)] org-shiftmetaright)
6884 '([?\e (up)] org-metaup)
6885 '([?\e (down)] org-metadown)
6886 '([?\e (left)] org-metaleft)
6887 '([?\e (right)] org-metaright)
6888 '([?\e (shift up)] org-shiftmetaup)
6889 '([?\e (shift down)] org-shiftmetadown)
6890 '([?\e (shift left)] org-shiftmetaleft)
6891 '([?\e (shift right)] org-shiftmetaright)
6892 '([(shift up)] org-shiftup)
6893 '([(shift down)] org-shiftdown)
6894 '([(shift left)] org-shiftleft)
6895 '([(shift right)] org-shiftright)
6896 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6897 '("\M-q" fill-paragraph)
6898 '("\C-c^" org-sort)
6899 '("\C-c-" org-cycle-list-bullet)))
6900 elt key fun cmd)
6901 (while (setq elt (pop bindings))
6902 (setq nfunc (1+ nfunc))
6903 (setq key (org-key (car elt))
6904 fun (nth 1 elt)
6905 cmd (orgstruct-make-binding fun nfunc key))
6906 (org-defkey orgstruct-mode-map key cmd))
6908 ;; Special treatment needed for TAB and RET
6909 (org-defkey orgstruct-mode-map [(tab)]
6910 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6911 (org-defkey orgstruct-mode-map "\C-i"
6912 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6914 (org-defkey orgstruct-mode-map "\M-\C-m"
6915 (orgstruct-make-binding 'org-insert-heading 105
6916 "\M-\C-m" [(meta return)]))
6917 (org-defkey orgstruct-mode-map [(meta return)]
6918 (orgstruct-make-binding 'org-insert-heading 106
6919 [(meta return)] "\M-\C-m"))
6921 (org-defkey orgstruct-mode-map [(shift meta return)]
6922 (orgstruct-make-binding 'org-insert-todo-heading 107
6923 [(meta return)] "\M-\C-m"))
6925 (org-defkey orgstruct-mode-map "\e\C-m"
6926 (orgstruct-make-binding 'org-insert-heading 108
6927 "\e\C-m" [?\e (return)]))
6928 (org-defkey orgstruct-mode-map [?\e (return)]
6929 (orgstruct-make-binding 'org-insert-heading 109
6930 [?\e (return)] "\e\C-m"))
6931 (org-defkey orgstruct-mode-map [?\e (shift return)]
6932 (orgstruct-make-binding 'org-insert-todo-heading 110
6933 [?\e (return)] "\e\C-m"))
6935 (unless org-local-vars
6936 (setq org-local-vars (org-get-local-variables)))
6940 (defun orgstruct-make-binding (fun n &rest keys)
6941 "Create a function for binding in the structure minor mode.
6942 FUN is the command to call inside a table. N is used to create a unique
6943 command name. KEYS are keys that should be checked in for a command
6944 to execute outside of tables."
6945 (eval
6946 (list 'defun
6947 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6948 '(arg)
6949 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6950 "Outside of structure, run the binding of `"
6951 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6952 "'.")
6953 '(interactive "p")
6954 (list 'if
6955 `(org-context-p 'headline 'item
6956 (and orgstruct-is-++
6957 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6958 'item-body))
6959 (list 'org-run-like-in-org-mode (list 'quote fun))
6960 (list 'let '(orgstruct-mode)
6961 (list 'call-interactively
6962 (append '(or)
6963 (mapcar (lambda (k)
6964 (list 'key-binding k))
6965 keys)
6966 '('orgstruct-error))))))))
6968 (defun org-context-p (&rest contexts)
6969 "Check if local context is any of CONTEXTS.
6970 Possible values in the list of contexts are `table', `headline', and `item'."
6971 (let ((pos (point)))
6972 (goto-char (point-at-bol))
6973 (prog1 (or (and (memq 'table contexts)
6974 (looking-at "[ \t]*|"))
6975 (and (memq 'headline contexts)
6976 ;;????????? (looking-at "\\*+"))
6977 (looking-at outline-regexp))
6978 (and (memq 'item contexts)
6979 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6980 (and (memq 'item-body contexts)
6981 (org-in-item-p)))
6982 (goto-char pos))))
6984 (defun org-get-local-variables ()
6985 "Return a list of all local variables in an org-mode buffer."
6986 (let (varlist)
6987 (with-current-buffer (get-buffer-create "*Org tmp*")
6988 (erase-buffer)
6989 (org-mode)
6990 (setq varlist (buffer-local-variables)))
6991 (kill-buffer "*Org tmp*")
6992 (delq nil
6993 (mapcar
6994 (lambda (x)
6995 (setq x
6996 (if (symbolp x)
6997 (list x)
6998 (list (car x) (list 'quote (cdr x)))))
6999 (if (string-match
7000 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7001 (symbol-name (car x)))
7002 x nil))
7003 varlist))))
7005 ;;;###autoload
7006 (defun org-run-like-in-org-mode (cmd)
7007 "Run a command, pretending that the current buffer is in Org-mode.
7008 This will temporarily bind local variables that are typically bound in
7009 Org-mode to the values they have in Org-mode, and then interactively
7010 call CMD."
7011 (org-load-modules-maybe)
7012 (unless org-local-vars
7013 (setq org-local-vars (org-get-local-variables)))
7014 (eval (list 'let org-local-vars
7015 (list 'call-interactively (list 'quote cmd)))))
7017 ;;;; Archiving
7019 (defun org-get-category (&optional pos)
7020 "Get the category applying to position POS."
7021 (get-text-property (or pos (point)) 'org-category))
7023 (defun org-refresh-category-properties ()
7024 "Refresh category text properties in the buffer."
7025 (let ((def-cat (cond
7026 ((null org-category)
7027 (if buffer-file-name
7028 (file-name-sans-extension
7029 (file-name-nondirectory buffer-file-name))
7030 "???"))
7031 ((symbolp org-category) (symbol-name org-category))
7032 (t org-category)))
7033 beg end cat pos optionp)
7034 (org-unmodified
7035 (save-excursion
7036 (save-restriction
7037 (widen)
7038 (goto-char (point-min))
7039 (put-text-property (point) (point-max) 'org-category def-cat)
7040 (while (re-search-forward
7041 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7042 (setq pos (match-end 0)
7043 optionp (equal (char-after (match-beginning 0)) ?#)
7044 cat (org-trim (match-string 2)))
7045 (if optionp
7046 (setq beg (point-at-bol) end (point-max))
7047 (org-back-to-heading t)
7048 (setq beg (point) end (org-end-of-subtree t t)))
7049 (put-text-property beg end 'org-category cat)
7050 (goto-char pos)))))))
7053 ;;;; Link Stuff
7055 ;;; Link abbreviations
7057 (defun org-link-expand-abbrev (link)
7058 "Apply replacements as defined in `org-link-abbrev-alist."
7059 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7060 (let* ((key (match-string 1 link))
7061 (as (or (assoc key org-link-abbrev-alist-local)
7062 (assoc key org-link-abbrev-alist)))
7063 (tag (and (match-end 2) (match-string 3 link)))
7064 rpl)
7065 (if (not as)
7066 link
7067 (setq rpl (cdr as))
7068 (cond
7069 ((symbolp rpl) (funcall rpl tag))
7070 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7071 ((string-match "%h" rpl)
7072 (replace-match (url-hexify-string (or tag "")) t t rpl))
7073 (t (concat rpl tag)))))
7074 link))
7076 ;;; Storing and inserting links
7078 (defvar org-insert-link-history nil
7079 "Minibuffer history for links inserted with `org-insert-link'.")
7081 (defvar org-stored-links nil
7082 "Contains the links stored with `org-store-link'.")
7084 (defvar org-store-link-plist nil
7085 "Plist with info about the most recently link created with `org-store-link'.")
7087 (defvar org-link-protocols nil
7088 "Link protocols added to Org-mode using `org-add-link-type'.")
7090 (defvar org-store-link-functions nil
7091 "List of functions that are called to create and store a link.
7092 Each function will be called in turn until one returns a non-nil
7093 value. Each function should check if it is responsible for creating
7094 this link (for example by looking at the major mode).
7095 If not, it must exit and return nil.
7096 If yes, it should return a non-nil value after a calling
7097 `org-store-link-props' with a list of properties and values.
7098 Special properties are:
7100 :type The link prefix. like \"http\". This must be given.
7101 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7102 This is obligatory as well.
7103 :description Optional default description for the second pair
7104 of brackets in an Org-mode link. The user can still change
7105 this when inserting this link into an Org-mode buffer.
7107 In addition to these, any additional properties can be specified
7108 and then used in remember templates.")
7110 (defun org-add-link-type (type &optional follow export)
7111 "Add TYPE to the list of `org-link-types'.
7112 Re-compute all regular expressions depending on `org-link-types'
7114 FOLLOW and EXPORT are two functions.
7116 FOLLOW should take the link path as the single argument and do whatever
7117 is necessary to follow the link, for example find a file or display
7118 a mail message.
7120 EXPORT should format the link path for export to one of the export formats.
7121 It should be a function accepting three arguments:
7123 path the path of the link, the text after the prefix (like \"http:\")
7124 desc the description of the link, if any, nil if there was no description
7125 format the export format, a symbol like `html' or `latex'.
7127 The function may use the FORMAT information to return different values
7128 depending on the format. The return value will be put literally into
7129 the exported file.
7130 Org-mode has a built-in default for exporting links. If you are happy with
7131 this default, there is no need to define an export function for the link
7132 type. For a simple example of an export function, see `org-bbdb.el'."
7133 (add-to-list 'org-link-types type t)
7134 (org-make-link-regexps)
7135 (if (assoc type org-link-protocols)
7136 (setcdr (assoc type org-link-protocols) (list follow export))
7137 (push (list type follow export) org-link-protocols)))
7139 ;;;###autoload
7140 (defun org-store-link (arg)
7141 "\\<org-mode-map>Store an org-link to the current location.
7142 This link is added to `org-stored-links' and can later be inserted
7143 into an org-buffer with \\[org-insert-link].
7145 For some link types, a prefix arg is interpreted:
7146 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7147 For file links, arg negates `org-context-in-file-links'."
7148 (interactive "P")
7149 (org-load-modules-maybe)
7150 (setq org-store-link-plist nil) ; reset
7151 (let ((outline-regexp (org-get-limited-outline-regexp))
7152 link cpltxt desc description search txt custom-id)
7153 (cond
7155 ((run-hook-with-args-until-success 'org-store-link-functions)
7156 (setq link (plist-get org-store-link-plist :link)
7157 desc (or (plist-get org-store-link-plist :description) link)))
7159 ((equal (buffer-name) "*Org Edit Src Example*")
7160 (let (label gc)
7161 (while (or (not label)
7162 (save-excursion
7163 (save-restriction
7164 (widen)
7165 (goto-char (point-min))
7166 (re-search-forward
7167 (regexp-quote (format org-coderef-label-format label))
7168 nil t))))
7169 (when label (message "Label exists already") (sit-for 2))
7170 (setq label (read-string "Code line label: " label)))
7171 (end-of-line 1)
7172 (setq link (format org-coderef-label-format label))
7173 (setq gc (- 79 (length link)))
7174 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7175 (insert link)
7176 (setq link (concat "(" label ")") desc nil)))
7178 ((eq major-mode 'calendar-mode)
7179 (let ((cd (calendar-cursor-to-date)))
7180 (setq link
7181 (format-time-string
7182 (car org-time-stamp-formats)
7183 (apply 'encode-time
7184 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7185 nil nil nil))))
7186 (org-store-link-props :type "calendar" :date cd)))
7188 ((eq major-mode 'w3-mode)
7189 (setq cpltxt (if (and (buffer-name)
7190 (not (string-match "Untitled" (buffer-name))))
7191 (buffer-name)
7192 (url-view-url t))
7193 link (org-make-link (url-view-url t)))
7194 (org-store-link-props :type "w3" :url (url-view-url t)))
7196 ((eq major-mode 'w3m-mode)
7197 (setq cpltxt (or w3m-current-title w3m-current-url)
7198 link (org-make-link w3m-current-url))
7199 (org-store-link-props :type "w3m" :url (url-view-url t)))
7201 ((setq search (run-hook-with-args-until-success
7202 'org-create-file-search-functions))
7203 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7204 "::" search))
7205 (setq cpltxt (or description link)))
7207 ((eq major-mode 'image-mode)
7208 (setq cpltxt (concat "file:"
7209 (abbreviate-file-name buffer-file-name))
7210 link (org-make-link cpltxt))
7211 (org-store-link-props :type "image" :file buffer-file-name))
7213 ((eq major-mode 'dired-mode)
7214 ;; link to the file in the current line
7215 (setq cpltxt (concat "file:"
7216 (abbreviate-file-name
7217 (expand-file-name
7218 (dired-get-filename nil t))))
7219 link (org-make-link cpltxt)))
7221 ((and buffer-file-name (org-mode-p))
7222 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7223 (cond
7224 ((org-in-regexp "<<\\(.*?\\)>>")
7225 (setq cpltxt
7226 (concat "file:"
7227 (abbreviate-file-name buffer-file-name)
7228 "::" (match-string 1))
7229 link (org-make-link cpltxt)))
7230 ((and (featurep 'org-id)
7231 (or (eq org-link-to-org-use-id t)
7232 (and (eq org-link-to-org-use-id 'create-if-interactive)
7233 (interactive-p))
7234 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7235 (interactive-p)
7236 (not custom-id))
7237 (and org-link-to-org-use-id
7238 (condition-case nil
7239 (org-entry-get nil "ID")
7240 (error nil)))))
7241 ;; We can make a link using the ID.
7242 (setq link (condition-case nil
7243 (prog1 (org-id-store-link)
7244 (setq desc (plist-get org-store-link-plist
7245 :description)))
7246 (error
7247 ;; probably before first headline, link to file only
7248 (concat "file:"
7249 (abbreviate-file-name buffer-file-name))))))
7251 ;; Just link to current headline
7252 (setq cpltxt (concat "file:"
7253 (abbreviate-file-name buffer-file-name)))
7254 ;; Add a context search string
7255 (when (org-xor org-context-in-file-links arg)
7256 (setq txt (cond
7257 ((org-on-heading-p) nil)
7258 ((org-region-active-p)
7259 (buffer-substring (region-beginning) (region-end)))
7260 (t nil)))
7261 (when (or (null txt) (string-match "\\S-" txt))
7262 (setq cpltxt
7263 (concat cpltxt "::"
7264 (condition-case nil
7265 (org-make-org-heading-search-string txt)
7266 (error "")))
7267 desc (or (nth 4 (org-heading-components)) "NONE"))))
7268 (if (string-match "::\\'" cpltxt)
7269 (setq cpltxt (substring cpltxt 0 -2)))
7270 (setq link (org-make-link cpltxt)))))
7272 ((buffer-file-name (buffer-base-buffer))
7273 ;; Just link to this file here.
7274 (setq cpltxt (concat "file:"
7275 (abbreviate-file-name
7276 (buffer-file-name (buffer-base-buffer)))))
7277 ;; Add a context string
7278 (when (org-xor org-context-in-file-links arg)
7279 (setq txt (if (org-region-active-p)
7280 (buffer-substring (region-beginning) (region-end))
7281 (buffer-substring (point-at-bol) (point-at-eol))))
7282 ;; Only use search option if there is some text.
7283 (when (string-match "\\S-" txt)
7284 (setq cpltxt
7285 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7286 desc "NONE")))
7287 (setq link (org-make-link cpltxt)))
7289 ((interactive-p)
7290 (error "Cannot link to a buffer which is not visiting a file"))
7292 (t (setq link nil)))
7294 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7295 (setq link (or link cpltxt)
7296 desc (or desc cpltxt))
7297 (if (equal desc "NONE") (setq desc nil))
7299 (if (and (or (interactive-p) executing-kbd-macro) link)
7300 (progn
7301 (setq org-stored-links
7302 (cons (list link desc) org-stored-links))
7303 (message "Stored: %s" (or desc link))
7304 (when custom-id
7305 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7306 "::#" custom-id))
7307 (setq org-stored-links
7308 (cons (list link desc) org-stored-links))))
7309 (and link (org-make-link-string link desc)))))
7311 (defun org-store-link-props (&rest plist)
7312 "Store link properties, extract names and addresses."
7313 (let (x adr)
7314 (when (setq x (plist-get plist :from))
7315 (setq adr (mail-extract-address-components x))
7316 (setq plist (plist-put plist :fromname (car adr)))
7317 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7318 (when (setq x (plist-get plist :to))
7319 (setq adr (mail-extract-address-components x))
7320 (setq plist (plist-put plist :toname (car adr)))
7321 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7322 (let ((from (plist-get plist :from))
7323 (to (plist-get plist :to)))
7324 (when (and from to org-from-is-user-regexp)
7325 (setq plist
7326 (plist-put plist :fromto
7327 (if (string-match org-from-is-user-regexp from)
7328 (concat "to %t")
7329 (concat "from %f"))))))
7330 (setq org-store-link-plist plist))
7332 (defun org-add-link-props (&rest plist)
7333 "Add these properties to the link property list."
7334 (let (key value)
7335 (while plist
7336 (setq key (pop plist) value (pop plist))
7337 (setq org-store-link-plist
7338 (plist-put org-store-link-plist key value)))))
7340 (defun org-email-link-description (&optional fmt)
7341 "Return the description part of an email link.
7342 This takes information from `org-store-link-plist' and formats it
7343 according to FMT (default from `org-email-link-description-format')."
7344 (setq fmt (or fmt org-email-link-description-format))
7345 (let* ((p org-store-link-plist)
7346 (to (plist-get p :toaddress))
7347 (from (plist-get p :fromaddress))
7348 (table
7349 (list
7350 (cons "%c" (plist-get p :fromto))
7351 (cons "%F" (plist-get p :from))
7352 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7353 (cons "%T" (plist-get p :to))
7354 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7355 (cons "%s" (plist-get p :subject))
7356 (cons "%m" (plist-get p :message-id)))))
7357 (when (string-match "%c" fmt)
7358 ;; Check if the user wrote this message
7359 (if (and org-from-is-user-regexp from to
7360 (save-match-data (string-match org-from-is-user-regexp from)))
7361 (setq fmt (replace-match "to %t" t t fmt))
7362 (setq fmt (replace-match "from %f" t t fmt))))
7363 (org-replace-escapes fmt table)))
7365 (defun org-make-org-heading-search-string (&optional string heading)
7366 "Make search string for STRING or current headline."
7367 (interactive)
7368 (let ((s (or string (org-get-heading))))
7369 (unless (and string (not heading))
7370 ;; We are using a headline, clean up garbage in there.
7371 (if (string-match org-todo-regexp s)
7372 (setq s (replace-match "" t t s)))
7373 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7374 (setq s (replace-match "" t t s)))
7375 (setq s (org-trim s))
7376 (if (string-match (concat "^\\(" org-quote-string "\\|"
7377 org-comment-string "\\)") s)
7378 (setq s (replace-match "" t t s)))
7379 (while (string-match org-ts-regexp s)
7380 (setq s (replace-match "" t t s))))
7381 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7382 (setq s (replace-match " " t t s)))
7383 (or string (setq s (concat "*" s))) ; Add * for headlines
7384 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7386 (defun org-make-link (&rest strings)
7387 "Concatenate STRINGS."
7388 (apply 'concat strings))
7390 (defun org-make-link-string (link &optional description)
7391 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7392 (unless (string-match "\\S-" link)
7393 (error "Empty link"))
7394 (when (stringp description)
7395 ;; Remove brackets from the description, they are fatal.
7396 (while (string-match "\\[" description)
7397 (setq description (replace-match "{" t t description)))
7398 (while (string-match "\\]" description)
7399 (setq description (replace-match "}" t t description))))
7400 (when (equal (org-link-escape link) description)
7401 ;; No description needed, it is identical
7402 (setq description nil))
7403 (when (and (not description)
7404 (not (equal link (org-link-escape link))))
7405 (setq description (org-extract-attributes link)))
7406 (concat "[[" (org-link-escape link) "]"
7407 (if description (concat "[" description "]") "")
7408 "]"))
7410 (defconst org-link-escape-chars
7411 '((?\ . "%20")
7412 (?\[ . "%5B")
7413 (?\] . "%5D")
7414 (?\340 . "%E0") ; `a
7415 (?\342 . "%E2") ; ^a
7416 (?\347 . "%E7") ; ,c
7417 (?\350 . "%E8") ; `e
7418 (?\351 . "%E9") ; 'e
7419 (?\352 . "%EA") ; ^e
7420 (?\356 . "%EE") ; ^i
7421 (?\364 . "%F4") ; ^o
7422 (?\371 . "%F9") ; `u
7423 (?\373 . "%FB") ; ^u
7424 (?\; . "%3B")
7425 (?? . "%3F")
7426 (?= . "%3D")
7427 (?+ . "%2B")
7429 "Association list of escapes for some characters problematic in links.
7430 This is the list that is used for internal purposes.")
7432 (defvar org-url-encoding-use-url-hexify nil)
7434 (defconst org-link-escape-chars-browser
7435 '((?\ . "%20")) ; 32 for the SPC char
7436 "Association list of escapes for some characters problematic in links.
7437 This is the list that is used before handing over to the browser.")
7439 (defun org-link-escape (text &optional table)
7440 "Escape characters in TEXT that are problematic for links."
7441 (if org-url-encoding-use-url-hexify
7442 (url-hexify-string text)
7443 (setq table (or table org-link-escape-chars))
7444 (when text
7445 (let ((re (mapconcat (lambda (x) (regexp-quote
7446 (char-to-string (car x))))
7447 table "\\|")))
7448 (while (string-match re text)
7449 (setq text
7450 (replace-match
7451 (cdr (assoc (string-to-char (match-string 0 text))
7452 table))
7453 t t text)))
7454 text))))
7456 (defun org-link-unescape (text &optional table)
7457 "Reverse the action of `org-link-escape'."
7458 (if org-url-encoding-use-url-hexify
7459 (url-unhex-string text)
7460 (setq table (or table org-link-escape-chars))
7461 (when text
7462 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7463 table "\\|")))
7464 (while (string-match re text)
7465 (setq text
7466 (replace-match
7467 (char-to-string (car (rassoc (match-string 0 text) table)))
7468 t t text)))
7469 text))))
7471 (defun org-xor (a b)
7472 "Exclusive or."
7473 (if a (not b) b))
7475 (defun org-fixup-message-id-for-http (s)
7476 "Replace special characters in a message id, so it can be used in an http query."
7477 (while (string-match "<" s)
7478 (setq s (replace-match "%3C" t t s)))
7479 (while (string-match ">" s)
7480 (setq s (replace-match "%3E" t t s)))
7481 (while (string-match "@" s)
7482 (setq s (replace-match "%40" t t s)))
7485 ;;;###autoload
7486 (defun org-insert-link-global ()
7487 "Insert a link like Org-mode does.
7488 This command can be called in any mode to insert a link in Org-mode syntax."
7489 (interactive)
7490 (org-load-modules-maybe)
7491 (org-run-like-in-org-mode 'org-insert-link))
7493 (defun org-insert-link (&optional complete-file link-location)
7494 "Insert a link. At the prompt, enter the link.
7496 Completion can be used to insert any of the link protocol prefixes like
7497 http or ftp in use.
7499 The history can be used to select a link previously stored with
7500 `org-store-link'. When the empty string is entered (i.e. if you just
7501 press RET at the prompt), the link defaults to the most recently
7502 stored link. As SPC triggers completion in the minibuffer, you need to
7503 use M-SPC or C-q SPC to force the insertion of a space character.
7505 You will also be prompted for a description, and if one is given, it will
7506 be displayed in the buffer instead of the link.
7508 If there is already a link at point, this command will allow you to edit link
7509 and description parts.
7511 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7512 be selected using completion. The path to the file will be relative to the
7513 current directory if the file is in the current directory or a subdirectory.
7514 Otherwise, the link will be the absolute path as completed in the minibuffer
7515 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7516 option `org-link-file-path-type'.
7518 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7519 the current directory or below.
7521 With three \\[universal-argument] prefixes, negate the meaning of
7522 `org-keep-stored-link-after-insertion'.
7524 If `org-make-link-description-function' is non-nil, this function will be
7525 called with the link target, and the result will be the default
7526 link description.
7528 If the LINK-LOCATION parameter is non-nil, this value will be
7529 used as the link location instead of reading one interactively."
7530 (interactive "P")
7531 (let* ((wcf (current-window-configuration))
7532 (region (if (org-region-active-p)
7533 (buffer-substring (region-beginning) (region-end))))
7534 (remove (and region (list (region-beginning) (region-end))))
7535 (desc region)
7536 tmphist ; byte-compile incorrectly complains about this
7537 (link link-location)
7538 entry file all-prefixes)
7539 (cond
7540 (link-location) ; specified by arg, just use it.
7541 ((org-in-regexp org-bracket-link-regexp 1)
7542 ;; We do have a link at point, and we are going to edit it.
7543 (setq remove (list (match-beginning 0) (match-end 0)))
7544 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7545 (setq link (read-string "Link: "
7546 (org-link-unescape
7547 (org-match-string-no-properties 1)))))
7548 ((or (org-in-regexp org-angle-link-re)
7549 (org-in-regexp org-plain-link-re))
7550 ;; Convert to bracket link
7551 (setq remove (list (match-beginning 0) (match-end 0))
7552 link (read-string "Link: "
7553 (org-remove-angle-brackets (match-string 0)))))
7554 ((member complete-file '((4) (16)))
7555 ;; Completing read for file names.
7556 (setq link (org-file-complete-link complete-file)))
7558 ;; Read link, with completion for stored links.
7559 (with-output-to-temp-buffer "*Org Links*"
7560 (princ "Insert a link.
7561 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7562 (when org-stored-links
7563 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7564 (princ (mapconcat
7565 (lambda (x)
7566 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7567 (reverse org-stored-links) "\n"))))
7568 (let ((cw (selected-window)))
7569 (select-window (get-buffer-window "*Org Links*"))
7570 (setq truncate-lines t)
7571 (unless (pos-visible-in-window-p (point-max))
7572 (org-fit-window-to-buffer))
7573 (and (window-live-p cw) (select-window cw)))
7574 ;; Fake a link history, containing the stored links.
7575 (setq tmphist (append (mapcar 'car org-stored-links)
7576 org-insert-link-history))
7577 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7578 (mapcar 'car org-link-abbrev-alist)
7579 org-link-types))
7580 (unwind-protect
7581 (progn
7582 (setq link
7583 (let ((org-completion-use-ido nil)
7584 (org-completion-use-iswitchb nil))
7585 (org-completing-read
7586 "Link: "
7587 (append
7588 (mapcar (lambda (x) (list (concat x ":")))
7589 all-prefixes)
7590 (mapcar 'car org-stored-links))
7591 nil nil nil
7592 'tmphist
7593 (car (car org-stored-links)))))
7594 (if (or (member link all-prefixes)
7595 (and (equal ":" (substring link -1))
7596 (member (substring link 0 -1) all-prefixes)
7597 (setq link (substring link 0 -1))))
7598 (setq link (org-link-try-special-completion link))))
7599 (set-window-configuration wcf)
7600 (kill-buffer "*Org Links*"))
7601 (setq entry (assoc link org-stored-links))
7602 (or entry (push link org-insert-link-history))
7603 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7604 (not org-keep-stored-link-after-insertion))
7605 (setq org-stored-links (delq (assoc link org-stored-links)
7606 org-stored-links)))
7607 (setq desc (or desc (nth 1 entry)))))
7609 (if (string-match org-plain-link-re link)
7610 ;; URL-like link, normalize the use of angular brackets.
7611 (setq link (org-make-link (org-remove-angle-brackets link))))
7613 ;; Check if we are linking to the current file with a search option
7614 ;; If yes, simplify the link by using only the search option.
7615 (when (and buffer-file-name
7616 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7617 (let* ((path (match-string 1 link))
7618 (case-fold-search nil)
7619 (search (match-string 2 link)))
7620 (save-match-data
7621 (if (equal (file-truename buffer-file-name) (file-truename path))
7622 ;; We are linking to this same file, with a search option
7623 (setq link search)))))
7625 ;; Check if we can/should use a relative path. If yes, simplify the link
7626 (when (string-match "^file:\\(.*\\)" link)
7627 (let* ((path (match-string 1 link))
7628 (origpath path)
7629 (case-fold-search nil))
7630 (cond
7631 ((or (eq org-link-file-path-type 'absolute)
7632 (equal complete-file '(16)))
7633 (setq path (abbreviate-file-name (expand-file-name path))))
7634 ((eq org-link-file-path-type 'noabbrev)
7635 (setq path (expand-file-name path)))
7636 ((eq org-link-file-path-type 'relative)
7637 (setq path (file-relative-name path)))
7639 (save-match-data
7640 (if (string-match (concat "^" (regexp-quote
7641 (file-name-as-directory
7642 (expand-file-name "."))))
7643 (expand-file-name path))
7644 ;; We are linking a file with relative path name.
7645 (setq path (substring (expand-file-name path)
7646 (match-end 0)))
7647 (setq path (abbreviate-file-name (expand-file-name path)))))))
7648 (setq link (concat "file:" path))
7649 (if (equal desc origpath)
7650 (setq desc path))))
7652 (if org-make-link-description-function
7653 (setq desc (funcall org-make-link-description-function link desc)))
7655 (setq desc (read-string "Description: " desc))
7656 (unless (string-match "\\S-" desc) (setq desc nil))
7657 (if remove (apply 'delete-region remove))
7658 (insert (org-make-link-string link desc))))
7660 (defun org-link-try-special-completion (type)
7661 "If there is completion support for link type TYPE, offer it."
7662 (let ((fun (intern (concat "org-" type "-complete-link"))))
7663 (if (functionp fun)
7664 (funcall fun)
7665 (read-string "Link (no completion support): " (concat type ":")))))
7667 (defun org-file-complete-link (&optional arg)
7668 "Create a file link using completion."
7669 (let (file link)
7670 (setq file (read-file-name "File: "))
7671 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7672 (pwd1 (file-name-as-directory (abbreviate-file-name
7673 (expand-file-name ".")))))
7674 (cond
7675 ((equal arg '(16))
7676 (setq link (org-make-link
7677 "file:"
7678 (abbreviate-file-name (expand-file-name file)))))
7679 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7680 (setq link (org-make-link "file:" (match-string 1 file))))
7681 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7682 (expand-file-name file))
7683 (setq link (org-make-link
7684 "file:" (match-string 1 (expand-file-name file)))))
7685 (t (setq link (org-make-link "file:" file)))))
7686 link))
7688 (defun org-completing-read (&rest args)
7689 "Completing-read with SPACE being a normal character."
7690 (let ((minibuffer-local-completion-map
7691 (copy-keymap minibuffer-local-completion-map)))
7692 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7693 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7694 (apply 'org-icompleting-read args)))
7696 (defun org-completing-read-no-i (&rest args)
7697 (let (org-completion-use-ido org-completion-use-iswitchb)
7698 (apply 'org-completing-read args)))
7700 (defun org-iswitchb-completing-read (prompt choices &rest args)
7701 "Use iswitch as a completing-read replacement to choose from choices.
7702 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7703 from."
7704 (let ((iswitchb-make-buflist-hook
7705 (lambda ()
7706 (setq iswitchb-temp-buflist choices))))
7707 (iswitchb-read-buffer prompt)))
7709 (defun org-icompleting-read (&rest args)
7710 "Completing-read using `ido-mode' or `iswitchb' speedups if available"
7711 (if (and org-completion-use-ido
7712 (fboundp 'ido-completing-read)
7713 (boundp 'ido-mode) ido-mode
7714 (listp (second args)))
7715 (let ((ido-enter-matching-directory nil))
7716 (apply 'ido-completing-read (concat (car args))
7717 (if (consp (car (nth 1 args)))
7718 (mapcar (lambda (x) (car x)) (nth 1 args))
7719 (nth 1 args))
7720 (cddr args)))
7721 (if (and org-completion-use-iswitchb
7722 (boundp 'iswitchb-mode) iswitchb-mode
7723 (listp (second args)))
7724 (apply 'org-iswitchb-completing-read (concat (car args))
7725 (mapcar (lambda (x) (car x)) (nth 1 args))
7726 (cddr args))
7727 (apply 'completing-read args))))
7729 (defun org-extract-attributes (s)
7730 "Extract the attributes cookie from a string and set as text property."
7731 (let (a attr (start 0) key value)
7732 (save-match-data
7733 (when (string-match "{{\\([^}]+\\)}}$" s)
7734 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7735 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7736 (setq key (match-string 1 a) value (match-string 2 a)
7737 start (match-end 0)
7738 attr (plist-put attr (intern key) value))))
7739 (org-add-props s nil 'org-attr attr))
7742 (defun org-extract-attributes-from-string (tag)
7743 (let (key value attr)
7744 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7745 (setq key (match-string 1 tag) value (match-string 2 tag)
7746 tag (replace-match "" t t tag)
7747 attr (plist-put attr (intern key) value)))
7748 (cons tag attr)))
7750 (defun org-attributes-to-string (plist)
7751 "Format a property list into an HTML attribute list."
7752 (let ((s "") key value)
7753 (while plist
7754 (setq key (pop plist) value (pop plist))
7755 (and value
7756 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7759 ;;; Opening/following a link
7761 (defvar org-link-search-failed nil)
7763 (defun org-next-link ()
7764 "Move forward to the next link.
7765 If the link is in hidden text, expose it."
7766 (interactive)
7767 (when (and org-link-search-failed (eq this-command last-command))
7768 (goto-char (point-min))
7769 (message "Link search wrapped back to beginning of buffer"))
7770 (setq org-link-search-failed nil)
7771 (let* ((pos (point))
7772 (ct (org-context))
7773 (a (assoc :link ct)))
7774 (if a (goto-char (nth 2 a)))
7775 (if (re-search-forward org-any-link-re nil t)
7776 (progn
7777 (goto-char (match-beginning 0))
7778 (if (org-invisible-p) (org-show-context)))
7779 (goto-char pos)
7780 (setq org-link-search-failed t)
7781 (error "No further link found"))))
7783 (defun org-previous-link ()
7784 "Move backward to the previous link.
7785 If the link is in hidden text, expose it."
7786 (interactive)
7787 (when (and org-link-search-failed (eq this-command last-command))
7788 (goto-char (point-max))
7789 (message "Link search wrapped back to end of buffer"))
7790 (setq org-link-search-failed nil)
7791 (let* ((pos (point))
7792 (ct (org-context))
7793 (a (assoc :link ct)))
7794 (if a (goto-char (nth 1 a)))
7795 (if (re-search-backward org-any-link-re nil t)
7796 (progn
7797 (goto-char (match-beginning 0))
7798 (if (org-invisible-p) (org-show-context)))
7799 (goto-char pos)
7800 (setq org-link-search-failed t)
7801 (error "No further link found"))))
7803 (defun org-translate-link (s)
7804 "Translate a link string if a translation function has been defined."
7805 (if (and org-link-translation-function
7806 (fboundp org-link-translation-function)
7807 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7808 (progn
7809 (setq s (funcall org-link-translation-function
7810 (match-string 1) (match-string 2)))
7811 (concat (car s) ":" (cdr s)))
7814 (defun org-translate-link-from-planner (type path)
7815 "Translate a link from Emacs Planner syntax so that Org can follow it.
7816 This is still an experimental function, your mileage may vary."
7817 (cond
7818 ((member type '("http" "https" "news" "ftp"))
7819 ;; standard Internet links are the same.
7820 nil)
7821 ((and (equal type "irc") (string-match "^//" path))
7822 ;; Planner has two / at the beginning of an irc link, we have 1.
7823 ;; We should have zero, actually....
7824 (setq path (substring path 1)))
7825 ((and (equal type "lisp") (string-match "^/" path))
7826 ;; Planner has a slash, we do not.
7827 (setq type "elisp" path (substring path 1)))
7828 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7829 ;; A typical message link. Planner has the id after the fina slash,
7830 ;; we separate it with a hash mark
7831 (setq path (concat (match-string 1 path) "#"
7832 (org-remove-angle-brackets (match-string 2 path)))))
7834 (cons type path))
7836 (defun org-find-file-at-mouse (ev)
7837 "Open file link or URL at mouse."
7838 (interactive "e")
7839 (mouse-set-point ev)
7840 (org-open-at-point 'in-emacs))
7842 (defun org-open-at-mouse (ev)
7843 "Open file link or URL at mouse."
7844 (interactive "e")
7845 (mouse-set-point ev)
7846 (if (eq major-mode 'org-agenda-mode)
7847 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7848 (org-open-at-point))
7850 (defvar org-window-config-before-follow-link nil
7851 "The window configuration before following a link.
7852 This is saved in case the need arises to restore it.")
7854 (defvar org-open-link-marker (make-marker)
7855 "Marker pointing to the location where `org-open-at-point; was called.")
7857 ;;;###autoload
7858 (defun org-open-at-point-global ()
7859 "Follow a link like Org-mode does.
7860 This command can be called in any mode to follow a link that has
7861 Org-mode syntax."
7862 (interactive)
7863 (org-run-like-in-org-mode 'org-open-at-point))
7865 ;;;###autoload
7866 (defun org-open-link-from-string (s &optional arg)
7867 "Open a link in the string S, as if it was in Org-mode."
7868 (interactive "sLink: \nP")
7869 (let ((reference-buffer (current-buffer)))
7870 (with-temp-buffer
7871 (let ((org-inhibit-startup t))
7872 (org-mode)
7873 (insert s)
7874 (goto-char (point-min))
7875 (org-open-at-point arg reference-buffer)))))
7877 (defun org-open-at-point (&optional in-emacs reference-buffer)
7878 "Open link at or after point.
7879 If there is no link at point, this function will search forward up to
7880 the end of the current line.
7881 Normally, files will be opened by an appropriate application. If the
7882 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7883 With a double prefix argument, try to open outside of Emacs, in the
7884 application the system uses for this file type."
7885 (interactive "P")
7886 (org-load-modules-maybe)
7887 (move-marker org-open-link-marker (point))
7888 (setq org-window-config-before-follow-link (current-window-configuration))
7889 (org-remove-occur-highlights nil nil t)
7890 (cond
7891 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7892 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7893 (org-footnote-action))
7895 (let (type path link line search (pos (point)))
7896 (catch 'match
7897 (save-excursion
7898 (skip-chars-forward "^]\n\r")
7899 (when (org-in-regexp org-bracket-link-regexp)
7900 (setq link (org-extract-attributes
7901 (org-link-unescape (org-match-string-no-properties 1))))
7902 (while (string-match " *\n *" link)
7903 (setq link (replace-match " " t t link)))
7904 (setq link (org-link-expand-abbrev link))
7905 (cond
7906 ((or (file-name-absolute-p link)
7907 (string-match "^\\.\\.?/" link))
7908 (setq type "file" path link))
7909 ((string-match org-link-re-with-space3 link)
7910 (setq type (match-string 1 link) path (match-string 2 link)))
7911 (t (setq type "thisfile" path link)))
7912 (throw 'match t)))
7914 (when (get-text-property (point) 'org-linked-text)
7915 (setq type "thisfile"
7916 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7917 (1+ (point)) (point))
7918 path (buffer-substring
7919 (previous-single-property-change pos 'org-linked-text)
7920 (next-single-property-change pos 'org-linked-text)))
7921 (throw 'match t))
7923 (save-excursion
7924 (when (or (org-in-regexp org-angle-link-re)
7925 (org-in-regexp org-plain-link-re))
7926 (setq type (match-string 1) path (match-string 2))
7927 (throw 'match t)))
7928 (save-excursion
7929 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7930 (setq type "tags"
7931 path (match-string 1))
7932 (while (string-match ":" path)
7933 (setq path (replace-match "+" t t path)))
7934 (throw 'match t)))
7935 (when (org-in-regexp "<\\([^><\n]+\\)>")
7936 (setq type "tree-match"
7937 path (match-string 1))
7938 (throw 'match t)))
7939 (unless path
7940 (error "No link found"))
7942 ;; switch back to reference buffer
7943 ;; needed when if called in a temporary buffer through
7944 ;; org-open-link-from-string
7945 (and reference-buffer (switch-to-buffer reference-buffer))
7947 ;; Remove any trailing spaces in path
7948 (if (string-match " +\\'" path)
7949 (setq path (replace-match "" t t path)))
7950 (if (and org-link-translation-function
7951 (fboundp org-link-translation-function))
7952 ;; Check if we need to translate the link
7953 (let ((tmp (funcall org-link-translation-function type path)))
7954 (setq type (car tmp) path (cdr tmp))))
7956 (cond
7958 ((assoc type org-link-protocols)
7959 (funcall (nth 1 (assoc type org-link-protocols)) path))
7961 ((equal type "mailto")
7962 (let ((cmd (car org-link-mailto-program))
7963 (args (cdr org-link-mailto-program)) args1
7964 (address path) (subject "") a)
7965 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7966 (setq address (match-string 1 path)
7967 subject (org-link-escape (match-string 2 path))))
7968 (while args
7969 (cond
7970 ((not (stringp (car args))) (push (pop args) args1))
7971 (t (setq a (pop args))
7972 (if (string-match "%a" a)
7973 (setq a (replace-match address t t a)))
7974 (if (string-match "%s" a)
7975 (setq a (replace-match subject t t a)))
7976 (push a args1))))
7977 (apply cmd (nreverse args1))))
7979 ((member type '("http" "https" "ftp" "news"))
7980 (browse-url (concat type ":" (org-link-escape
7981 path org-link-escape-chars-browser))))
7983 ((member type '("message"))
7984 (browse-url (concat type ":" path)))
7986 ((string= type "tags")
7987 (org-tags-view in-emacs path))
7988 ((string= type "thisfile")
7989 (if in-emacs
7990 (switch-to-buffer-other-window
7991 (org-get-buffer-for-internal-link (current-buffer)))
7992 (org-mark-ring-push))
7993 (let ((cmd `(org-link-search
7994 ,path
7995 ,(cond ((equal in-emacs '(4)) 'occur)
7996 ((equal in-emacs '(16)) 'org-occur)
7997 (t nil))
7998 ,pos)))
7999 (condition-case nil (eval cmd)
8000 (error (progn (widen) (eval cmd))))))
8002 ((string= type "tree-match")
8003 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8005 ((string= type "file")
8006 (if (string-match "::\\([0-9]+\\)\\'" path)
8007 (setq line (string-to-number (match-string 1 path))
8008 path (substring path 0 (match-beginning 0)))
8009 (if (string-match "::\\(.+\\)\\'" path)
8010 (setq search (match-string 1 path)
8011 path (substring path 0 (match-beginning 0)))))
8012 (if (string-match "[*?{]" (file-name-nondirectory path))
8013 (dired path)
8014 (org-open-file path in-emacs line search)))
8016 ((string= type "news")
8017 (require 'org-gnus)
8018 (org-gnus-follow-link path))
8020 ((string= type "shell")
8021 (let ((cmd path))
8022 (if (or (not org-confirm-shell-link-function)
8023 (funcall org-confirm-shell-link-function
8024 (format "Execute \"%s\" in shell? "
8025 (org-add-props cmd nil
8026 'face 'org-warning))))
8027 (progn
8028 (message "Executing %s" cmd)
8029 (shell-command cmd))
8030 (error "Abort"))))
8032 ((string= type "elisp")
8033 (let ((cmd path))
8034 (if (or (not org-confirm-elisp-link-function)
8035 (funcall org-confirm-elisp-link-function
8036 (format "Execute \"%s\" as elisp? "
8037 (org-add-props cmd nil
8038 'face 'org-warning))))
8039 (message "%s => %s" cmd
8040 (if (equal (string-to-char cmd) ?\()
8041 (eval (read cmd))
8042 (call-interactively (read cmd))))
8043 (error "Abort"))))
8046 (browse-url-at-point))))))
8047 (move-marker org-open-link-marker nil)
8048 (run-hook-with-args 'org-follow-link-hook))
8050 ;;;; Time estimates
8052 (defun org-get-effort (&optional pom)
8053 "Get the effort estimate for the current entry."
8054 (org-entry-get pom org-effort-property))
8056 ;;; File search
8058 (defvar org-create-file-search-functions nil
8059 "List of functions to construct the right search string for a file link.
8060 These functions are called in turn with point at the location to
8061 which the link should point.
8063 A function in the hook should first test if it would like to
8064 handle this file type, for example by checking the major-mode or
8065 the file extension. If it decides not to handle this file, it
8066 should just return nil to give other functions a chance. If it
8067 does handle the file, it must return the search string to be used
8068 when following the link. The search string will be part of the
8069 file link, given after a double colon, and `org-open-at-point'
8070 will automatically search for it. If special measures must be
8071 taken to make the search successful, another function should be
8072 added to the companion hook `org-execute-file-search-functions',
8073 which see.
8075 A function in this hook may also use `setq' to set the variable
8076 `description' to provide a suggestion for the descriptive text to
8077 be used for this link when it gets inserted into an Org-mode
8078 buffer with \\[org-insert-link].")
8080 (defvar org-execute-file-search-functions nil
8081 "List of functions to execute a file search triggered by a link.
8083 Functions added to this hook must accept a single argument, the
8084 search string that was part of the file link, the part after the
8085 double colon. The function must first check if it would like to
8086 handle this search, for example by checking the major-mode or the
8087 file extension. If it decides not to handle this search, it
8088 should just return nil to give other functions a chance. If it
8089 does handle the search, it must return a non-nil value to keep
8090 other functions from trying.
8092 Each function can access the current prefix argument through the
8093 variable `current-prefix-argument'. Note that a single prefix is
8094 used to force opening a link in Emacs, so it may be good to only
8095 use a numeric or double prefix to guide the search function.
8097 In case this is needed, a function in this hook can also restore
8098 the window configuration before `org-open-at-point' was called using:
8100 (set-window-configuration org-window-config-before-follow-link)")
8102 (defun org-link-search (s &optional type avoid-pos)
8103 "Search for a link search option.
8104 If S is surrounded by forward slashes, it is interpreted as a
8105 regular expression. In org-mode files, this will create an `org-occur'
8106 sparse tree. In ordinary files, `occur' will be used to list matches.
8107 If the current buffer is in `dired-mode', grep will be used to search
8108 in all files. If AVOID-POS is given, ignore matches near that position."
8109 (let ((case-fold-search t)
8110 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8111 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8112 (append '(("") (" ") ("\t") ("\n"))
8113 org-emphasis-alist)
8114 "\\|") "\\)"))
8115 (pos (point))
8116 (pre nil) (post nil)
8117 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8118 (cond
8119 ;; First check if there are any special
8120 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8121 ;; Now try the builtin stuff
8122 ((and (equal (string-to-char s0) ?#)
8123 (> (length s0) 1)
8124 (save-excursion
8125 (goto-char (point-min))
8126 (and
8127 (re-search-forward
8128 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8129 (setq type 'dedicated
8130 pos (match-beginning 0))))
8131 ;; There is an exact target for this
8132 (goto-char pos)
8133 (org-back-to-heading t)))
8134 ((save-excursion
8135 (goto-char (point-min))
8136 (and
8137 (re-search-forward
8138 (concat "<<" (regexp-quote s0) ">>") nil t)
8139 (setq type 'dedicated
8140 pos (match-beginning 0))))
8141 ;; There is an exact target for this
8142 (goto-char pos))
8143 ((and (string-match "^(\\(.*\\))$" s0)
8144 (save-excursion
8145 (goto-char (point-min))
8146 (and
8147 (re-search-forward
8148 (concat "[^[]" (regexp-quote
8149 (format org-coderef-label-format
8150 (match-string 1 s0))))
8151 nil t)
8152 (setq type 'dedicated
8153 pos (1+ (match-beginning 0))))))
8154 ;; There is a coderef target for this
8155 (goto-char pos))
8156 ((string-match "^/\\(.*\\)/$" s)
8157 ;; A regular expression
8158 (cond
8159 ((org-mode-p)
8160 (org-occur (match-string 1 s)))
8161 ;;((eq major-mode 'dired-mode)
8162 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8163 (t (org-do-occur (match-string 1 s)))))
8165 ;; A normal search strings
8166 (when (equal (string-to-char s) ?*)
8167 ;; Anchor on headlines, post may include tags.
8168 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8169 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8170 s (substring s 1)))
8171 (remove-text-properties
8172 0 (length s)
8173 '(face nil mouse-face nil keymap nil fontified nil) s)
8174 ;; Make a series of regular expressions to find a match
8175 (setq words (org-split-string s "[ \n\r\t]+")
8177 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8178 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8179 "\\)" markers)
8180 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8181 re2a (concat "[ \t\r\n]" re2a_)
8182 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8183 re4 (concat "[^a-zA-Z_]" re4_)
8185 re1 (concat pre re2 post)
8186 re3 (concat pre (if pre re4_ re4) post)
8187 re5 (concat pre ".*" re4)
8188 re2 (concat pre re2)
8189 re2a (concat pre (if pre re2a_ re2a))
8190 re4 (concat pre (if pre re4_ re4))
8191 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8192 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8193 re5 "\\)"
8195 (cond
8196 ((eq type 'org-occur) (org-occur reall))
8197 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8198 (t (goto-char (point-min))
8199 (setq type 'fuzzy)
8200 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8201 (org-search-not-self 1 re1 nil t)
8202 (org-search-not-self 1 re2 nil t)
8203 (org-search-not-self 1 re2a nil t)
8204 (org-search-not-self 1 re3 nil t)
8205 (org-search-not-self 1 re4 nil t)
8206 (org-search-not-self 1 re5 nil t)
8208 (goto-char (match-beginning 1))
8209 (goto-char pos)
8210 (error "No match")))))
8212 ;; Normal string-search
8213 (goto-char (point-min))
8214 (if (search-forward s nil t)
8215 (goto-char (match-beginning 0))
8216 (error "No match"))))
8217 (and (org-mode-p) (org-show-context 'link-search))
8218 type))
8220 (defun org-search-not-self (group &rest args)
8221 "Execute `re-search-forward', but only accept matches that do not
8222 enclose the position of `org-open-link-marker'."
8223 (let ((m org-open-link-marker))
8224 (catch 'exit
8225 (while (apply 're-search-forward args)
8226 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8227 (goto-char (match-end group))
8228 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8229 (> (match-beginning 0) (marker-position m))
8230 (< (match-end 0) (marker-position m)))
8231 (save-match-data
8232 (or (not (org-in-regexp
8233 org-bracket-link-analytic-regexp 1))
8234 (not (match-end 4)) ; no description
8235 (and (<= (match-beginning 4) (point))
8236 (>= (match-end 4) (point))))))
8237 (throw 'exit (point))))))))
8239 (defun org-get-buffer-for-internal-link (buffer)
8240 "Return a buffer to be used for displaying the link target of internal links."
8241 (cond
8242 ((not org-display-internal-link-with-indirect-buffer)
8243 buffer)
8244 ((string-match "(Clone)$" (buffer-name buffer))
8245 (message "Buffer is already a clone, not making another one")
8246 ;; we also do not modify visibility in this case
8247 buffer)
8248 (t ; make a new indirect buffer for displaying the link
8249 (let* ((bn (buffer-name buffer))
8250 (ibn (concat bn "(Clone)"))
8251 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8252 (with-current-buffer ib (org-overview))
8253 ib))))
8255 (defun org-do-occur (regexp &optional cleanup)
8256 "Call the Emacs command `occur'.
8257 If CLEANUP is non-nil, remove the printout of the regular expression
8258 in the *Occur* buffer. This is useful if the regex is long and not useful
8259 to read."
8260 (occur regexp)
8261 (when cleanup
8262 (let ((cwin (selected-window)) win beg end)
8263 (when (setq win (get-buffer-window "*Occur*"))
8264 (select-window win))
8265 (goto-char (point-min))
8266 (when (re-search-forward "match[a-z]+" nil t)
8267 (setq beg (match-end 0))
8268 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8269 (setq end (1- (match-beginning 0)))))
8270 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8271 (goto-char (point-min))
8272 (select-window cwin))))
8274 ;;; The mark ring for links jumps
8276 (defvar org-mark-ring nil
8277 "Mark ring for positions before jumps in Org-mode.")
8278 (defvar org-mark-ring-last-goto nil
8279 "Last position in the mark ring used to go back.")
8280 ;; Fill and close the ring
8281 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8282 (loop for i from 1 to org-mark-ring-length do
8283 (push (make-marker) org-mark-ring))
8284 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8285 org-mark-ring)
8287 (defun org-mark-ring-push (&optional pos buffer)
8288 "Put the current position or POS into the mark ring and rotate it."
8289 (interactive)
8290 (setq pos (or pos (point)))
8291 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8292 (move-marker (car org-mark-ring)
8293 (or pos (point))
8294 (or buffer (current-buffer)))
8295 (message "%s"
8296 (substitute-command-keys
8297 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8299 (defun org-mark-ring-goto (&optional n)
8300 "Jump to the previous position in the mark ring.
8301 With prefix arg N, jump back that many stored positions. When
8302 called several times in succession, walk through the entire ring.
8303 Org-mode commands jumping to a different position in the current file,
8304 or to another Org-mode file, automatically push the old position
8305 onto the ring."
8306 (interactive "p")
8307 (let (p m)
8308 (if (eq last-command this-command)
8309 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8310 (setq p org-mark-ring))
8311 (setq org-mark-ring-last-goto p)
8312 (setq m (car p))
8313 (switch-to-buffer (marker-buffer m))
8314 (goto-char m)
8315 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8317 (defun org-remove-angle-brackets (s)
8318 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8319 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8321 (defun org-add-angle-brackets (s)
8322 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8323 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8325 (defun org-remove-double-quotes (s)
8326 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8327 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8330 ;;; Following specific links
8332 (defun org-follow-timestamp-link ()
8333 (cond
8334 ((org-at-date-range-p t)
8335 (let ((org-agenda-start-on-weekday)
8336 (t1 (match-string 1))
8337 (t2 (match-string 2)))
8338 (setq t1 (time-to-days (org-time-string-to-time t1))
8339 t2 (time-to-days (org-time-string-to-time t2)))
8340 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8341 ((org-at-timestamp-p t)
8342 (org-agenda-list nil (time-to-days (org-time-string-to-time
8343 (substring (match-string 1) 0 10)))
8345 (t (error "This should not happen"))))
8348 ;;; Following file links
8349 (defvar org-wait nil)
8350 (defun org-open-file (path &optional in-emacs line search)
8351 "Open the file at PATH.
8352 First, this expands any special file name abbreviations. Then the
8353 configuration variable `org-file-apps' is checked if it contains an
8354 entry for this file type, and if yes, the corresponding command is launched.
8356 If no application is found, Emacs simply visits the file.
8358 With optional prefix argument IN-EMACS, Emacs will visit the file.
8359 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8360 and o use an external application to visit the file.
8362 Optional LINE specifies a line to go to, optional SEARCH a string to
8363 search for. If LINE or SEARCH is given, the file will always be
8364 opened in Emacs.
8365 If the file does not exist, an error is thrown."
8366 (setq in-emacs (or in-emacs line search))
8367 (let* ((file (if (equal path "")
8368 buffer-file-name
8369 (substitute-in-file-name (expand-file-name path))))
8370 (apps (append org-file-apps (org-default-apps)))
8371 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8372 (dirp (if remp nil (file-directory-p file)))
8373 (file (if (and dirp org-open-directory-means-index-dot-org)
8374 (concat (file-name-as-directory file) "index.org")
8375 file))
8376 (a-m-a-p (assq 'auto-mode apps))
8377 (dfile (downcase file))
8378 (old-buffer (current-buffer))
8379 (old-pos (point))
8380 (old-mode major-mode)
8381 ext cmd)
8382 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8383 (setq ext (match-string 1 dfile))
8384 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8385 (setq ext (match-string 1 dfile))))
8386 (cond
8387 ((equal in-emacs '(16))
8388 (setq cmd (cdr (assoc 'system apps))))
8389 (in-emacs (setq cmd 'emacs))
8391 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8392 (and dirp (cdr (assoc 'directory apps)))
8393 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8394 'string-match)
8395 (cdr (assoc ext apps))
8396 (cdr (assoc t apps))))))
8397 (when (eq cmd 'system)
8398 (setq cmd (cdr (assoc 'system apps))))
8399 (when (eq cmd 'default)
8400 (setq cmd (cdr (assoc t apps))))
8401 (when (eq cmd 'mailcap)
8402 (require 'mailcap)
8403 (mailcap-parse-mailcaps)
8404 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8405 (command (mailcap-mime-info mime-type)))
8406 (if (stringp command)
8407 (setq cmd command)
8408 (setq cmd 'emacs))))
8409 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8410 (not (file-exists-p file))
8411 (not org-open-non-existing-files))
8412 (error "No such file: %s" file))
8413 (cond
8414 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8415 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8416 (while (string-match "['\"]%s['\"]" cmd)
8417 (setq cmd (replace-match "%s" t t cmd)))
8418 (while (string-match "%s" cmd)
8419 (setq cmd (replace-match
8420 (save-match-data
8421 (shell-quote-argument
8422 (convert-standard-filename file)))
8423 t t cmd)))
8424 (save-window-excursion
8425 (start-process-shell-command cmd nil cmd)
8426 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8428 ((or (stringp cmd)
8429 (eq cmd 'emacs))
8430 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8431 (widen)
8432 (if line (org-goto-line line)
8433 (if search (org-link-search search))))
8434 ((consp cmd)
8435 (let ((file (convert-standard-filename file)))
8436 (eval cmd)))
8437 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8438 (and (org-mode-p) (eq old-mode 'org-mode)
8439 (or (not (equal old-buffer (current-buffer)))
8440 (not (equal old-pos (point))))
8441 (org-mark-ring-push old-pos old-buffer))))
8443 (defun org-default-apps ()
8444 "Return the default applications for this operating system."
8445 (cond
8446 ((eq system-type 'darwin)
8447 org-file-apps-defaults-macosx)
8448 ((eq system-type 'windows-nt)
8449 org-file-apps-defaults-windowsnt)
8450 (t org-file-apps-defaults-gnu)))
8452 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8453 "Convert extensions to regular expressions in the cars of LIST.
8454 Also, weed out any non-string entries, because the return value is used
8455 only for regexp matching.
8456 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8457 point to the symbol `emacs', indicating that the file should
8458 be opened in Emacs."
8459 (append
8460 (delq nil
8461 (mapcar (lambda (x)
8462 (if (not (stringp (car x)))
8464 (if (string-match "\\W" (car x))
8466 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8467 list))
8468 (if add-auto-mode
8469 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8471 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8472 (defun org-file-remote-p (file)
8473 "Test whether FILE specifies a location on a remote system.
8474 Return non-nil if the location is indeed remote.
8476 For example, the filename \"/user@host:/foo\" specifies a location
8477 on the system \"/user@host:\"."
8478 (cond ((fboundp 'file-remote-p)
8479 (file-remote-p file))
8480 ((fboundp 'tramp-handle-file-remote-p)
8481 (tramp-handle-file-remote-p file))
8482 ((and (boundp 'ange-ftp-name-format)
8483 (string-match (car ange-ftp-name-format) file))
8485 (t nil)))
8488 ;;;; Refiling
8490 (defun org-get-org-file ()
8491 "Read a filename, with default directory `org-directory'."
8492 (let ((default (or org-default-notes-file remember-data-file)))
8493 (read-file-name (format "File name [%s]: " default)
8494 (file-name-as-directory org-directory)
8495 default)))
8497 (defun org-notes-order-reversed-p ()
8498 "Check if the current file should receive notes in reversed order."
8499 (cond
8500 ((not org-reverse-note-order) nil)
8501 ((eq t org-reverse-note-order) t)
8502 ((not (listp org-reverse-note-order)) nil)
8503 (t (catch 'exit
8504 (let ((all org-reverse-note-order)
8505 entry)
8506 (while (setq entry (pop all))
8507 (if (string-match (car entry) buffer-file-name)
8508 (throw 'exit (cdr entry))))
8509 nil)))))
8511 (defvar org-refile-target-table nil
8512 "The list of refile targets, created by `org-refile'.")
8514 (defvar org-agenda-new-buffers nil
8515 "Buffers created to visit agenda files.")
8517 (defun org-get-refile-targets (&optional default-buffer)
8518 "Produce a table with refile targets."
8519 (let ((case-fold-search nil)
8520 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8521 (entries (or org-refile-targets '((nil . (:level . 1)))))
8522 targets txt re files f desc descre fast-path-p level pos0)
8523 (message "Getting targets...")
8524 (with-current-buffer (or default-buffer (current-buffer))
8525 (while (setq entry (pop entries))
8526 (setq files (car entry) desc (cdr entry))
8527 (setq fast-path-p nil)
8528 (cond
8529 ((null files) (setq files (list (current-buffer))))
8530 ((eq files 'org-agenda-files)
8531 (setq files (org-agenda-files 'unrestricted)))
8532 ((and (symbolp files) (fboundp files))
8533 (setq files (funcall files)))
8534 ((and (symbolp files) (boundp files))
8535 (setq files (symbol-value files))))
8536 (if (stringp files) (setq files (list files)))
8537 (cond
8538 ((eq (car desc) :tag)
8539 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8540 ((eq (car desc) :todo)
8541 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8542 ((eq (car desc) :regexp)
8543 (setq descre (cdr desc)))
8544 ((eq (car desc) :level)
8545 (setq descre (concat "^\\*\\{" (number-to-string
8546 (if org-odd-levels-only
8547 (1- (* 2 (cdr desc)))
8548 (cdr desc)))
8549 "\\}[ \t]")))
8550 ((eq (car desc) :maxlevel)
8551 (setq fast-path-p t)
8552 (setq descre (concat "^\\*\\{1," (number-to-string
8553 (if org-odd-levels-only
8554 (1- (* 2 (cdr desc)))
8555 (cdr desc)))
8556 "\\}[ \t]")))
8557 (t (error "Bad refiling target description %s" desc)))
8558 (while (setq f (pop files))
8559 (save-excursion
8560 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8561 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8562 (setq f (expand-file-name f))
8563 (if (eq org-refile-use-outline-path 'file)
8564 (push (list (file-name-nondirectory f) f nil nil) targets))
8565 (save-excursion
8566 (save-restriction
8567 (widen)
8568 (goto-char (point-min))
8569 (while (re-search-forward descre nil t)
8570 (goto-char (setq pos0 (point-at-bol)))
8571 (catch 'next
8572 (when org-refile-target-verify-function
8573 (save-match-data
8574 (or (funcall org-refile-target-verify-function)
8575 (throw 'next t))))
8576 (when (looking-at org-complex-heading-regexp)
8577 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8578 txt (org-link-display-format (match-string 4))
8579 re (concat "^" (regexp-quote
8580 (buffer-substring (match-beginning 1)
8581 (match-end 4)))))
8582 (if (match-end 5) (setq re (concat re "[ \t]+"
8583 (regexp-quote
8584 (match-string 5)))))
8585 (setq re (concat re "[ \t]*$"))
8586 (when org-refile-use-outline-path
8587 (setq txt (mapconcat 'org-protect-slash
8588 (append
8589 (if (eq org-refile-use-outline-path 'file)
8590 (list (file-name-nondirectory
8591 (buffer-file-name (buffer-base-buffer))))
8592 (if (eq org-refile-use-outline-path 'full-file-path)
8593 (list (buffer-file-name (buffer-base-buffer)))))
8594 (org-get-outline-path fast-path-p level txt)
8595 (list txt))
8596 "/")))
8597 (push (list txt f re (point)) targets)))
8598 (when (= (point) pos0)
8599 ;; verification function has not moved point
8600 (goto-char (point-at-eol))))))))))
8601 (message "Getting targets...done")
8602 (nreverse targets)))
8604 (defun org-protect-slash (s)
8605 (while (string-match "/" s)
8606 (setq s (replace-match "\\" t t s)))
8609 (defvar org-olpa (make-vector 20 nil))
8611 (defun org-get-outline-path (&optional fastp level heading)
8612 "Return the outline path to the current entry, as a list."
8613 (if fastp
8614 (progn
8615 (if (> level 19)
8616 (error "Outline path failure, more than 19 levels."))
8617 (loop for i from level upto 19 do
8618 (aset org-olpa i nil))
8619 (prog1
8620 (delq nil (append org-olpa nil))
8621 (aset org-olpa level heading)))
8622 (let (rtn)
8623 (save-excursion
8624 (while (org-up-heading-safe)
8625 (when (looking-at org-complex-heading-regexp)
8626 (push (org-match-string-no-properties 4) rtn)))
8627 rtn))))
8629 (defvar org-refile-history nil
8630 "History for refiling operations.")
8632 (defvar org-after-refile-insert-hook nil
8633 "Hook run after `org-refile' has inserted its stuff at the new location.
8634 Note that this is still *before* the stuff will be removed from
8635 the *old* location.")
8637 (defun org-refile (&optional goto default-buffer rfloc)
8638 "Move the entry at point to another heading.
8639 The list of target headings is compiled using the information in
8640 `org-refile-targets', which see. This list is created before each use
8641 and will therefore always be up-to-date.
8643 At the target location, the entry is filed as a subitem of the target heading.
8644 Depending on `org-reverse-note-order', the new subitem will either be the
8645 first or the last subitem.
8647 If there is an active region, all entries in that region will be moved.
8648 However, the region must fulfil the requirement that the first heading
8649 is the first one sets the top-level of the moved text - at most siblings
8650 below it are allowed.
8652 With prefix arg GOTO, the command will only visit the target location,
8653 not actually move anything.
8654 With a double prefix `C-u C-u', go to the location where the last refiling
8655 operation has put the subtree.
8657 RFLOC can be a refile location obtained in a different way.
8659 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8660 (interactive "P")
8661 (let* ((cbuf (current-buffer))
8662 (regionp (org-region-active-p))
8663 (region-start (and regionp (region-beginning)))
8664 (region-end (and regionp (region-end)))
8665 (region-length (and regionp (- region-end region-start)))
8666 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8667 pos it nbuf file re level reversed)
8668 (when regionp
8669 (goto-char region-start)
8670 (or (bolp) (goto-char (point-at-bol)))
8671 (setq region-start (point))
8672 (unless (org-kill-is-subtree-p
8673 (buffer-substring region-start region-end))
8674 (error "The region is not a (sequence of) subtree(s)")))
8675 (if (equal goto '(16))
8676 (org-refile-goto-last-stored)
8677 (when (setq it (or rfloc
8678 (save-excursion
8679 (org-refile-get-location
8680 (if goto "Goto: " "Refile to: ") default-buffer
8681 org-refile-allow-creating-parent-nodes))))
8682 (setq file (nth 1 it)
8683 re (nth 2 it)
8684 pos (nth 3 it))
8685 (if (and (not goto)
8687 (equal (buffer-file-name) file)
8688 (if regionp
8689 (and (>= pos region-start)
8690 (<= pos region-end))
8691 (and (>= pos (point))
8692 (< pos (save-excursion
8693 (org-end-of-subtree t t))))))
8694 (error "Cannot refile to position inside the tree or region"))
8696 (setq nbuf (or (find-buffer-visiting file)
8697 (find-file-noselect file)))
8698 (if goto
8699 (progn
8700 (switch-to-buffer nbuf)
8701 (goto-char pos)
8702 (org-show-context 'org-goto))
8703 (if regionp
8704 (progn
8705 (org-kill-new (buffer-substring region-start region-end))
8706 (org-save-markers-in-region region-start region-end))
8707 (org-copy-subtree 1 nil t))
8708 (save-excursion
8709 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8710 (find-file-noselect file))))
8711 (setq reversed (org-notes-order-reversed-p))
8712 (save-excursion
8713 (save-restriction
8714 (widen)
8715 (if pos
8716 (progn
8717 (goto-char pos)
8718 (looking-at outline-regexp)
8719 (setq level (org-get-valid-level (funcall outline-level) 1))
8720 (goto-char
8721 (if reversed
8722 (or (outline-next-heading) (point-max))
8723 (or (save-excursion (outline-get-next-sibling))
8724 (org-end-of-subtree t t)
8725 (point-max)))))
8726 (setq level 1)
8727 (if (not reversed)
8728 (goto-char (point-max))
8729 (goto-char (point-min))
8730 (or (outline-next-heading) (goto-char (point-max)))))
8731 (if (not (bolp)) (newline))
8732 (bookmark-set "org-refile-last-stored")
8733 (org-paste-subtree level)
8734 (if (fboundp 'deactivate-mark) (deactivate-mark))
8735 (run-hooks 'org-after-refile-insert-hook))))
8736 (if regionp
8737 (delete-region (point) (+ (point) region-length))
8738 (org-cut-subtree))
8739 (when (featurep 'org-inlinetask)
8740 (org-inlinetask-remove-END-maybe))
8741 (setq org-markers-to-move nil)
8742 (message "Refiled to \"%s\"" (car it))))))
8743 (org-reveal))
8745 (defun org-refile-goto-last-stored ()
8746 "Go to the location where the last refile was stored."
8747 (interactive)
8748 (bookmark-jump "org-refile-last-stored")
8749 (message "This is the location of the last refile"))
8751 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8752 "Prompt the user for a refile location, using PROMPT."
8753 (let ((org-refile-targets org-refile-targets)
8754 (org-refile-use-outline-path org-refile-use-outline-path))
8755 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8756 (unless org-refile-target-table
8757 (error "No refile targets"))
8758 (let* ((cbuf (current-buffer))
8759 (partial-completion-mode nil)
8760 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8761 (cfunc (if (and org-refile-use-outline-path
8762 org-outline-path-complete-in-steps)
8763 'org-olpath-completing-read
8764 'org-icompleting-read))
8765 (extra (if org-refile-use-outline-path "/" ""))
8766 (filename (and cfn (expand-file-name cfn)))
8767 (tbl (mapcar
8768 (lambda (x)
8769 (if (and (not (member org-refile-use-outline-path
8770 '(file full-file-path)))
8771 (not (equal filename (nth 1 x))))
8772 (cons (concat (car x) extra " ("
8773 (file-name-nondirectory (nth 1 x)) ")")
8774 (cdr x))
8775 (cons (concat (car x) extra) (cdr x))))
8776 org-refile-target-table))
8777 (completion-ignore-case t)
8778 pa answ parent-target child parent old-hist)
8779 (setq old-hist org-refile-history)
8780 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8781 nil 'org-refile-history))
8782 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8783 (if pa
8784 (progn
8785 (when (or (not org-refile-history)
8786 (not (eq old-hist org-refile-history))
8787 (not (equal (car pa) (car org-refile-history))))
8788 (setq org-refile-history
8789 (cons (car pa) (if (assoc (car org-refile-history) tbl)
8790 org-refile-history
8791 (cdr org-refile-history))))
8792 (if (equal (car org-refile-history) (nth 1 org-refile-history))
8793 (pop org-refile-history)))
8795 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8796 (setq parent (match-string 1 answ)
8797 child (match-string 2 answ))
8798 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8799 (when (and parent-target
8800 (or (eq new-nodes t)
8801 (and (eq new-nodes 'confirm)
8802 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8803 (org-refile-new-child parent-target child))))))
8805 (defun org-refile-new-child (parent-target child)
8806 "Use refile target PARENT-TARGET to add new CHILD below it."
8807 (unless parent-target
8808 (error "Cannot find parent for new node"))
8809 (let ((file (nth 1 parent-target))
8810 (pos (nth 3 parent-target))
8811 level)
8812 (with-current-buffer (or (find-buffer-visiting file)
8813 (find-file-noselect file))
8814 (save-excursion
8815 (save-restriction
8816 (widen)
8817 (if pos
8818 (goto-char pos)
8819 (goto-char (point-max))
8820 (if (not (bolp)) (newline)))
8821 (when (looking-at outline-regexp)
8822 (setq level (funcall outline-level))
8823 (org-end-of-subtree t t))
8824 (org-back-over-empty-lines)
8825 (insert "\n" (make-string
8826 (if pos (org-get-valid-level level 1) 1) ?*)
8827 " " child "\n")
8828 (beginning-of-line 0)
8829 (list (concat (car parent-target) "/" child) file "" (point)))))))
8831 (defun org-olpath-completing-read (prompt collection &rest args)
8832 "Read an outline path like a file name."
8833 (let ((thetable collection)
8834 (org-completion-use-ido nil) ; does not work with ido.
8835 (org-completion-use-iswitchb nil)) ; or iswitchb
8836 (apply
8837 'org-icompleting-read prompt
8838 (lambda (string predicate &optional flag)
8839 (let (rtn r f (l (length string)))
8840 (cond
8841 ((eq flag nil)
8842 ;; try completion
8843 (try-completion string thetable))
8844 ((eq flag t)
8845 ;; all-completions
8846 (setq rtn (all-completions string thetable predicate))
8847 (mapcar
8848 (lambda (x)
8849 (setq r (substring x l))
8850 (if (string-match " ([^)]*)$" x)
8851 (setq f (match-string 0 x))
8852 (setq f ""))
8853 (if (string-match "/" r)
8854 (concat string (substring r 0 (match-end 0)) f)
8856 rtn))
8857 ((eq flag 'lambda)
8858 ;; exact match?
8859 (assoc string thetable)))
8861 args)))
8863 ;;;; Dynamic blocks
8865 (defun org-find-dblock (name)
8866 "Find the first dynamic block with name NAME in the buffer.
8867 If not found, stay at current position and return nil."
8868 (let (pos)
8869 (save-excursion
8870 (goto-char (point-min))
8871 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8872 nil t)
8873 (match-beginning 0))))
8874 (if pos (goto-char pos))
8875 pos))
8877 (defconst org-dblock-start-re
8878 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8879 "Matches the startline of a dynamic block, with parameters.")
8881 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8882 "Matches the end of a dynamic block.")
8884 (defun org-create-dblock (plist)
8885 "Create a dynamic block section, with parameters taken from PLIST.
8886 PLIST must contain a :name entry which is used as name of the block."
8887 (unless (bolp) (newline))
8888 (let ((name (plist-get plist :name)))
8889 (insert "#+BEGIN: " name)
8890 (while plist
8891 (if (eq (car plist) :name)
8892 (setq plist (cddr plist))
8893 (insert " " (prin1-to-string (pop plist)))))
8894 (insert "\n\n#+END:\n")
8895 (beginning-of-line -2)))
8897 (defun org-prepare-dblock ()
8898 "Prepare dynamic block for refresh.
8899 This empties the block, puts the cursor at the insert position and returns
8900 the property list including an extra property :name with the block name."
8901 (unless (looking-at org-dblock-start-re)
8902 (error "Not at a dynamic block"))
8903 (let* ((begdel (1+ (match-end 0)))
8904 (name (org-no-properties (match-string 1)))
8905 (params (append (list :name name)
8906 (read (concat "(" (match-string 3) ")")))))
8907 (unless (re-search-forward org-dblock-end-re nil t)
8908 (error "Dynamic block not terminated"))
8909 (setq params
8910 (append params
8911 (list :content (buffer-substring
8912 begdel (match-beginning 0)))))
8913 (delete-region begdel (match-beginning 0))
8914 (goto-char begdel)
8915 (open-line 1)
8916 params))
8918 (defun org-map-dblocks (&optional command)
8919 "Apply COMMAND to all dynamic blocks in the current buffer.
8920 If COMMAND is not given, use `org-update-dblock'."
8921 (let ((cmd (or command 'org-update-dblock))
8922 pos)
8923 (save-excursion
8924 (goto-char (point-min))
8925 (while (re-search-forward org-dblock-start-re nil t)
8926 (goto-char (setq pos (match-beginning 0)))
8927 (condition-case nil
8928 (funcall cmd)
8929 (error (message "Error during update of dynamic block")))
8930 (goto-char pos)
8931 (unless (re-search-forward org-dblock-end-re nil t)
8932 (error "Dynamic block not terminated"))))))
8934 (defun org-dblock-update (&optional arg)
8935 "User command for updating dynamic blocks.
8936 Update the dynamic block at point. With prefix ARG, update all dynamic
8937 blocks in the buffer."
8938 (interactive "P")
8939 (if arg
8940 (org-update-all-dblocks)
8941 (or (looking-at org-dblock-start-re)
8942 (org-beginning-of-dblock))
8943 (org-update-dblock)))
8945 (defun org-update-dblock ()
8946 "Update the dynamic block at point
8947 This means to empty the block, parse for parameters and then call
8948 the correct writing function."
8949 (save-window-excursion
8950 (let* ((pos (point))
8951 (line (org-current-line))
8952 (params (org-prepare-dblock))
8953 (name (plist-get params :name))
8954 (cmd (intern (concat "org-dblock-write:" name))))
8955 (message "Updating dynamic block `%s' at line %d..." name line)
8956 (funcall cmd params)
8957 (message "Updating dynamic block `%s' at line %d...done" name line)
8958 (goto-char pos))))
8960 (defun org-beginning-of-dblock ()
8961 "Find the beginning of the dynamic block at point.
8962 Error if there is no such block at point."
8963 (let ((pos (point))
8964 beg)
8965 (end-of-line 1)
8966 (if (and (re-search-backward org-dblock-start-re nil t)
8967 (setq beg (match-beginning 0))
8968 (re-search-forward org-dblock-end-re nil t)
8969 (> (match-end 0) pos))
8970 (goto-char beg)
8971 (goto-char pos)
8972 (error "Not in a dynamic block"))))
8974 (defun org-update-all-dblocks ()
8975 "Update all dynamic blocks in the buffer.
8976 This function can be used in a hook."
8977 (when (org-mode-p)
8978 (org-map-dblocks 'org-update-dblock)))
8981 ;;;; Completion
8983 (defconst org-additional-option-like-keywords
8984 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
8985 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
8986 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
8987 "BEGIN:" "END:"
8988 "ORGTBL" "TBLFM:" "TBLNAME:"
8989 "BEGIN_EXAMPLE" "END_EXAMPLE"
8990 "BEGIN_QUOTE" "END_QUOTE"
8991 "BEGIN_VERSE" "END_VERSE"
8992 "BEGIN_CENTER" "END_CENTER"
8993 "BEGIN_SRC" "END_SRC"
8994 "CATEGORY" "COLUMNS"
8995 "CAPTION" "LABEL"
8996 "BIND"
8997 "MACRO"))
8999 (defcustom org-structure-template-alist
9001 ("s" "#+begin_src ?\n\n#+end_src"
9002 "<src lang=\"?\">\n\n</src>")
9003 ("e" "#+begin_example\n?\n#+end_example"
9004 "<example>\n?\n</example>")
9005 ("q" "#+begin_quote\n?\n#+end_quote"
9006 "<quote>\n?\n</quote>")
9007 ("v" "#+begin_verse\n?\n#+end_verse"
9008 "<verse>\n?\n/verse>")
9009 ("c" "#+begin_center\n?\n#+end_center"
9010 "<center>\n?\n/center>")
9011 ("l" "#+begin_latex\n?\n#+end_latex"
9012 "<literal style=\"latex\">\n?\n</literal>")
9013 ("L" "#+latex: "
9014 "<literal style=\"latex\">?</literal>")
9015 ("h" "#+begin_html\n?\n#+end_html"
9016 "<literal style=\"html\">\n?\n</literal>")
9017 ("H" "#+html: "
9018 "<literal style=\"html\">?</literal>")
9019 ("a" "#+begin_ascii\n?\n#+end_ascii")
9020 ("A" "#+ascii: ")
9021 ("i" "#+include %file ?"
9022 "<include file=%file markup=\"?\">")
9024 "Structure completion elements.
9025 This is a list of abbreviation keys and values. The value gets inserted
9026 it you type @samp{.} followed by the key and then the completion key,
9027 usually `M-TAB'. %file will be replaced by a file name after prompting
9028 for the file using completion.
9029 There are two templates for each key, the first uses the original Org syntax,
9030 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9031 the default when the /org-mtags.el/ module has been loaded. See also the
9032 variable `org-mtags-prefer-muse-templates'.
9033 This is an experimental feature, it is undecided if it is going to stay in."
9034 :group 'org-completion
9035 :type '(repeat
9036 (string :tag "Key")
9037 (string :tag "Template")
9038 (string :tag "Muse Template")))
9040 (defun org-try-structure-completion ()
9041 "Try to complete a structure template before point.
9042 This looks for strings like \"<e\" on an otherwise empty line and
9043 expands them."
9044 (let ((l (buffer-substring (point-at-bol) (point)))
9046 (when (and (looking-at "[ \t]*$")
9047 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9048 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9049 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9050 (match-beginning 1)) a)
9051 t)))
9053 (defun org-complete-expand-structure-template (start cell)
9054 "Expand a structure template."
9055 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9056 (rpl (nth (if musep 2 1) cell))
9057 (ind ""))
9058 (delete-region start (point))
9059 (when (string-match "\\`#\\+" rpl)
9060 (cond
9061 ((bolp))
9062 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9063 (setq ind (buffer-substring (point-at-bol) (point))))
9064 (t (newline))))
9065 (setq start (point))
9066 (if (string-match "%file" rpl)
9067 (setq rpl (replace-match
9068 (concat
9069 "\""
9070 (save-match-data
9071 (abbreviate-file-name (read-file-name "Include file: ")))
9072 "\"")
9073 t t rpl)))
9074 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9075 (concat "\n" ind)))
9076 (insert rpl)
9077 (if (re-search-backward "\\?" start t) (delete-char 1))))
9080 (defun org-complete (&optional arg)
9081 "Perform completion on word at point.
9082 At the beginning of a headline, this completes TODO keywords as given in
9083 `org-todo-keywords'.
9084 If the current word is preceded by a backslash, completes the TeX symbols
9085 that are supported for HTML support.
9086 If the current word is preceded by \"#+\", completes special words for
9087 setting file options.
9088 In the line after \"#+STARTUP:, complete valid keywords.\"
9089 At all other locations, this simply calls the value of
9090 `org-completion-fallback-command'."
9091 (interactive "P")
9092 (org-without-partial-completion
9093 (catch 'exit
9094 (let* ((a nil)
9095 (end (point))
9096 (beg1 (save-excursion
9097 (skip-chars-backward (org-re "[:alnum:]_@"))
9098 (point)))
9099 (beg (save-excursion
9100 (skip-chars-backward "a-zA-Z0-9_:$")
9101 (point)))
9102 (confirm (lambda (x) (stringp (car x))))
9103 (searchhead (equal (char-before beg) ?*))
9104 (struct
9105 (when (and (member (char-before beg1) '(?. ?<))
9106 (setq a (assoc (buffer-substring beg1 (point))
9107 org-structure-template-alist)))
9108 (org-complete-expand-structure-template (1- beg1) a)
9109 (throw 'exit t)))
9110 (tag (and (equal (char-before beg1) ?:)
9111 (equal (char-after (point-at-bol)) ?*)))
9112 (prop (and (equal (char-before beg1) ?:)
9113 (not (equal (char-after (point-at-bol)) ?*))))
9114 (texp (equal (char-before beg) ?\\))
9115 (link (equal (char-before beg) ?\[))
9116 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9117 beg)
9118 "#+"))
9119 (startup (string-match "^#\\+STARTUP:.*"
9120 (buffer-substring (point-at-bol) (point))))
9121 (completion-ignore-case opt)
9122 (type nil)
9123 (tbl nil)
9124 (table (cond
9125 (opt
9126 (setq type :opt)
9127 (require 'org-exp)
9128 (append
9129 (delq nil
9130 (mapcar
9131 (lambda (x)
9132 (if (string-match
9133 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9134 (cons (match-string 2 x)
9135 (match-string 1 x))))
9136 (org-split-string (org-get-current-options) "\n")))
9137 (mapcar 'list org-additional-option-like-keywords)))
9138 (startup
9139 (setq type :startup)
9140 org-startup-options)
9141 (link (append org-link-abbrev-alist-local
9142 org-link-abbrev-alist))
9143 (texp
9144 (setq type :tex)
9145 org-html-entities)
9146 ((string-match "\\`\\*+[ \t]+\\'"
9147 (buffer-substring (point-at-bol) beg))
9148 (setq type :todo)
9149 (mapcar 'list org-todo-keywords-1))
9150 (searchhead
9151 (setq type :searchhead)
9152 (save-excursion
9153 (goto-char (point-min))
9154 (while (re-search-forward org-todo-line-regexp nil t)
9155 (push (list
9156 (org-make-org-heading-search-string
9157 (match-string 3) t))
9158 tbl)))
9159 tbl)
9160 (tag (setq type :tag beg beg1)
9161 (or org-tag-alist (org-get-buffer-tags)))
9162 (prop (setq type :prop beg beg1)
9163 (mapcar 'list (org-buffer-property-keys nil t t)))
9164 (t (progn
9165 (call-interactively org-completion-fallback-command)
9166 (throw 'exit nil)))))
9167 (pattern (buffer-substring-no-properties beg end))
9168 (completion (try-completion pattern table confirm)))
9169 (cond ((eq completion t)
9170 (if (not (assoc (upcase pattern) table))
9171 (message "Already complete")
9172 (if (and (equal type :opt)
9173 (not (member (car (assoc (upcase pattern) table))
9174 org-additional-option-like-keywords)))
9175 (insert (substring (cdr (assoc (upcase pattern) table))
9176 (length pattern)))
9177 (if (memq type '(:tag :prop)) (insert ":")))))
9178 ((null completion)
9179 (message "Can't find completion for \"%s\"" pattern)
9180 (ding))
9181 ((not (string= pattern completion))
9182 (delete-region beg end)
9183 (if (string-match " +$" completion)
9184 (setq completion (replace-match "" t t completion)))
9185 (insert completion)
9186 (if (get-buffer-window "*Completions*")
9187 (delete-window (get-buffer-window "*Completions*")))
9188 (if (assoc completion table)
9189 (if (eq type :todo) (insert " ")
9190 (if (memq type '(:tag :prop)) (insert ":"))))
9191 (if (and (equal type :opt) (assoc completion table))
9192 (message "%s" (substitute-command-keys
9193 "Press \\[org-complete] again to insert example settings"))))
9195 (message "Making completion list...")
9196 (let ((list (sort (all-completions pattern table confirm)
9197 'string<)))
9198 (with-output-to-temp-buffer "*Completions*"
9199 (condition-case nil
9200 ;; Protection needed for XEmacs and emacs 21
9201 (display-completion-list list pattern)
9202 (error (display-completion-list list)))))
9203 (message "Making completion list...%s" "done")))))))
9205 ;;;; TODO, DEADLINE, Comments
9207 (defun org-toggle-comment ()
9208 "Change the COMMENT state of an entry."
9209 (interactive)
9210 (save-excursion
9211 (org-back-to-heading)
9212 (let (case-fold-search)
9213 (if (looking-at (concat outline-regexp
9214 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9215 (replace-match "" t t nil 1)
9216 (if (looking-at outline-regexp)
9217 (progn
9218 (goto-char (match-end 0))
9219 (insert org-comment-string " ")))))))
9221 (defvar org-last-todo-state-is-todo nil
9222 "This is non-nil when the last TODO state change led to a TODO state.
9223 If the last change removed the TODO tag or switched to DONE, then
9224 this is nil.")
9226 (defvar org-setting-tags nil) ; dynamically skipped
9228 (defun org-parse-local-options (string var)
9229 "Parse STRING for startup setting relevant for variable VAR."
9230 (let ((rtn (symbol-value var))
9231 e opts)
9232 (save-match-data
9233 (if (or (not string) (not (string-match "\\S-" string)))
9235 (setq opts (delq nil (mapcar (lambda (x)
9236 (setq e (assoc x org-startup-options))
9237 (if (eq (nth 1 e) var) e nil))
9238 (org-split-string string "[ \t]+"))))
9239 (if (not opts)
9241 (setq rtn nil)
9242 (while (setq e (pop opts))
9243 (if (not (nth 3 e))
9244 (setq rtn (nth 2 e))
9245 (if (not (listp rtn)) (setq rtn nil))
9246 (push (nth 2 e) rtn)))
9247 rtn)))))
9249 (defvar org-todo-setup-filter-hook nil
9250 "Hook for functions that pre-filter todo specs.
9252 Each function takes a todo spec and returns either `nil' or the spec
9253 transformed into canonical form." )
9255 (defvar org-todo-get-default-hook nil
9256 "Hook for functions that get a default item for todo.
9258 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9259 `nil' or a string to be used for the todo mark." )
9261 (defvar org-agenda-headline-snapshot-before-repeat)
9263 (defun org-todo (&optional arg)
9264 "Change the TODO state of an item.
9265 The state of an item is given by a keyword at the start of the heading,
9266 like
9267 *** TODO Write paper
9268 *** DONE Call mom
9270 The different keywords are specified in the variable `org-todo-keywords'.
9271 By default the available states are \"TODO\" and \"DONE\".
9272 So for this example: when the item starts with TODO, it is changed to DONE.
9273 When it starts with DONE, the DONE is removed. And when neither TODO nor
9274 DONE are present, add TODO at the beginning of the heading.
9276 With C-u prefix arg, use completion to determine the new state.
9277 With numeric prefix arg, switch to that state.
9278 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9279 With a tripple C-u prefix, circumvent any state blocking.
9281 For calling through lisp, arg is also interpreted in the following way:
9282 'none -> empty state
9283 \"\"(empty string) -> switch to empty state
9284 'done -> switch to DONE
9285 'nextset -> switch to the next set of keywords
9286 'previousset -> switch to the previous set of keywords
9287 \"WAITING\" -> switch to the specified keyword, but only if it
9288 really is a member of `org-todo-keywords'."
9289 (interactive "P")
9290 (if (equal arg '(16)) (setq arg 'nextset))
9291 (let ((org-blocker-hook org-blocker-hook)
9292 (case-fold-search nil))
9293 (when (equal arg '(64))
9294 (setq arg nil org-blocker-hook nil))
9295 (when (and org-blocker-hook
9296 (or org-inhibit-blocking
9297 (org-entry-get nil "NOBLOCKING")))
9298 (setq org-blocker-hook nil))
9299 (save-excursion
9300 (catch 'exit
9301 (org-back-to-heading)
9302 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9303 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9304 (looking-at " *"))
9305 (let* ((match-data (match-data))
9306 (startpos (point-at-bol))
9307 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9308 (org-log-done org-log-done)
9309 (org-log-repeat org-log-repeat)
9310 (org-todo-log-states org-todo-log-states)
9311 (this (match-string 1))
9312 (hl-pos (match-beginning 0))
9313 (head (org-get-todo-sequence-head this))
9314 (ass (assoc head org-todo-kwd-alist))
9315 (interpret (nth 1 ass))
9316 (done-word (nth 3 ass))
9317 (final-done-word (nth 4 ass))
9318 (last-state (or this ""))
9319 (completion-ignore-case t)
9320 (member (member this org-todo-keywords-1))
9321 (tail (cdr member))
9322 (state (cond
9323 ((and org-todo-key-trigger
9324 (or (and (equal arg '(4))
9325 (eq org-use-fast-todo-selection 'prefix))
9326 (and (not arg) org-use-fast-todo-selection
9327 (not (eq org-use-fast-todo-selection
9328 'prefix)))))
9329 ;; Use fast selection
9330 (org-fast-todo-selection))
9331 ((and (equal arg '(4))
9332 (or (not org-use-fast-todo-selection)
9333 (not org-todo-key-trigger)))
9334 ;; Read a state with completion
9335 (org-icompleting-read
9336 "State: " (mapcar (lambda(x) (list x))
9337 org-todo-keywords-1)
9338 nil t))
9339 ((eq arg 'right)
9340 (if this
9341 (if tail (car tail) nil)
9342 (car org-todo-keywords-1)))
9343 ((eq arg 'left)
9344 (if (equal member org-todo-keywords-1)
9346 (if this
9347 (nth (- (length org-todo-keywords-1)
9348 (length tail) 2)
9349 org-todo-keywords-1)
9350 (org-last org-todo-keywords-1))))
9351 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9352 (setq arg nil))) ; hack to fall back to cycling
9353 (arg
9354 ;; user or caller requests a specific state
9355 (cond
9356 ((equal arg "") nil)
9357 ((eq arg 'none) nil)
9358 ((eq arg 'done) (or done-word (car org-done-keywords)))
9359 ((eq arg 'nextset)
9360 (or (car (cdr (member head org-todo-heads)))
9361 (car org-todo-heads)))
9362 ((eq arg 'previousset)
9363 (let ((org-todo-heads (reverse org-todo-heads)))
9364 (or (car (cdr (member head org-todo-heads)))
9365 (car org-todo-heads))))
9366 ((car (member arg org-todo-keywords-1)))
9367 ((nth (1- (prefix-numeric-value arg))
9368 org-todo-keywords-1))))
9369 ((null member) (or head (car org-todo-keywords-1)))
9370 ((equal this final-done-word) nil) ;; -> make empty
9371 ((null tail) nil) ;; -> first entry
9372 ((memq interpret '(type priority))
9373 (if (eq this-command last-command)
9374 (car tail)
9375 (if (> (length tail) 0)
9376 (or done-word (car org-done-keywords))
9377 nil)))
9379 (car tail))))
9380 (state (or
9381 (run-hook-with-args-until-success
9382 'org-todo-get-default-hook state last-state)
9383 state))
9384 (next (if state (concat " " state " ") " "))
9385 (change-plist (list :type 'todo-state-change :from this :to state
9386 :position startpos))
9387 dolog now-done-p)
9388 (when org-blocker-hook
9389 (setq org-last-todo-state-is-todo
9390 (not (member this org-done-keywords)))
9391 (unless (save-excursion
9392 (save-match-data
9393 (run-hook-with-args-until-failure
9394 'org-blocker-hook change-plist)))
9395 (if (interactive-p)
9396 (error "TODO state change from %s to %s blocked" this state)
9397 ;; fail silently
9398 (message "TODO state change from %s to %s blocked" this state)
9399 (throw 'exit nil))))
9400 (store-match-data match-data)
9401 (replace-match next t t)
9402 (unless (pos-visible-in-window-p hl-pos)
9403 (message "TODO state changed to %s" (org-trim next)))
9404 (unless head
9405 (setq head (org-get-todo-sequence-head state)
9406 ass (assoc head org-todo-kwd-alist)
9407 interpret (nth 1 ass)
9408 done-word (nth 3 ass)
9409 final-done-word (nth 4 ass)))
9410 (when (memq arg '(nextset previousset))
9411 (message "Keyword-Set %d/%d: %s"
9412 (- (length org-todo-sets) -1
9413 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9414 (length org-todo-sets)
9415 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9416 (setq org-last-todo-state-is-todo
9417 (not (member state org-done-keywords)))
9418 (setq now-done-p (and (member state org-done-keywords)
9419 (not (member this org-done-keywords))))
9420 (and logging (org-local-logging logging))
9421 (when (and (or org-todo-log-states org-log-done)
9422 (not (eq org-inhibit-logging t))
9423 (not (memq arg '(nextset previousset))))
9424 ;; we need to look at recording a time and note
9425 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9426 (nth 2 (assoc this org-todo-log-states))))
9427 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9428 (setq dolog 'time))
9429 (when (and state
9430 (member state org-not-done-keywords)
9431 (not (member this org-not-done-keywords)))
9432 ;; This is now a todo state and was not one before
9433 ;; If there was a CLOSED time stamp, get rid of it.
9434 (org-add-planning-info nil nil 'closed))
9435 (when (and now-done-p org-log-done)
9436 ;; It is now done, and it was not done before
9437 (org-add-planning-info 'closed (org-current-time))
9438 (if (and (not dolog) (eq 'note org-log-done))
9439 (org-add-log-setup 'done state this 'findpos 'note)))
9440 (when (and state dolog)
9441 ;; This is a non-nil state, and we need to log it
9442 (org-add-log-setup 'state state this 'findpos dolog)))
9443 ;; Fixup tag positioning
9444 (org-todo-trigger-tag-changes state)
9445 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9446 (when org-provide-todo-statistics
9447 (org-update-parent-todo-statistics))
9448 (run-hooks 'org-after-todo-state-change-hook)
9449 (if (and arg (not (member state org-done-keywords)))
9450 (setq head (org-get-todo-sequence-head state)))
9451 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9452 ;; Do we need to trigger a repeat?
9453 (when now-done-p
9454 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9455 ;; This is for the agenda, take a snapshot of the headline.
9456 (save-match-data
9457 (setq org-agenda-headline-snapshot-before-repeat
9458 (org-get-heading))))
9459 (org-auto-repeat-maybe state))
9460 ;; Fixup cursor location if close to the keyword
9461 (if (and (outline-on-heading-p)
9462 (not (bolp))
9463 (save-excursion (beginning-of-line 1)
9464 (looking-at org-todo-line-regexp))
9465 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9466 (progn
9467 (goto-char (or (match-end 2) (match-end 1)))
9468 (and (looking-at " ") (just-one-space))))
9469 (when org-trigger-hook
9470 (save-excursion
9471 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9473 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9474 "Block turning an entry into a TODO, using the hierarchy.
9475 This checks whether the current task should be blocked from state
9476 changes. Such blocking occurs when:
9478 1. The task has children which are not all in a completed state.
9480 2. A task has a parent with the property :ORDERED:, and there
9481 are siblings prior to the current task with incomplete
9482 status.
9484 3. The parent of the task is blocked because it has siblings that should
9485 be done first, or is child of a block grandparent TODO entry."
9487 (catch 'dont-block
9488 ;; If this is not a todo state change, or if this entry is already DONE,
9489 ;; do not block
9490 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9491 (member (plist-get change-plist :from)
9492 (cons 'done org-done-keywords))
9493 (member (plist-get change-plist :to)
9494 (cons 'todo org-not-done-keywords)))
9495 (throw 'dont-block t))
9496 ;; If this task has children, and any are undone, it's blocked
9497 (save-excursion
9498 (org-back-to-heading t)
9499 (let ((this-level (funcall outline-level)))
9500 (outline-next-heading)
9501 (let ((child-level (funcall outline-level)))
9502 (while (and (not (eobp))
9503 (> child-level this-level))
9504 ;; this todo has children, check whether they are all
9505 ;; completed
9506 (if (and (not (org-entry-is-done-p))
9507 (org-entry-is-todo-p))
9508 (throw 'dont-block nil))
9509 (outline-next-heading)
9510 (setq child-level (funcall outline-level))))))
9511 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9512 ;; any previous siblings are undone, it's blocked
9513 (save-excursion
9514 (org-back-to-heading t)
9515 (let* ((pos (point))
9516 (parent-pos (and (org-up-heading-safe) (point))))
9517 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9518 (when (and (org-entry-get (point) "ORDERED")
9519 (forward-line 1)
9520 (re-search-forward org-not-done-heading-regexp pos t))
9521 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9522 ;; Search further up the hierarchy, to see if an anchestor is blocked
9523 (while t
9524 (goto-char parent-pos)
9525 (if (not (looking-at org-not-done-heading-regexp))
9526 (throw 'dont-block t)) ; do not block, parent is not a TODO
9527 (setq pos (point))
9528 (setq parent-pos (and (org-up-heading-safe) (point)))
9529 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9530 (when (and (org-entry-get (point) "ORDERED")
9531 (forward-line 1)
9532 (re-search-forward org-not-done-heading-regexp pos t))
9533 (throw 'dont-block nil))))))) ; block, older sibling not done.
9535 (defcustom org-track-ordered-property-with-tag nil
9536 "Should the ORDERED property also be shown as a tag?
9537 The ORDERED property decides if an entry should require subtasks to be
9538 completed in sequence. Since a property is not very visible, setting
9539 this option means that toggling the ORDERED property with the command
9540 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9541 not relevant for the behavior, but it makes things more visible.
9543 Note that toggling the tag with tags commands will not change the property
9544 and therefore not influence behavior!
9546 This can be t, meaning the tag ORDERED should be used, It can also be a
9547 string to select a different tag for this task."
9548 :group 'org-todo
9549 :type '(choice
9550 (const :tag "No tracking" nil)
9551 (const :tag "Track with ORDERED tag" t)
9552 (string :tag "Use other tag")))
9554 (defun org-toggle-ordered-property ()
9555 "Toggle the ORDERED property of the current entry.
9556 For better visibility, you can track the value of this property with a tag.
9557 See variable `org-track-ordered-property-with-tag'."
9558 (interactive)
9559 (let* ((t1 org-track-ordered-property-with-tag)
9560 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9561 (save-excursion
9562 (org-back-to-heading)
9563 (if (org-entry-get nil "ORDERED")
9564 (progn
9565 (org-delete-property "ORDERED")
9566 (and tag (org-toggle-tag tag 'off))
9567 (message "Subtasks can be completed in arbitrary order"))
9568 (org-entry-put nil "ORDERED" "t")
9569 (and tag (org-toggle-tag tag 'on))
9570 (message "Subtasks must be completed in sequence")))))
9572 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9573 (defun org-block-todo-from-checkboxes (change-plist)
9574 "Block turning an entry into a TODO, using checkboxes.
9575 This checks whether the current task should be blocked from state
9576 changes because there are uncheckd boxes in this entry."
9577 (catch 'dont-block
9578 ;; If this is not a todo state change, or if this entry is already DONE,
9579 ;; do not block
9580 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9581 (member (plist-get change-plist :from)
9582 (cons 'done org-done-keywords))
9583 (member (plist-get change-plist :to)
9584 (cons 'todo org-not-done-keywords)))
9585 (throw 'dont-block t))
9586 ;; If this task has checkboxes that are not checked, it's blocked
9587 (save-excursion
9588 (org-back-to-heading t)
9589 (let ((beg (point)) end)
9590 (outline-next-heading)
9591 (setq end (point))
9592 (goto-char beg)
9593 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9594 end t)
9595 (progn
9596 (if (boundp 'org-blocked-by-checkboxes)
9597 (setq org-blocked-by-checkboxes t))
9598 (throw 'dont-block nil)))))
9599 t)) ; do not block
9601 (defvar org-entry-property-inherited-from) ;; defined below
9602 (defun org-update-parent-todo-statistics ()
9603 "Update any statistics cookie in the parent of the current headline.
9604 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9605 the entire subtree and this will travel up the hierarchy and update
9606 statistics everywhere."
9607 (interactive)
9608 (let* ((lim 0) prop
9609 (recursive (or (not org-hierarchical-todo-statistics)
9610 (string-match
9611 "\\<recursive\\>"
9612 (or (setq prop (org-entry-get
9613 nil "COOKIE_DATA" 'inherit)) ""))))
9614 (lim (or (and prop (marker-position
9615 org-entry-property-inherited-from))
9616 lim))
9617 (first t)
9618 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9619 level ltoggle l1
9620 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9621 (catch 'exit
9622 (save-excursion
9623 (beginning-of-line 1)
9624 (if (org-at-heading-p)
9625 (setq ltoggle (funcall outline-level))
9626 (error "This should not happen"))
9627 (while (and (setq level (org-up-heading-safe))
9628 (or recursive first)
9629 (>= (point) lim))
9630 (setq first nil)
9631 (unless (and level
9632 (not (string-match
9633 "\\<checkbox\\>"
9634 (downcase
9635 (or (org-entry-get
9636 nil "COOKIE_DATA")
9637 "")))))
9638 (throw 'exit nil))
9639 (while (re-search-forward box-re (point-at-eol) t)
9640 (setq cnt-all 0 cnt-done 0 cookie-present t)
9641 (setq is-percent (match-end 2))
9642 (save-match-data
9643 (unless (outline-next-heading) (throw 'exit nil))
9644 (while (and (looking-at org-complex-heading-regexp)
9645 (> (setq l1 (length (match-string 1))) level))
9646 (setq kwd (and (or recursive (= l1 ltoggle))
9647 (match-string 2)))
9648 (if (or (eq org-provide-todo-statistics 'all-headlines)
9649 (and (listp org-provide-todo-statistics)
9650 (or (member kwd org-provide-todo-statistics)
9651 (member kwd org-done-keywords))))
9652 (setq cnt-all (1+ cnt-all))
9653 (if (eq org-provide-todo-statistics t)
9654 (and kwd (setq cnt-all (1+ cnt-all)))))
9655 (and (member kwd org-done-keywords)
9656 (setq cnt-done (1+ cnt-done)))
9657 (outline-next-heading)))
9658 (replace-match
9659 (if is-percent
9660 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9661 (format "[%d/%d]" cnt-done cnt-all)))))
9662 (when cookie-present
9663 (run-hook-with-args 'org-after-todo-statistics-hook
9664 cnt-done (- cnt-all cnt-done)))))
9665 (run-hooks 'org-todo-statistics-hook)))
9667 (defvar org-after-todo-statistics-hook nil
9668 "Hook that is called after a TODO statistics cookie has been updated.
9669 Each function is called with two arguments: the number of not-done entries
9670 and the number of done entries.
9672 For example, the following function, when added to this hook, will switch
9673 an entry to DONE when all children are done, and back to TODO when new
9674 entries are set to a TODO status. Note that this hook is only called
9675 when there is a statistics cookie in the headline!
9677 (defun org-summary-todo (n-done n-not-done)
9678 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9679 (let (org-log-done org-log-states) ; turn off logging
9680 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9683 (defvar org-todo-statistics-hook nil
9684 "Hook that is run whenever Org thinks TODO statistics should be updated.
9685 This hook runs even if there is no statisics cookie present, in which case
9686 `org-after-todo-statistics-hook' would not run.")
9688 (defun org-todo-trigger-tag-changes (state)
9689 "Apply the changes defined in `org-todo-state-tags-triggers'."
9690 (let ((l org-todo-state-tags-triggers)
9691 changes)
9692 (when (or (not state) (equal state ""))
9693 (setq changes (append changes (cdr (assoc "" l)))))
9694 (when (and (stringp state) (> (length state) 0))
9695 (setq changes (append changes (cdr (assoc state l)))))
9696 (when (member state org-not-done-keywords)
9697 (setq changes (append changes (cdr (assoc 'todo l)))))
9698 (when (member state org-done-keywords)
9699 (setq changes (append changes (cdr (assoc 'done l)))))
9700 (dolist (c changes)
9701 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9703 (defun org-local-logging (value)
9704 "Get logging settings from a property VALUE."
9705 (let* (words w a)
9706 ;; directly set the variables, they are already local.
9707 (setq org-log-done nil
9708 org-log-repeat nil
9709 org-todo-log-states nil)
9710 (setq words (org-split-string value))
9711 (while (setq w (pop words))
9712 (cond
9713 ((setq a (assoc w org-startup-options))
9714 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9715 (set (nth 1 a) (nth 2 a))))
9716 ((setq a (org-extract-log-state-settings w))
9717 (and (member (car a) org-todo-keywords-1)
9718 (push a org-todo-log-states)))))))
9720 (defun org-get-todo-sequence-head (kwd)
9721 "Return the head of the TODO sequence to which KWD belongs.
9722 If KWD is not set, check if there is a text property remembering the
9723 right sequence."
9724 (let (p)
9725 (cond
9726 ((not kwd)
9727 (or (get-text-property (point-at-bol) 'org-todo-head)
9728 (progn
9729 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9730 nil (point-at-eol)))
9731 (get-text-property p 'org-todo-head))))
9732 ((not (member kwd org-todo-keywords-1))
9733 (car org-todo-keywords-1))
9734 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9736 (defun org-fast-todo-selection ()
9737 "Fast TODO keyword selection with single keys.
9738 Returns the new TODO keyword, or nil if no state change should occur."
9739 (let* ((fulltable org-todo-key-alist)
9740 (done-keywords org-done-keywords) ;; needed for the faces.
9741 (maxlen (apply 'max (mapcar
9742 (lambda (x)
9743 (if (stringp (car x)) (string-width (car x)) 0))
9744 fulltable)))
9745 (expert nil)
9746 (fwidth (+ maxlen 3 1 3))
9747 (ncol (/ (- (window-width) 4) fwidth))
9748 tg cnt e c tbl
9749 groups ingroup)
9750 (save-excursion
9751 (save-window-excursion
9752 (if expert
9753 (set-buffer (get-buffer-create " *Org todo*"))
9754 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9755 (erase-buffer)
9756 (org-set-local 'org-done-keywords done-keywords)
9757 (setq tbl fulltable cnt 0)
9758 (while (setq e (pop tbl))
9759 (cond
9760 ((equal e '(:startgroup))
9761 (push '() groups) (setq ingroup t)
9762 (when (not (= cnt 0))
9763 (setq cnt 0)
9764 (insert "\n"))
9765 (insert "{ "))
9766 ((equal e '(:endgroup))
9767 (setq ingroup nil cnt 0)
9768 (insert "}\n"))
9769 ((equal e '(:newline))
9770 (when (not (= cnt 0))
9771 (setq cnt 0)
9772 (insert "\n")
9773 (setq e (car tbl))
9774 (while (equal (car tbl) '(:newline))
9775 (insert "\n")
9776 (setq tbl (cdr tbl)))))
9778 (setq tg (car e) c (cdr e))
9779 (if ingroup (push tg (car groups)))
9780 (setq tg (org-add-props tg nil 'face
9781 (org-get-todo-face tg)))
9782 (if (and (= cnt 0) (not ingroup)) (insert " "))
9783 (insert "[" c "] " tg (make-string
9784 (- fwidth 4 (length tg)) ?\ ))
9785 (when (= (setq cnt (1+ cnt)) ncol)
9786 (insert "\n")
9787 (if ingroup (insert " "))
9788 (setq cnt 0)))))
9789 (insert "\n")
9790 (goto-char (point-min))
9791 (if (not expert) (org-fit-window-to-buffer))
9792 (message "[a-z..]:Set [SPC]:clear")
9793 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9794 (cond
9795 ((or (= c ?\C-g)
9796 (and (= c ?q) (not (rassoc c fulltable))))
9797 (setq quit-flag t))
9798 ((= c ?\ ) nil)
9799 ((setq e (rassoc c fulltable) tg (car e))
9801 (t (setq quit-flag t)))))))
9803 (defun org-entry-is-todo-p ()
9804 (member (org-get-todo-state) org-not-done-keywords))
9806 (defun org-entry-is-done-p ()
9807 (member (org-get-todo-state) org-done-keywords))
9809 (defun org-get-todo-state ()
9810 (save-excursion
9811 (org-back-to-heading t)
9812 (and (looking-at org-todo-line-regexp)
9813 (match-end 2)
9814 (match-string 2))))
9816 (defun org-at-date-range-p (&optional inactive-ok)
9817 "Is the cursor inside a date range?"
9818 (interactive)
9819 (save-excursion
9820 (catch 'exit
9821 (let ((pos (point)))
9822 (skip-chars-backward "^[<\r\n")
9823 (skip-chars-backward "<[")
9824 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9825 (>= (match-end 0) pos)
9826 (throw 'exit t))
9827 (skip-chars-backward "^<[\r\n")
9828 (skip-chars-backward "<[")
9829 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9830 (>= (match-end 0) pos)
9831 (throw 'exit t)))
9832 nil)))
9834 (defun org-get-repeat ()
9835 "Check if there is a deadline/schedule with repeater in this entry."
9836 (save-match-data
9837 (save-excursion
9838 (org-back-to-heading t)
9839 (if (re-search-forward
9840 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9841 (match-string 1)))))
9843 (defvar org-last-changed-timestamp)
9844 (defvar org-last-inserted-timestamp)
9845 (defvar org-log-post-message)
9846 (defvar org-log-note-purpose)
9847 (defvar org-log-note-how)
9848 (defvar org-log-note-extra)
9849 (defun org-auto-repeat-maybe (done-word)
9850 "Check if the current headline contains a repeated deadline/schedule.
9851 If yes, set TODO state back to what it was and change the base date
9852 of repeating deadline/scheduled time stamps to new date.
9853 This function is run automatically after each state change to a DONE state."
9854 ;; last-state is dynamically scoped into this function
9855 (let* ((repeat (org-get-repeat))
9856 (aa (assoc last-state org-todo-kwd-alist))
9857 (interpret (nth 1 aa))
9858 (head (nth 2 aa))
9859 (whata '(("d" . day) ("m" . month) ("y" . year)))
9860 (msg "Entry repeats: ")
9861 (org-log-done nil)
9862 (org-todo-log-states nil)
9863 (nshiftmax 10) (nshift 0)
9864 re type n what ts time)
9865 (when repeat
9866 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9867 (org-todo (if (eq interpret 'type) last-state head))
9868 (org-entry-put nil "LAST_REPEAT" (format-time-string
9869 (org-time-stamp-format t t)))
9870 (when org-log-repeat
9871 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9872 (memq 'org-add-log-note post-command-hook))
9873 ;; OK, we are already setup for some record
9874 (if (eq org-log-repeat 'note)
9875 ;; make sure we take a note, not only a time stamp
9876 (setq org-log-note-how 'note))
9877 ;; Set up for taking a record
9878 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9879 last-state
9880 'findpos org-log-repeat)))
9881 (org-back-to-heading t)
9882 (org-add-planning-info nil nil 'closed)
9883 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9884 org-deadline-time-regexp "\\)\\|\\("
9885 org-ts-regexp "\\)"))
9886 (while (re-search-forward
9887 re (save-excursion (outline-next-heading) (point)) t)
9888 (setq type (if (match-end 1) org-scheduled-string
9889 (if (match-end 3) org-deadline-string "Plain:"))
9890 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9891 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9892 (setq n (string-to-number (match-string 2 ts))
9893 what (match-string 3 ts))
9894 (if (equal what "w") (setq n (* n 7) what "d"))
9895 ;; Preparation, see if we need to modify the start date for the change
9896 (when (match-end 1)
9897 (setq time (save-match-data (org-time-string-to-time ts)))
9898 (cond
9899 ((equal (match-string 1 ts) ".")
9900 ;; Shift starting date to today
9901 (org-timestamp-change
9902 (- (time-to-days (current-time)) (time-to-days time))
9903 'day))
9904 ((equal (match-string 1 ts) "+")
9905 (while (or (= nshift 0)
9906 (<= (time-to-days time) (time-to-days (current-time))))
9907 (when (= (incf nshift) nshiftmax)
9908 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9909 (error "Abort")))
9910 (org-timestamp-change n (cdr (assoc what whata)))
9911 (org-at-timestamp-p t)
9912 (setq ts (match-string 1))
9913 (setq time (save-match-data (org-time-string-to-time ts))))
9914 (org-timestamp-change (- n) (cdr (assoc what whata)))
9915 ;; rematch, so that we have everything in place for the real shift
9916 (org-at-timestamp-p t)
9917 (setq ts (match-string 1))
9918 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9919 (org-timestamp-change n (cdr (assoc what whata)))
9920 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9921 (setq org-log-post-message msg)
9922 (message "%s" msg))))
9924 (defun org-show-todo-tree (arg)
9925 "Make a compact tree which shows all headlines marked with TODO.
9926 The tree will show the lines where the regexp matches, and all higher
9927 headlines above the match.
9928 With a \\[universal-argument] prefix, prompt for a regexp to match.
9929 With a numeric prefix N, construct a sparse tree for the Nth element
9930 of `org-todo-keywords-1'."
9931 (interactive "P")
9932 (let ((case-fold-search nil)
9933 (kwd-re
9934 (cond ((null arg) org-not-done-regexp)
9935 ((equal arg '(4))
9936 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
9937 (mapcar 'list org-todo-keywords-1))))
9938 (concat "\\("
9939 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9940 "\\)\\>")))
9941 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9942 (regexp-quote (nth (1- (prefix-numeric-value arg))
9943 org-todo-keywords-1)))
9944 (t (error "Invalid prefix argument: %s" arg)))))
9945 (message "%d TODO entries found"
9946 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9948 (defun org-deadline (&optional remove time)
9949 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9950 With argument REMOVE, remove any deadline from the item.
9951 When TIME is set, it should be an internal time specification, and the
9952 scheduling will use the corresponding date."
9953 (interactive "P")
9954 (if remove
9955 (progn
9956 (org-remove-timestamp-with-keyword org-deadline-string)
9957 (message "Item no longer has a deadline."))
9958 (if (org-get-repeat)
9959 (error "Cannot change deadline on task with repeater, please do that by hand")
9960 (org-add-planning-info 'deadline time 'closed)
9961 (message "Deadline on %s" org-last-inserted-timestamp))))
9963 (defun org-schedule (&optional remove time)
9964 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9965 With argument REMOVE, remove any scheduling date from the item.
9966 When TIME is set, it should be an internal time specification, and the
9967 scheduling will use the corresponding date."
9968 (interactive "P")
9969 (if remove
9970 (progn
9971 (org-remove-timestamp-with-keyword org-scheduled-string)
9972 (message "Item is no longer scheduled."))
9973 (if (org-get-repeat)
9974 (error "Cannot reschedule task with repeater, please do that by hand")
9975 (org-add-planning-info 'scheduled time 'closed)
9976 (message "Scheduled to %s" org-last-inserted-timestamp))))
9978 (defun org-get-scheduled-time (pom &optional inherit)
9979 "Get the scheduled time as a time tuple, of a format suitable
9980 for calling org-schedule with, or if there is no scheduling,
9981 returns nil."
9982 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9983 (when time
9984 (apply 'encode-time (org-parse-time-string time)))))
9986 (defun org-get-deadline-time (pom &optional inherit)
9987 "Get the deadine as a time tuple, of a format suitable for
9988 calling org-deadlin with, or if there is no scheduling, returns
9989 nil."
9990 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9991 (when time
9992 (apply 'encode-time (org-parse-time-string time)))))
9994 (defun org-remove-timestamp-with-keyword (keyword)
9995 "Remove all time stamps with KEYWORD in the current entry."
9996 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9997 beg)
9998 (save-excursion
9999 (org-back-to-heading t)
10000 (setq beg (point))
10001 (org-end-of-subtree t t)
10002 (while (re-search-backward re beg t)
10003 (replace-match "")
10004 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10005 (equal (char-before) ?\ ))
10006 (backward-delete-char 1)
10007 (if (string-match "^[ \t]*$" (buffer-substring
10008 (point-at-bol) (point-at-eol)))
10009 (delete-region (point-at-bol)
10010 (min (point-max) (1+ (point-at-eol))))))))))
10012 (defun org-add-planning-info (what &optional time &rest remove)
10013 "Insert new timestamp with keyword in the line directly after the headline.
10014 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10015 If non is given, the user is prompted for a date.
10016 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10017 be removed."
10018 (interactive)
10019 (let (org-time-was-given org-end-time-was-given ts
10020 end default-time default-input)
10022 (catch 'exit
10023 (when (and (not time) (memq what '(scheduled deadline)))
10024 ;; Try to get a default date/time from existing timestamp
10025 (save-excursion
10026 (org-back-to-heading t)
10027 (setq end (save-excursion (outline-next-heading) (point)))
10028 (when (re-search-forward (if (eq what 'scheduled)
10029 org-scheduled-time-regexp
10030 org-deadline-time-regexp)
10031 end t)
10032 (setq ts (match-string 1)
10033 default-time
10034 (apply 'encode-time (org-parse-time-string ts))
10035 default-input (and ts (org-get-compact-tod ts))))))
10036 (when what
10037 ;; If necessary, get the time from the user
10038 (setq time (or time (org-read-date nil 'to-time nil nil
10039 default-time default-input))))
10041 (when (and org-insert-labeled-timestamps-at-point
10042 (member what '(scheduled deadline)))
10043 (insert
10044 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10045 (org-insert-time-stamp time org-time-was-given
10046 nil nil nil (list org-end-time-was-given))
10047 (setq what nil))
10048 (save-excursion
10049 (save-restriction
10050 (let (col list elt ts buffer-invisibility-spec)
10051 (org-back-to-heading t)
10052 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10053 (goto-char (match-end 1))
10054 (setq col (current-column))
10055 (goto-char (match-end 0))
10056 (if (eobp) (insert "\n") (forward-char 1))
10057 (when (and (not what)
10058 (not (looking-at
10059 (concat "[ \t]*"
10060 org-keyword-time-not-clock-regexp))))
10061 ;; Nothing to add, nothing to remove...... :-)
10062 (throw 'exit nil))
10063 (if (and (not (looking-at outline-regexp))
10064 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10065 "[^\r\n]*"))
10066 (not (equal (match-string 1) org-clock-string)))
10067 (narrow-to-region (match-beginning 0) (match-end 0))
10068 (insert-before-markers "\n")
10069 (backward-char 1)
10070 (narrow-to-region (point) (point))
10071 (and org-adapt-indentation (org-indent-to-column col)))
10072 ;; Check if we have to remove something.
10073 (setq list (cons what remove))
10074 (while list
10075 (setq elt (pop list))
10076 (goto-char (point-min))
10077 (when (or (and (eq elt 'scheduled)
10078 (re-search-forward org-scheduled-time-regexp nil t))
10079 (and (eq elt 'deadline)
10080 (re-search-forward org-deadline-time-regexp nil t))
10081 (and (eq elt 'closed)
10082 (re-search-forward org-closed-time-regexp nil t)))
10083 (replace-match "")
10084 (if (looking-at "--+<[^>]+>") (replace-match ""))
10085 (if (looking-at " +") (replace-match ""))))
10086 (goto-char (point-max))
10087 (when what
10088 (insert
10089 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10090 (cond ((eq what 'scheduled) org-scheduled-string)
10091 ((eq what 'deadline) org-deadline-string)
10092 ((eq what 'closed) org-closed-string))
10093 " ")
10094 (setq ts (org-insert-time-stamp
10095 time
10096 (or org-time-was-given
10097 (and (eq what 'closed) org-log-done-with-time))
10098 (eq what 'closed)
10099 nil nil (list org-end-time-was-given)))
10100 (end-of-line 1))
10101 (goto-char (point-min))
10102 (widen)
10103 (if (and (looking-at "[ \t]+\n")
10104 (equal (char-before) ?\n))
10105 (delete-region (1- (point)) (point-at-eol)))
10106 ts))))))
10108 (defvar org-log-note-marker (make-marker))
10109 (defvar org-log-note-purpose nil)
10110 (defvar org-log-note-state nil)
10111 (defvar org-log-note-previous-state nil)
10112 (defvar org-log-note-how nil)
10113 (defvar org-log-note-extra nil)
10114 (defvar org-log-note-window-configuration nil)
10115 (defvar org-log-note-return-to (make-marker))
10116 (defvar org-log-post-message nil
10117 "Message to be displayed after a log note has been stored.
10118 The auto-repeater uses this.")
10120 (defun org-add-note ()
10121 "Add a note to the current entry.
10122 This is done in the same way as adding a state change note."
10123 (interactive)
10124 (org-add-log-setup 'note nil nil 'findpos nil))
10126 (defvar org-property-end-re)
10127 (defun org-add-log-setup (&optional purpose state prev-state
10128 findpos how &optional extra)
10129 "Set up the post command hook to take a note.
10130 If this is about to TODO state change, the new state is expected in STATE.
10131 When FINDPOS is non-nil, find the correct position for the note in
10132 the current entry. If not, assume that it can be inserted at point.
10133 HOW is an indicator what kind of note should be created.
10134 EXTRA is additional text that will be inserted into the notes buffer."
10135 (let* ((org-log-into-drawer (org-log-into-drawer))
10136 (drawer (cond ((stringp org-log-into-drawer)
10137 org-log-into-drawer)
10138 (org-log-into-drawer "LOGBOOK")
10139 (t nil))))
10140 (save-restriction
10141 (save-excursion
10142 (when findpos
10143 (org-back-to-heading t)
10144 (narrow-to-region (point) (save-excursion
10145 (outline-next-heading) (point)))
10146 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10147 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10148 "[^\r\n]*\\)?"))
10149 (goto-char (match-end 0))
10150 (cond
10151 (drawer
10152 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10153 nil t)
10154 (progn
10155 (goto-char (match-end 0))
10156 (or org-log-states-order-reversed
10157 (and (re-search-forward org-property-end-re nil t)
10158 (goto-char (1- (match-beginning 0))))))
10159 (insert "\n:" drawer ":\n:END:")
10160 (beginning-of-line 0)
10161 (org-indent-line-function)
10162 (beginning-of-line 2)
10163 (org-indent-line-function)
10164 (end-of-line 0)))
10165 ((and org-log-state-notes-insert-after-drawers
10166 (save-excursion
10167 (forward-line) (looking-at org-drawer-regexp)))
10168 (forward-line)
10169 (while (looking-at org-drawer-regexp)
10170 (goto-char (match-end 0))
10171 (re-search-forward org-property-end-re (point-max) t)
10172 (forward-line))
10173 (forward-line -1)))
10174 (unless org-log-states-order-reversed
10175 (and (= (char-after) ?\n) (forward-char 1))
10176 (org-skip-over-state-notes)
10177 (skip-chars-backward " \t\n\r")))
10178 (move-marker org-log-note-marker (point))
10179 (setq org-log-note-purpose purpose
10180 org-log-note-state state
10181 org-log-note-previous-state prev-state
10182 org-log-note-how how
10183 org-log-note-extra extra)
10184 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10186 (defun org-skip-over-state-notes ()
10187 "Skip past the list of State notes in an entry."
10188 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10189 (while (looking-at "[ \t]*- State")
10190 (condition-case nil
10191 (org-next-item)
10192 (error (org-end-of-item)))))
10194 (defun org-add-log-note (&optional purpose)
10195 "Pop up a window for taking a note, and add this note later at point."
10196 (remove-hook 'post-command-hook 'org-add-log-note)
10197 (setq org-log-note-window-configuration (current-window-configuration))
10198 (delete-other-windows)
10199 (move-marker org-log-note-return-to (point))
10200 (switch-to-buffer (marker-buffer org-log-note-marker))
10201 (goto-char org-log-note-marker)
10202 (org-switch-to-buffer-other-window "*Org Note*")
10203 (erase-buffer)
10204 (if (memq org-log-note-how '(time state))
10205 (let (current-prefix-arg) (org-store-log-note))
10206 (let ((org-inhibit-startup t)) (org-mode))
10207 (insert (format "# Insert note for %s.
10208 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10209 (cond
10210 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10211 ((eq org-log-note-purpose 'done) "closed todo item")
10212 ((eq org-log-note-purpose 'state)
10213 (format "state change from \"%s\" to \"%s\""
10214 (or org-log-note-previous-state "")
10215 (or org-log-note-state "")))
10216 ((eq org-log-note-purpose 'note)
10217 "this entry")
10218 (t (error "This should not happen")))))
10219 (if org-log-note-extra (insert org-log-note-extra))
10220 (org-set-local 'org-finish-function 'org-store-log-note)))
10222 (defvar org-note-abort nil) ; dynamically scoped
10223 (defun org-store-log-note ()
10224 "Finish taking a log note, and insert it to where it belongs."
10225 (let ((txt (buffer-string))
10226 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10227 lines ind)
10228 (kill-buffer (current-buffer))
10229 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10230 (setq txt (replace-match "" t t txt)))
10231 (if (string-match "\\s-+\\'" txt)
10232 (setq txt (replace-match "" t t txt)))
10233 (setq lines (org-split-string txt "\n"))
10234 (when (and note (string-match "\\S-" note))
10235 (setq note
10236 (org-replace-escapes
10237 note
10238 (list (cons "%u" (user-login-name))
10239 (cons "%U" user-full-name)
10240 (cons "%t" (format-time-string
10241 (org-time-stamp-format 'long 'inactive)
10242 (current-time)))
10243 (cons "%s" (if org-log-note-state
10244 (concat "\"" org-log-note-state "\"")
10245 ""))
10246 (cons "%S" (if org-log-note-previous-state
10247 (concat "\"" org-log-note-previous-state "\"")
10248 "\"\"")))))
10249 (if lines (setq note (concat note " \\\\")))
10250 (push note lines))
10251 (when (or current-prefix-arg org-note-abort)
10252 (when org-log-into-drawer
10253 (org-remove-empty-drawer-at
10254 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10255 org-log-note-marker))
10256 (setq lines nil))
10257 (when lines
10258 (save-excursion
10259 (set-buffer (marker-buffer org-log-note-marker))
10260 (save-excursion
10261 (goto-char org-log-note-marker)
10262 (move-marker org-log-note-marker nil)
10263 (end-of-line 1)
10264 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10265 (insert "- " (pop lines))
10266 (org-indent-line-function)
10267 (beginning-of-line 1)
10268 (looking-at "[ \t]*")
10269 (setq ind (concat (match-string 0) " "))
10270 (end-of-line 1)
10271 (while lines (insert "\n" ind (pop lines)))
10272 (message "Note stored")
10273 (org-back-to-heading t)
10274 (org-cycle-hide-drawers 'children)))))
10275 (set-window-configuration org-log-note-window-configuration)
10276 (with-current-buffer (marker-buffer org-log-note-return-to)
10277 (goto-char org-log-note-return-to))
10278 (move-marker org-log-note-return-to nil)
10279 (and org-log-post-message (message "%s" org-log-post-message)))
10281 (defun org-remove-empty-drawer-at (drawer pos)
10282 "Remove an emptyr DARWER drawer at position POS.
10283 POS may also be a marker."
10284 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10285 (save-excursion
10286 (save-restriction
10287 (widen)
10288 (goto-char pos)
10289 (if (org-in-regexp
10290 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10291 (replace-match ""))))))
10293 (defun org-sparse-tree (&optional arg)
10294 "Create a sparse tree, prompt for the details.
10295 This command can create sparse trees. You first need to select the type
10296 of match used to create the tree:
10298 t Show entries with a specific TODO keyword.
10299 m Show entries selected by a tags/property match.
10300 p Enter a property name and its value (both with completion on existing
10301 names/values) and show entries with that property.
10302 r Show entries matching a regular expression.
10303 d Show deadlines due within `org-deadline-warning-days'.
10304 b Show deadlines and scheduled items before a date.
10305 a Show deadlines and scheduled items after a date."
10306 (interactive "P")
10307 (let (ans kwd value)
10308 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10309 (setq ans (read-char-exclusive))
10310 (cond
10311 ((equal ans ?d)
10312 (call-interactively 'org-check-deadlines))
10313 ((equal ans ?b)
10314 (call-interactively 'org-check-before-date))
10315 ((equal ans ?a)
10316 (call-interactively 'org-check-after-date))
10317 ((equal ans ?t)
10318 (org-show-todo-tree '(4)))
10319 ((member ans '(?T ?m))
10320 (call-interactively 'org-match-sparse-tree))
10321 ((member ans '(?p ?P))
10322 (setq kwd (org-icompleting-read "Property: "
10323 (mapcar 'list (org-buffer-property-keys))))
10324 (setq value (org-icompleting-read "Value: "
10325 (mapcar 'list (org-property-values kwd))))
10326 (unless (string-match "\\`{.*}\\'" value)
10327 (setq value (concat "\"" value "\"")))
10328 (org-match-sparse-tree arg (concat kwd "=" value)))
10329 ((member ans '(?r ?R ?/))
10330 (call-interactively 'org-occur))
10331 (t (error "No such sparse tree command \"%c\"" ans)))))
10333 (defvar org-occur-highlights nil
10334 "List of overlays used for occur matches.")
10335 (make-variable-buffer-local 'org-occur-highlights)
10336 (defvar org-occur-parameters nil
10337 "Parameters of the active org-occur calls.
10338 This is a list, each call to org-occur pushes as cons cell,
10339 containing the regular expression and the callback, onto the list.
10340 The list can contain several entries if `org-occur' has been called
10341 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10342 will only contain one set of parameters. When the highlights are
10343 removed (for example with `C-c C-c', or with the next edit (depending
10344 on `org-remove-highlights-with-change'), this variable is emptied
10345 as well.")
10346 (make-variable-buffer-local 'org-occur-parameters)
10348 (defun org-occur (regexp &optional keep-previous callback)
10349 "Make a compact tree which shows all matches of REGEXP.
10350 The tree will show the lines where the regexp matches, and all higher
10351 headlines above the match. It will also show the heading after the match,
10352 to make sure editing the matching entry is easy.
10353 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10354 call to `org-occur' will be kept, to allow stacking of calls to this
10355 command.
10356 If CALLBACK is non-nil, it is a function which is called to confirm
10357 that the match should indeed be shown."
10358 (interactive "sRegexp: \nP")
10359 (when (equal regexp "")
10360 (error "Regexp cannot be empty"))
10361 (unless keep-previous
10362 (org-remove-occur-highlights nil nil t))
10363 (push (cons regexp callback) org-occur-parameters)
10364 (let ((cnt 0))
10365 (save-excursion
10366 (goto-char (point-min))
10367 (if (or (not keep-previous) ; do not want to keep
10368 (not org-occur-highlights)) ; no previous matches
10369 ;; hide everything
10370 (org-overview))
10371 (while (re-search-forward regexp nil t)
10372 (when (or (not callback)
10373 (save-match-data (funcall callback)))
10374 (setq cnt (1+ cnt))
10375 (when org-highlight-sparse-tree-matches
10376 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10377 (org-show-context 'occur-tree))))
10378 (when org-remove-highlights-with-change
10379 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10380 nil 'local))
10381 (unless org-sparse-tree-open-archived-trees
10382 (org-hide-archived-subtrees (point-min) (point-max)))
10383 (run-hooks 'org-occur-hook)
10384 (if (interactive-p)
10385 (message "%d match(es) for regexp %s" cnt regexp))
10386 cnt))
10388 (defun org-show-context (&optional key)
10389 "Make sure point and context and visible.
10390 How much context is shown depends upon the variables
10391 `org-show-hierarchy-above', `org-show-following-heading'. and
10392 `org-show-siblings'."
10393 (let ((heading-p (org-on-heading-p t))
10394 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10395 (following-p (org-get-alist-option org-show-following-heading key))
10396 (entry-p (org-get-alist-option org-show-entry-below key))
10397 (siblings-p (org-get-alist-option org-show-siblings key)))
10398 (catch 'exit
10399 ;; Show heading or entry text
10400 (if (and heading-p (not entry-p))
10401 (org-flag-heading nil) ; only show the heading
10402 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10403 (org-show-hidden-entry))) ; show entire entry
10404 (when following-p
10405 ;; Show next sibling, or heading below text
10406 (save-excursion
10407 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10408 (org-flag-heading nil))))
10409 (when siblings-p (org-show-siblings))
10410 (when hierarchy-p
10411 ;; show all higher headings, possibly with siblings
10412 (save-excursion
10413 (while (and (condition-case nil
10414 (progn (org-up-heading-all 1) t)
10415 (error nil))
10416 (not (bobp)))
10417 (org-flag-heading nil)
10418 (when siblings-p (org-show-siblings))))))))
10420 (defun org-reveal (&optional siblings)
10421 "Show current entry, hierarchy above it, and the following headline.
10422 This can be used to show a consistent set of context around locations
10423 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10424 not t for the search context.
10426 With optional argument SIBLINGS, on each level of the hierarchy all
10427 siblings are shown. This repairs the tree structure to what it would
10428 look like when opened with hierarchical calls to `org-cycle'."
10429 (interactive "P")
10430 (let ((org-show-hierarchy-above t)
10431 (org-show-following-heading t)
10432 (org-show-siblings (if siblings t org-show-siblings)))
10433 (org-show-context nil)))
10435 (defun org-highlight-new-match (beg end)
10436 "Highlight from BEG to END and mark the highlight is an occur headline."
10437 (let ((ov (org-make-overlay beg end)))
10438 (org-overlay-put ov 'face 'secondary-selection)
10439 (push ov org-occur-highlights)))
10441 (defun org-remove-occur-highlights (&optional beg end noremove)
10442 "Remove the occur highlights from the buffer.
10443 BEG and END are ignored. If NOREMOVE is nil, remove this function
10444 from the `before-change-functions' in the current buffer."
10445 (interactive)
10446 (unless org-inhibit-highlight-removal
10447 (mapc 'org-delete-overlay org-occur-highlights)
10448 (setq org-occur-highlights nil)
10449 (setq org-occur-parameters nil)
10450 (unless noremove
10451 (remove-hook 'before-change-functions
10452 'org-remove-occur-highlights 'local))))
10454 ;;;; Priorities
10456 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10457 "Regular expression matching the priority indicator.")
10459 (defvar org-remove-priority-next-time nil)
10461 (defun org-priority-up ()
10462 "Increase the priority of the current item."
10463 (interactive)
10464 (org-priority 'up))
10466 (defun org-priority-down ()
10467 "Decrease the priority of the current item."
10468 (interactive)
10469 (org-priority 'down))
10471 (defun org-priority (&optional action)
10472 "Change the priority of an item by ARG.
10473 ACTION can be `set', `up', `down', or a character."
10474 (interactive)
10475 (unless org-enable-priority-commands
10476 (error "Priority commands are disabled"))
10477 (setq action (or action 'set))
10478 (let (current new news have remove)
10479 (save-excursion
10480 (org-back-to-heading t)
10481 (if (looking-at org-priority-regexp)
10482 (setq current (string-to-char (match-string 2))
10483 have t)
10484 (setq current org-default-priority))
10485 (cond
10486 ((or (eq action 'set)
10487 (if (featurep 'xemacs) (characterp action) (integerp action)))
10488 (if (not (eq action 'set))
10489 (setq new action)
10490 (message "Priority %c-%c, SPC to remove: "
10491 org-highest-priority org-lowest-priority)
10492 (setq new (read-char-exclusive)))
10493 (if (and (= (upcase org-highest-priority) org-highest-priority)
10494 (= (upcase org-lowest-priority) org-lowest-priority))
10495 (setq new (upcase new)))
10496 (cond ((equal new ?\ ) (setq remove t))
10497 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10498 (error "Priority must be between `%c' and `%c'"
10499 org-highest-priority org-lowest-priority))))
10500 ((eq action 'up)
10501 (if (and (not have) (eq last-command this-command))
10502 (setq new org-lowest-priority)
10503 (setq new (if (and org-priority-start-cycle-with-default (not have))
10504 org-default-priority (1- current)))))
10505 ((eq action 'down)
10506 (if (and (not have) (eq last-command this-command))
10507 (setq new org-highest-priority)
10508 (setq new (if (and org-priority-start-cycle-with-default (not have))
10509 org-default-priority (1+ current)))))
10510 (t (error "Invalid action")))
10511 (if (or (< (upcase new) org-highest-priority)
10512 (> (upcase new) org-lowest-priority))
10513 (setq remove t))
10514 (setq news (format "%c" new))
10515 (if have
10516 (if remove
10517 (replace-match "" t t nil 1)
10518 (replace-match news t t nil 2))
10519 (if remove
10520 (error "No priority cookie found in line")
10521 (let ((case-fold-search nil))
10522 (looking-at org-todo-line-regexp))
10523 (if (match-end 2)
10524 (progn
10525 (goto-char (match-end 2))
10526 (insert " [#" news "]"))
10527 (goto-char (match-beginning 3))
10528 (insert "[#" news "] "))))
10529 (org-preserve-lc (org-set-tags nil 'align)))
10530 (if remove
10531 (message "Priority removed")
10532 (message "Priority of current item set to %s" news))))
10534 (defun org-get-priority (s)
10535 "Find priority cookie and return priority."
10536 (save-match-data
10537 (if (not (string-match org-priority-regexp s))
10538 (* 1000 (- org-lowest-priority org-default-priority))
10539 (* 1000 (- org-lowest-priority
10540 (string-to-char (match-string 2 s)))))))
10542 ;;;; Tags
10544 (defvar org-agenda-archives-mode)
10545 (defvar org-map-continue-from nil
10546 "Position from where mapping should continue.
10547 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10549 (defvar org-scanner-tags nil
10550 "The current tag list while the tags scanner is running.")
10551 (defvar org-trust-scanner-tags nil
10552 "Should `org-get-tags-at' use the tags fro the scanner.
10553 This is for internal dynamical scoping only.
10554 When this is non-nil, the function `org-get-tags-at' will return the value
10555 of `org-scanner-tags' instead of building the list by itself. This
10556 can lead to large speed-ups when the tags scanner is used in a file with
10557 many entries, and when the list of tags is retrieved, for example to
10558 obtain a list of properties. Building the tags list for each entry in such
10559 a file becomes an N^2 operation - but with this variable set, it scales
10560 as N.")
10562 (defun org-scan-tags (action matcher &optional todo-only)
10563 "Scan headline tags with inheritance and produce output ACTION.
10565 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10566 or `agenda' to produce an entry list for an agenda view. It can also be
10567 a Lisp form or a function that should be called at each matched headline, in
10568 this case the return value is a list of all return values from these calls.
10570 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10571 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10572 only lines with a TODO keyword are included in the output."
10573 (require 'org-agenda)
10574 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10575 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10576 (org-re
10577 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10578 (props (list 'face 'default
10579 'done-face 'org-agenda-done
10580 'undone-face 'default
10581 'mouse-face 'highlight
10582 'org-not-done-regexp org-not-done-regexp
10583 'org-todo-regexp org-todo-regexp
10584 'keymap org-agenda-keymap
10585 'help-echo
10586 (format "mouse-2 or RET jump to org file %s"
10587 (abbreviate-file-name
10588 (or (buffer-file-name (buffer-base-buffer))
10589 (buffer-name (buffer-base-buffer)))))))
10590 (case-fold-search nil)
10591 (org-map-continue-from nil)
10592 lspos tags tags-list
10593 (tags-alist (list (cons 0 org-file-tags)))
10594 (llast 0) rtn rtn1 level category i txt
10595 todo marker entry priority)
10596 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10597 (setq action (list 'lambda nil action)))
10598 (save-excursion
10599 (goto-char (point-min))
10600 (when (eq action 'sparse-tree)
10601 (org-overview)
10602 (org-remove-occur-highlights))
10603 (while (re-search-forward re nil t)
10604 (catch :skip
10605 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10606 tags (if (match-end 4) (org-match-string-no-properties 4)))
10607 (goto-char (setq lspos (match-beginning 0)))
10608 (setq level (org-reduced-level (funcall outline-level))
10609 category (org-get-category))
10610 (setq i llast llast level)
10611 ;; remove tag lists from same and sublevels
10612 (while (>= i level)
10613 (when (setq entry (assoc i tags-alist))
10614 (setq tags-alist (delete entry tags-alist)))
10615 (setq i (1- i)))
10616 ;; add the next tags
10617 (when tags
10618 (setq tags (org-split-string tags ":")
10619 tags-alist
10620 (cons (cons level tags) tags-alist)))
10621 ;; compile tags for current headline
10622 (setq tags-list
10623 (if org-use-tag-inheritance
10624 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10625 tags)
10626 org-scanner-tags tags-list)
10627 (when org-use-tag-inheritance
10628 (setcdr (car tags-alist)
10629 (mapcar (lambda (x)
10630 (setq x (copy-sequence x))
10631 (org-add-prop-inherited x))
10632 (cdar tags-alist))))
10633 (when (and tags org-use-tag-inheritance
10634 (or (not (eq t org-use-tag-inheritance))
10635 org-tags-exclude-from-inheritance))
10636 ;; selective inheritance, remove uninherited ones
10637 (setcdr (car tags-alist)
10638 (org-remove-uniherited-tags (cdar tags-alist))))
10639 (when (and (or (not todo-only)
10640 (and (member todo org-not-done-keywords)
10641 (or (not org-agenda-tags-todo-honor-ignore-options)
10642 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10643 (let ((case-fold-search t)) (eval matcher))
10645 (not (member org-archive-tag tags-list))
10646 ;; we have an archive tag, should we use this anyway?
10647 (or (not org-agenda-skip-archived-trees)
10648 (and (eq action 'agenda) org-agenda-archives-mode))))
10649 (unless (eq action 'sparse-tree) (org-agenda-skip))
10651 ;; select this headline
10653 (cond
10654 ((eq action 'sparse-tree)
10655 (and org-highlight-sparse-tree-matches
10656 (org-get-heading) (match-end 0)
10657 (org-highlight-new-match
10658 (match-beginning 0) (match-beginning 1)))
10659 (org-show-context 'tags-tree))
10660 ((eq action 'agenda)
10661 (setq txt (org-format-agenda-item
10663 (concat
10664 (if (eq org-tags-match-list-sublevels 'indented)
10665 (make-string (1- level) ?.) "")
10666 (org-get-heading))
10667 category
10668 tags-list
10670 priority (org-get-priority txt))
10671 (goto-char lspos)
10672 (setq marker (org-agenda-new-marker))
10673 (org-add-props txt props
10674 'org-marker marker 'org-hd-marker marker 'org-category category
10675 'todo-state todo
10676 'priority priority 'type "tagsmatch")
10677 (push txt rtn))
10678 ((functionp action)
10679 (setq org-map-continue-from nil)
10680 (save-excursion
10681 (setq rtn1 (funcall action))
10682 (push rtn1 rtn)))
10683 (t (error "Invalid action")))
10685 ;; if we are to skip sublevels, jump to end of subtree
10686 (unless org-tags-match-list-sublevels
10687 (org-end-of-subtree t)
10688 (backward-char 1))))
10689 ;; Get the correct position from where to continue
10690 (if org-map-continue-from
10691 (goto-char org-map-continue-from)
10692 (and (= (point) lspos) (end-of-line 1)))))
10693 (when (and (eq action 'sparse-tree)
10694 (not org-sparse-tree-open-archived-trees))
10695 (org-hide-archived-subtrees (point-min) (point-max)))
10696 (nreverse rtn)))
10698 (defun org-remove-uniherited-tags (tags)
10699 "Remove all tags that are not inherited from the list TAGS."
10700 (cond
10701 ((eq org-use-tag-inheritance t)
10702 (if org-tags-exclude-from-inheritance
10703 (org-delete-all org-tags-exclude-from-inheritance tags)
10704 tags))
10705 ((not org-use-tag-inheritance) nil)
10706 ((stringp org-use-tag-inheritance)
10707 (delq nil (mapcar
10708 (lambda (x)
10709 (if (and (string-match org-use-tag-inheritance x)
10710 (not (member x org-tags-exclude-from-inheritance)))
10711 x nil))
10712 tags)))
10713 ((listp org-use-tag-inheritance)
10714 (delq nil (mapcar
10715 (lambda (x)
10716 (if (member x org-use-tag-inheritance) x nil))
10717 tags)))))
10719 (defvar todo-only) ;; dynamically scoped
10721 (defun org-match-sparse-tree (&optional todo-only match)
10722 "Create a sparse tree according to tags string MATCH.
10723 MATCH can contain positive and negative selection of tags, like
10724 \"+WORK+URGENT-WITHBOSS\".
10725 If optional argument TODO-ONLY is non-nil, only select lines that are
10726 also TODO lines."
10727 (interactive "P")
10728 (org-prepare-agenda-buffers (list (current-buffer)))
10729 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10731 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10733 (defvar org-cached-props nil)
10734 (defun org-cached-entry-get (pom property)
10735 (if (or (eq t org-use-property-inheritance)
10736 (and (stringp org-use-property-inheritance)
10737 (string-match org-use-property-inheritance property))
10738 (and (listp org-use-property-inheritance)
10739 (member property org-use-property-inheritance)))
10740 ;; Caching is not possible, check it directly
10741 (org-entry-get pom property 'inherit)
10742 ;; Get all properties, so that we can do complicated checks easily
10743 (cdr (assoc property (or org-cached-props
10744 (setq org-cached-props
10745 (org-entry-properties pom)))))))
10747 (defun org-global-tags-completion-table (&optional files)
10748 "Return the list of all tags in all agenda buffer/files."
10749 (save-excursion
10750 (org-uniquify
10751 (delq nil
10752 (apply 'append
10753 (mapcar
10754 (lambda (file)
10755 (set-buffer (find-file-noselect file))
10756 (append (org-get-buffer-tags)
10757 (mapcar (lambda (x) (if (stringp (car-safe x))
10758 (list (car-safe x)) nil))
10759 org-tag-alist)))
10760 (if (and files (car files))
10761 files
10762 (org-agenda-files))))))))
10764 (defun org-make-tags-matcher (match)
10765 "Create the TAGS//TODO matcher form for the selection string MATCH."
10766 ;; todo-only is scoped dynamically into this function, and the function
10767 ;; may change it if the matcher asks for it.
10768 (unless match
10769 ;; Get a new match request, with completion
10770 (let ((org-last-tags-completion-table
10771 (org-global-tags-completion-table)))
10772 (setq match (org-completing-read-no-i
10773 "Match: " 'org-tags-completion-function nil nil nil
10774 'org-tags-history))))
10776 ;; Parse the string and create a lisp form
10777 (let ((match0 match)
10778 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10779 minus tag mm
10780 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10781 orterms term orlist re-p str-p level-p level-op time-p
10782 prop-p pn pv po cat-p gv rest)
10783 (if (string-match "/+" match)
10784 ;; match contains also a todo-matching request
10785 (progn
10786 (setq tagsmatch (substring match 0 (match-beginning 0))
10787 todomatch (substring match (match-end 0)))
10788 (if (string-match "^!" todomatch)
10789 (setq todo-only t todomatch (substring todomatch 1)))
10790 (if (string-match "^\\s-*$" todomatch)
10791 (setq todomatch nil)))
10792 ;; only matching tags
10793 (setq tagsmatch match todomatch nil))
10795 ;; Make the tags matcher
10796 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10797 (setq tagsmatcher t)
10798 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10799 (while (setq term (pop orterms))
10800 (while (and (equal (substring term -1) "\\") orterms)
10801 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10802 (while (string-match re term)
10803 (setq rest (substring term (match-end 0))
10804 minus (and (match-end 1)
10805 (equal (match-string 1 term) "-"))
10806 tag (match-string 2 term)
10807 re-p (equal (string-to-char tag) ?{)
10808 level-p (match-end 4)
10809 prop-p (match-end 5)
10810 mm (cond
10811 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10812 (level-p
10813 (setq level-op (org-op-to-function (match-string 3 term)))
10814 `(,level-op level ,(string-to-number
10815 (match-string 4 term))))
10816 (prop-p
10817 (setq pn (match-string 5 term)
10818 po (match-string 6 term)
10819 pv (match-string 7 term)
10820 cat-p (equal pn "CATEGORY")
10821 re-p (equal (string-to-char pv) ?{)
10822 str-p (equal (string-to-char pv) ?\")
10823 time-p (save-match-data
10824 (string-match "^\"[[<].*[]>]\"$" pv))
10825 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10826 (if time-p (setq pv (org-matcher-time pv)))
10827 (setq po (org-op-to-function po (if time-p 'time str-p)))
10828 (cond
10829 ((equal pn "CATEGORY")
10830 (setq gv '(get-text-property (point) 'org-category)))
10831 ((equal pn "TODO")
10832 (setq gv 'todo))
10834 (setq gv `(org-cached-entry-get nil ,pn))))
10835 (if re-p
10836 (if (eq po 'org<>)
10837 `(not (string-match ,pv (or ,gv "")))
10838 `(string-match ,pv (or ,gv "")))
10839 (if str-p
10840 `(,po (or ,gv "") ,pv)
10841 `(,po (string-to-number (or ,gv ""))
10842 ,(string-to-number pv) ))))
10843 (t `(member ,tag tags-list)))
10844 mm (if minus (list 'not mm) mm)
10845 term rest)
10846 (push mm tagsmatcher))
10847 (push (if (> (length tagsmatcher) 1)
10848 (cons 'and tagsmatcher)
10849 (car tagsmatcher))
10850 orlist)
10851 (setq tagsmatcher nil))
10852 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10853 (setq tagsmatcher
10854 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10855 ;; Make the todo matcher
10856 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10857 (setq todomatcher t)
10858 (setq orterms (org-split-string todomatch "|") orlist nil)
10859 (while (setq term (pop orterms))
10860 (while (string-match re term)
10861 (setq minus (and (match-end 1)
10862 (equal (match-string 1 term) "-"))
10863 kwd (match-string 2 term)
10864 re-p (equal (string-to-char kwd) ?{)
10865 term (substring term (match-end 0))
10866 mm (if re-p
10867 `(string-match ,(substring kwd 1 -1) todo)
10868 (list 'equal 'todo kwd))
10869 mm (if minus (list 'not mm) mm))
10870 (push mm todomatcher))
10871 (push (if (> (length todomatcher) 1)
10872 (cons 'and todomatcher)
10873 (car todomatcher))
10874 orlist)
10875 (setq todomatcher nil))
10876 (setq todomatcher (if (> (length orlist) 1)
10877 (cons 'or orlist) (car orlist))))
10879 ;; Return the string and lisp forms of the matcher
10880 (setq matcher (if todomatcher
10881 (list 'and tagsmatcher todomatcher)
10882 tagsmatcher))
10883 (cons match0 matcher)))
10885 (defun org-op-to-function (op &optional stringp)
10886 "Turn an operator into the appropriate function."
10887 (setq op
10888 (cond
10889 ((equal op "<" ) '(< string< org-time<))
10890 ((equal op ">" ) '(> org-string> org-time>))
10891 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10892 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10893 ((member op '("=" "==")) '(= string= org-time=))
10894 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10895 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10897 (defun org<> (a b) (not (= a b)))
10898 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10899 (defun org-string>= (a b) (not (string< a b)))
10900 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10901 (defun org-string<> (a b) (not (string= a b)))
10902 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10903 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10904 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10905 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10906 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10907 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10908 (defun org-2ft (s)
10909 "Convert S to a floating point time.
10910 If S is already a number, just return it. If it is a string, parse
10911 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10912 (cond
10913 ((numberp s) s)
10914 ((stringp s)
10915 (condition-case nil
10916 (float-time (apply 'encode-time (org-parse-time-string s)))
10917 (error 0.)))
10918 (t 0.)))
10920 (defun org-time-today ()
10921 "Time in seconds today at 0:00.
10922 Returns the float number of seconds since the beginning of the
10923 epoch to the beginning of today (00:00)."
10924 (float-time (apply 'encode-time
10925 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10927 (defun org-matcher-time (s)
10928 "Interpret a time comparison value."
10929 (save-match-data
10930 (cond
10931 ((string= s "<now>") (float-time))
10932 ((string= s "<today>") (org-time-today))
10933 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10934 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10935 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10936 (+ (org-time-today)
10937 (* (string-to-number (match-string 1 s))
10938 (cdr (assoc (match-string 2 s)
10939 '(("d" . 86400.0) ("w" . 604800.0)
10940 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10941 (t (org-2ft s)))))
10943 (defun org-match-any-p (re list)
10944 "Does re match any element of list?"
10945 (setq list (mapcar (lambda (x) (string-match re x)) list))
10946 (delq nil list))
10948 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10949 (defvar org-tags-overlay (org-make-overlay 1 1))
10950 (org-detach-overlay org-tags-overlay)
10952 (defun org-get-local-tags-at (&optional pos)
10953 "Get a list of tags defined in the current headline."
10954 (org-get-tags-at pos 'local))
10956 (defun org-get-local-tags ()
10957 "Get a list of tags defined in the current headline."
10958 (org-get-tags-at nil 'local))
10960 (defun org-get-tags-at (&optional pos local)
10961 "Get a list of all headline tags applicable at POS.
10962 POS defaults to point. If tags are inherited, the list contains
10963 the targets in the same sequence as the headlines appear, i.e.
10964 the tags of the current headline come last.
10965 When LOCAL is non-nil, only return tags from the current headline,
10966 ignore inherited ones."
10967 (interactive)
10968 (if (and org-trust-scanner-tags
10969 (or (not pos) (equal pos (point)))
10970 (not local))
10971 org-scanner-tags
10972 (let (tags ltags lastpos parent)
10973 (save-excursion
10974 (save-restriction
10975 (widen)
10976 (goto-char (or pos (point)))
10977 (save-match-data
10978 (catch 'done
10979 (condition-case nil
10980 (progn
10981 (org-back-to-heading t)
10982 (while (not (equal lastpos (point)))
10983 (setq lastpos (point))
10984 (when (looking-at
10985 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10986 (setq ltags (org-split-string
10987 (org-match-string-no-properties 1) ":"))
10988 (when parent
10989 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10990 (setq tags (append
10991 (if parent
10992 (org-remove-uniherited-tags ltags)
10993 ltags)
10994 tags)))
10995 (or org-use-tag-inheritance (throw 'done t))
10996 (if local (throw 'done t))
10997 (or (org-up-heading-safe) (error nil))
10998 (setq parent t)))
10999 (error nil)))))
11000 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11002 (defun org-add-prop-inherited (s)
11003 (add-text-properties 0 (length s) '(inherited t) s)
11006 (defun org-toggle-tag (tag &optional onoff)
11007 "Toggle the tag TAG for the current line.
11008 If ONOFF is `on' or `off', don't toggle but set to this state."
11009 (let (res current)
11010 (save-excursion
11011 (org-back-to-heading t)
11012 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11013 (point-at-eol) t)
11014 (progn
11015 (setq current (match-string 1))
11016 (replace-match ""))
11017 (setq current ""))
11018 (setq current (nreverse (org-split-string current ":")))
11019 (cond
11020 ((eq onoff 'on)
11021 (setq res t)
11022 (or (member tag current) (push tag current)))
11023 ((eq onoff 'off)
11024 (or (not (member tag current)) (setq current (delete tag current))))
11025 (t (if (member tag current)
11026 (setq current (delete tag current))
11027 (setq res t)
11028 (push tag current))))
11029 (end-of-line 1)
11030 (if current
11031 (progn
11032 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11033 (org-set-tags nil t))
11034 (delete-horizontal-space))
11035 (run-hooks 'org-after-tags-change-hook))
11036 res))
11038 (defun org-align-tags-here (to-col)
11039 ;; Assumes that this is a headline
11040 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11041 (beginning-of-line 1)
11042 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11043 (< pos (match-beginning 2)))
11044 (progn
11045 (setq tags-l (- (match-end 2) (match-beginning 2)))
11046 (goto-char (match-beginning 1))
11047 (insert " ")
11048 (delete-region (point) (1+ (match-beginning 2)))
11049 (setq ncol (max (1+ (current-column))
11050 (1+ col)
11051 (if (> to-col 0)
11052 to-col
11053 (- (abs to-col) tags-l))))
11054 (setq p (point))
11055 (insert (make-string (- ncol (current-column)) ?\ ))
11056 (setq ncol (current-column))
11057 (when indent-tabs-mode (tabify p (point-at-eol)))
11058 (org-move-to-column (min ncol col) t))
11059 (goto-char pos))))
11061 (defun org-set-tags-command (&optional arg just-align)
11062 "Call the set-tags command for the current entry."
11063 (interactive "P")
11064 (if (org-on-heading-p)
11065 (org-set-tags arg just-align)
11066 (save-excursion
11067 (org-back-to-heading t)
11068 (org-set-tags arg just-align))))
11070 (defun org-set-tags (&optional arg just-align)
11071 "Set the tags for the current headline.
11072 With prefix ARG, realign all tags in headings in the current buffer."
11073 (interactive "P")
11074 (let* ((re (concat "^" outline-regexp))
11075 (current (org-get-tags-string))
11076 (col (current-column))
11077 (org-setting-tags t)
11078 table current-tags inherited-tags ; computed below when needed
11079 tags p0 c0 c1 rpl)
11080 (if arg
11081 (save-excursion
11082 (goto-char (point-min))
11083 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11084 (while (re-search-forward re nil t)
11085 (org-set-tags nil t)
11086 (end-of-line 1)))
11087 (message "All tags realigned to column %d" org-tags-column))
11088 (if just-align
11089 (setq tags current)
11090 ;; Get a new set of tags from the user
11091 (save-excursion
11092 (setq table (append org-tag-persistent-alist
11093 (or org-tag-alist (org-get-buffer-tags)))
11094 org-last-tags-completion-table table
11095 current-tags (org-split-string current ":")
11096 inherited-tags (nreverse
11097 (nthcdr (length current-tags)
11098 (nreverse (org-get-tags-at))))
11099 tags
11100 (if (or (eq t org-use-fast-tag-selection)
11101 (and org-use-fast-tag-selection
11102 (delq nil (mapcar 'cdr table))))
11103 (org-fast-tag-selection
11104 current-tags inherited-tags table
11105 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11106 (let ((org-add-colon-after-tag-completion t))
11107 (org-trim
11108 (org-without-partial-completion
11109 (org-icompleting-read "Tags: " 'org-tags-completion-function
11110 nil nil current 'org-tags-history)))))))
11111 (while (string-match "[-+&]+" tags)
11112 ;; No boolean logic, just a list
11113 (setq tags (replace-match ":" t t tags))))
11115 (if org-tags-sort-function
11116 (setq tags (mapconcat 'identity
11117 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11118 org-tags-sort-function) ":")))
11120 (if (string-match "\\`[\t ]*\\'" tags)
11121 (setq tags "")
11122 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11123 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11125 ;; Insert new tags at the correct column
11126 (beginning-of-line 1)
11127 (cond
11128 ((and (equal current "") (equal tags "")))
11129 ((re-search-forward
11130 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11131 (point-at-eol) t)
11132 (if (equal tags "")
11133 (setq rpl "")
11134 (goto-char (match-beginning 0))
11135 (setq c0 (current-column) p0 (point)
11136 c1 (max (1+ c0) (if (> org-tags-column 0)
11137 org-tags-column
11138 (- (- org-tags-column) (length tags))))
11139 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11140 (replace-match rpl t t)
11141 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11142 tags)
11143 (t (error "Tags alignment failed")))
11144 (org-move-to-column col)
11145 (unless just-align
11146 (run-hooks 'org-after-tags-change-hook)))))
11148 (defun org-change-tag-in-region (beg end tag off)
11149 "Add or remove TAG for each entry in the region.
11150 This works in the agenda, and also in an org-mode buffer."
11151 (interactive
11152 (list (region-beginning) (region-end)
11153 (let ((org-last-tags-completion-table
11154 (if (org-mode-p)
11155 (org-get-buffer-tags)
11156 (org-global-tags-completion-table))))
11157 (org-icompleting-read
11158 "Tag: " 'org-tags-completion-function nil nil nil
11159 'org-tags-history))
11160 (progn
11161 (message "[s]et or [r]emove? ")
11162 (equal (read-char-exclusive) ?r))))
11163 (if (fboundp 'deactivate-mark) (deactivate-mark))
11164 (let ((agendap (equal major-mode 'org-agenda-mode))
11165 l1 l2 m buf pos newhead (cnt 0))
11166 (goto-char end)
11167 (setq l2 (1- (org-current-line)))
11168 (goto-char beg)
11169 (setq l1 (org-current-line))
11170 (loop for l from l1 to l2 do
11171 (org-goto-line l)
11172 (setq m (get-text-property (point) 'org-hd-marker))
11173 (when (or (and (org-mode-p) (org-on-heading-p))
11174 (and agendap m))
11175 (setq buf (if agendap (marker-buffer m) (current-buffer))
11176 pos (if agendap m (point)))
11177 (with-current-buffer buf
11178 (save-excursion
11179 (save-restriction
11180 (goto-char pos)
11181 (setq cnt (1+ cnt))
11182 (org-toggle-tag tag (if off 'off 'on))
11183 (setq newhead (org-get-heading)))))
11184 (and agendap (org-agenda-change-all-lines newhead m))))
11185 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11187 (defun org-tags-completion-function (string predicate &optional flag)
11188 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11189 (confirm (lambda (x) (stringp (car x)))))
11190 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11191 (setq s1 (match-string 1 string)
11192 s2 (match-string 2 string))
11193 (setq s1 "" s2 string))
11194 (cond
11195 ((eq flag nil)
11196 ;; try completion
11197 (setq rtn (try-completion s2 ctable confirm))
11198 (if (stringp rtn)
11199 (setq rtn
11200 (concat s1 s2 (substring rtn (length s2))
11201 (if (and org-add-colon-after-tag-completion
11202 (assoc rtn ctable))
11203 ":" ""))))
11204 rtn)
11205 ((eq flag t)
11206 ;; all-completions
11207 (all-completions s2 ctable confirm)
11209 ((eq flag 'lambda)
11210 ;; exact match?
11211 (assoc s2 ctable)))
11214 (defun org-fast-tag-insert (kwd tags face &optional end)
11215 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11216 (insert (format "%-12s" (concat kwd ":"))
11217 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11218 (or end "")))
11220 (defun org-fast-tag-show-exit (flag)
11221 (save-excursion
11222 (org-goto-line 3)
11223 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11224 (replace-match ""))
11225 (when flag
11226 (end-of-line 1)
11227 (org-move-to-column (- (window-width) 19) t)
11228 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11230 (defun org-set-current-tags-overlay (current prefix)
11231 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11232 (if (featurep 'xemacs)
11233 (org-overlay-display org-tags-overlay (concat prefix s)
11234 'secondary-selection)
11235 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11236 (org-overlay-display org-tags-overlay (concat prefix s)))))
11238 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11239 "Fast tag selection with single keys.
11240 CURRENT is the current list of tags in the headline, INHERITED is the
11241 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11242 possibly with grouping information. TODO-TABLE is a similar table with
11243 TODO keywords, should these have keys assigned to them.
11244 If the keys are nil, a-z are automatically assigned.
11245 Returns the new tags string, or nil to not change the current settings."
11246 (let* ((fulltable (append table todo-table))
11247 (maxlen (apply 'max (mapcar
11248 (lambda (x)
11249 (if (stringp (car x)) (string-width (car x)) 0))
11250 fulltable)))
11251 (buf (current-buffer))
11252 (expert (eq org-fast-tag-selection-single-key 'expert))
11253 (buffer-tags nil)
11254 (fwidth (+ maxlen 3 1 3))
11255 (ncol (/ (- (window-width) 4) fwidth))
11256 (i-face 'org-done)
11257 (c-face 'org-todo)
11258 tg cnt e c char c1 c2 ntable tbl rtn
11259 ov-start ov-end ov-prefix
11260 (exit-after-next org-fast-tag-selection-single-key)
11261 (done-keywords org-done-keywords)
11262 groups ingroup)
11263 (save-excursion
11264 (beginning-of-line 1)
11265 (if (looking-at
11266 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11267 (setq ov-start (match-beginning 1)
11268 ov-end (match-end 1)
11269 ov-prefix "")
11270 (setq ov-start (1- (point-at-eol))
11271 ov-end (1+ ov-start))
11272 (skip-chars-forward "^\n\r")
11273 (setq ov-prefix
11274 (concat
11275 (buffer-substring (1- (point)) (point))
11276 (if (> (current-column) org-tags-column)
11278 (make-string (- org-tags-column (current-column)) ?\ ))))))
11279 (org-move-overlay org-tags-overlay ov-start ov-end)
11280 (save-window-excursion
11281 (if expert
11282 (set-buffer (get-buffer-create " *Org tags*"))
11283 (delete-other-windows)
11284 (split-window-vertically)
11285 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11286 (erase-buffer)
11287 (org-set-local 'org-done-keywords done-keywords)
11288 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11289 (org-fast-tag-insert "Current" current c-face "\n\n")
11290 (org-fast-tag-show-exit exit-after-next)
11291 (org-set-current-tags-overlay current ov-prefix)
11292 (setq tbl fulltable char ?a cnt 0)
11293 (while (setq e (pop tbl))
11294 (cond
11295 ((equal e '(:startgroup))
11296 (push '() groups) (setq ingroup t)
11297 (when (not (= cnt 0))
11298 (setq cnt 0)
11299 (insert "\n"))
11300 (insert "{ "))
11301 ((equal e '(:endgroup))
11302 (setq ingroup nil cnt 0)
11303 (insert "}\n"))
11304 ((equal e '(:newline))
11305 (when (not (= cnt 0))
11306 (setq cnt 0)
11307 (insert "\n")
11308 (setq e (car tbl))
11309 (while (equal (car tbl) '(:newline))
11310 (insert "\n")
11311 (setq tbl (cdr tbl)))))
11313 (setq tg (copy-sequence (car e)) c2 nil)
11314 (if (cdr e)
11315 (setq c (cdr e))
11316 ;; automatically assign a character.
11317 (setq c1 (string-to-char
11318 (downcase (substring
11319 tg (if (= (string-to-char tg) ?@) 1 0)))))
11320 (if (or (rassoc c1 ntable) (rassoc c1 table))
11321 (while (or (rassoc char ntable) (rassoc char table))
11322 (setq char (1+ char)))
11323 (setq c2 c1))
11324 (setq c (or c2 char)))
11325 (if ingroup (push tg (car groups)))
11326 (setq tg (org-add-props tg nil 'face
11327 (cond
11328 ((not (assoc tg table))
11329 (org-get-todo-face tg))
11330 ((member tg current) c-face)
11331 ((member tg inherited) i-face)
11332 (t nil))))
11333 (if (and (= cnt 0) (not ingroup)) (insert " "))
11334 (insert "[" c "] " tg (make-string
11335 (- fwidth 4 (length tg)) ?\ ))
11336 (push (cons tg c) ntable)
11337 (when (= (setq cnt (1+ cnt)) ncol)
11338 (insert "\n")
11339 (if ingroup (insert " "))
11340 (setq cnt 0)))))
11341 (setq ntable (nreverse ntable))
11342 (insert "\n")
11343 (goto-char (point-min))
11344 (if (not expert) (org-fit-window-to-buffer))
11345 (setq rtn
11346 (catch 'exit
11347 (while t
11348 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11349 (if groups " [!] no groups" " [!]groups")
11350 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11351 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11352 (cond
11353 ((= c ?\r) (throw 'exit t))
11354 ((= c ?!)
11355 (setq groups (not groups))
11356 (goto-char (point-min))
11357 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11358 ((= c ?\C-c)
11359 (if (not expert)
11360 (org-fast-tag-show-exit
11361 (setq exit-after-next (not exit-after-next)))
11362 (setq expert nil)
11363 (delete-other-windows)
11364 (split-window-vertically)
11365 (org-switch-to-buffer-other-window " *Org tags*")
11366 (org-fit-window-to-buffer)))
11367 ((or (= c ?\C-g)
11368 (and (= c ?q) (not (rassoc c ntable))))
11369 (org-detach-overlay org-tags-overlay)
11370 (setq quit-flag t))
11371 ((= c ?\ )
11372 (setq current nil)
11373 (if exit-after-next (setq exit-after-next 'now)))
11374 ((= c ?\t)
11375 (condition-case nil
11376 (setq tg (org-icompleting-read
11377 "Tag: "
11378 (or buffer-tags
11379 (with-current-buffer buf
11380 (org-get-buffer-tags)))))
11381 (quit (setq tg "")))
11382 (when (string-match "\\S-" tg)
11383 (add-to-list 'buffer-tags (list tg))
11384 (if (member tg current)
11385 (setq current (delete tg current))
11386 (push tg current)))
11387 (if exit-after-next (setq exit-after-next 'now)))
11388 ((setq e (rassoc c todo-table) tg (car e))
11389 (with-current-buffer buf
11390 (save-excursion (org-todo tg)))
11391 (if exit-after-next (setq exit-after-next 'now)))
11392 ((setq e (rassoc c ntable) tg (car e))
11393 (if (member tg current)
11394 (setq current (delete tg current))
11395 (loop for g in groups do
11396 (if (member tg g)
11397 (mapc (lambda (x)
11398 (setq current (delete x current)))
11399 g)))
11400 (push tg current))
11401 (if exit-after-next (setq exit-after-next 'now))))
11403 ;; Create a sorted list
11404 (setq current
11405 (sort current
11406 (lambda (a b)
11407 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11408 (if (eq exit-after-next 'now) (throw 'exit t))
11409 (goto-char (point-min))
11410 (beginning-of-line 2)
11411 (delete-region (point) (point-at-eol))
11412 (org-fast-tag-insert "Current" current c-face)
11413 (org-set-current-tags-overlay current ov-prefix)
11414 (while (re-search-forward
11415 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11416 (setq tg (match-string 1))
11417 (add-text-properties
11418 (match-beginning 1) (match-end 1)
11419 (list 'face
11420 (cond
11421 ((member tg current) c-face)
11422 ((member tg inherited) i-face)
11423 (t (get-text-property (match-beginning 1) 'face))))))
11424 (goto-char (point-min)))))
11425 (org-detach-overlay org-tags-overlay)
11426 (if rtn
11427 (mapconcat 'identity current ":")
11428 nil))))
11430 (defun org-get-tags-string ()
11431 "Get the TAGS string in the current headline."
11432 (unless (org-on-heading-p t)
11433 (error "Not on a heading"))
11434 (save-excursion
11435 (beginning-of-line 1)
11436 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11437 (org-match-string-no-properties 1)
11438 "")))
11440 (defun org-get-tags ()
11441 "Get the list of tags specified in the current headline."
11442 (org-split-string (org-get-tags-string) ":"))
11444 (defun org-get-buffer-tags ()
11445 "Get a table of all tags used in the buffer, for completion."
11446 (let (tags)
11447 (save-excursion
11448 (goto-char (point-min))
11449 (while (re-search-forward
11450 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11451 (when (equal (char-after (point-at-bol 0)) ?*)
11452 (mapc (lambda (x) (add-to-list 'tags x))
11453 (org-split-string (org-match-string-no-properties 1) ":")))))
11454 (mapcar 'list tags)))
11456 ;;;; The mapping API
11458 ;;;###autoload
11459 (defun org-map-entries (func &optional match scope &rest skip)
11460 "Call FUNC at each headline selected by MATCH in SCOPE.
11462 FUNC is a function or a lisp form. The function will be called without
11463 arguments, with the cursor positioned at the beginning of the headline.
11464 The return values of all calls to the function will be collected and
11465 returned as a list.
11467 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11468 does not need to preserve point. After evaluation, the cursor will be
11469 moved to the end of the line (presumably of the headline of the
11470 processed entry) and search continues from there. Under some
11471 circumstances, this may not produce the wanted results. For example,
11472 if you have removed (e.g. archived) the current (sub)tree it could
11473 mean that the next entry will be skipped entirely. In such cases, you
11474 can specify the position from where search should continue by making
11475 FUNC set the variable `org-map-continue-from' to the desired buffer
11476 position.
11478 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11479 Only headlines that are matched by this query will be considered during
11480 the iteration. When MATCH is nil or t, all headlines will be
11481 visited by the iteration.
11483 SCOPE determines the scope of this command. It can be any of:
11485 nil The current buffer, respecting the restriction if any
11486 tree The subtree started with the entry at point
11487 file The current buffer, without restriction
11488 file-with-archives
11489 The current buffer, and any archives associated with it
11490 agenda All agenda files
11491 agenda-with-archives
11492 All agenda files with any archive files associated with them
11493 \(file1 file2 ...)
11494 If this is a list, all files in the list will be scanned
11496 The remaining args are treated as settings for the skipping facilities of
11497 the scanner. The following items can be given here:
11499 archive skip trees with the archive tag.
11500 comment skip trees with the COMMENT keyword
11501 function or Emacs Lisp form:
11502 will be used as value for `org-agenda-skip-function', so whenever
11503 the the function returns t, FUNC will not be called for that
11504 entry and search will continue from the point where the
11505 function leaves it.
11507 If your function needs to retrieve the tags including inherited tags
11508 at the *current* entry, you can use the value of the variable
11509 `org-scanner-tags' which will be much faster than getting the value
11510 with `org-get-tags-at'. If your function gets properties with
11511 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11512 to t around the call to `org-entry-properties' to get the same speedup.
11513 Note that if your function moves around to retrieve tags and properties at
11514 a *different* entry, you cannot use these techniques."
11515 (let* ((org-agenda-archives-mode nil) ; just to make sure
11516 (org-agenda-skip-archived-trees (memq 'archive skip))
11517 (org-agenda-skip-comment-trees (memq 'comment skip))
11518 (org-agenda-skip-function
11519 (car (org-delete-all '(comment archive) skip)))
11520 (org-tags-match-list-sublevels t)
11521 matcher file res
11522 org-todo-keywords-for-agenda
11523 org-done-keywords-for-agenda
11524 org-todo-keyword-alist-for-agenda
11525 org-tag-alist-for-agenda)
11527 (cond
11528 ((eq match t) (setq matcher t))
11529 ((eq match nil) (setq matcher t))
11530 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11532 (save-excursion
11533 (save-restriction
11534 (when (eq scope 'tree)
11535 (org-back-to-heading t)
11536 (org-narrow-to-subtree)
11537 (setq scope nil))
11539 (if (not scope)
11540 (progn
11541 (org-prepare-agenda-buffers
11542 (list (buffer-file-name (current-buffer))))
11543 (setq res (org-scan-tags func matcher)))
11544 ;; Get the right scope
11545 (cond
11546 ((and scope (listp scope) (symbolp (car scope)))
11547 (setq scope (eval scope)))
11548 ((eq scope 'agenda)
11549 (setq scope (org-agenda-files t)))
11550 ((eq scope 'agenda-with-archives)
11551 (setq scope (org-agenda-files t))
11552 (setq scope (org-add-archive-files scope)))
11553 ((eq scope 'file)
11554 (setq scope (list (buffer-file-name))))
11555 ((eq scope 'file-with-archives)
11556 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11557 (org-prepare-agenda-buffers scope)
11558 (while (setq file (pop scope))
11559 (with-current-buffer (org-find-base-buffer-visiting file)
11560 (save-excursion
11561 (save-restriction
11562 (widen)
11563 (goto-char (point-min))
11564 (setq res (append res (org-scan-tags func matcher))))))))))
11565 res))
11567 ;;;; Properties
11569 ;;; Setting and retrieving properties
11571 (defconst org-special-properties
11572 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11573 "TIMESTAMP" "TIMESTAMP_IA")
11574 "The special properties valid in Org-mode.
11576 These are properties that are not defined in the property drawer,
11577 but in some other way.")
11579 (defconst org-default-properties
11580 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11581 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11582 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11583 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11584 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11585 "CLOCK_MODELINE_TOTAL")
11586 "Some properties that are used by Org-mode for various purposes.
11587 Being in this list makes sure that they are offered for completion.")
11589 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11590 "Regular expression matching the first line of a property drawer.")
11592 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11593 "Regular expression matching the first line of a property drawer.")
11595 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11596 "Regular expression matching the first line of a property drawer.")
11598 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11599 "Regular expression matching the first line of a property drawer.")
11601 (defconst org-property-drawer-re
11602 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11603 org-property-end-re "\\)\n?")
11604 "Matches an entire property drawer.")
11606 (defconst org-clock-drawer-re
11607 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11608 org-property-end-re "\\)\n?")
11609 "Matches an entire clock drawer.")
11611 (defun org-property-action ()
11612 "Do an action on properties."
11613 (interactive)
11614 (let (c)
11615 (org-at-property-p)
11616 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11617 (setq c (read-char-exclusive))
11618 (cond
11619 ((equal c ?s)
11620 (call-interactively 'org-set-property))
11621 ((equal c ?d)
11622 (call-interactively 'org-delete-property))
11623 ((equal c ?D)
11624 (call-interactively 'org-delete-property-globally))
11625 ((equal c ?c)
11626 (call-interactively 'org-compute-property-at-point))
11627 (t (error "No such property action %c" c)))))
11629 (defun org-at-property-p ()
11630 "Is the cursor in a property line?"
11631 ;; FIXME: Does not check if we are actually in the drawer.
11632 ;; FIXME: also returns true on any drawers.....
11633 ;; This is used by C-c C-c for property action.
11634 (save-excursion
11635 (beginning-of-line 1)
11636 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11638 (defun org-get-property-block (&optional beg end force)
11639 "Return the (beg . end) range of the body of the property drawer.
11640 BEG and END can be beginning and end of subtree, if not given
11641 they will be found.
11642 If the drawer does not exist and FORCE is non-nil, create the drawer."
11643 (catch 'exit
11644 (save-excursion
11645 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11646 (end (or end (progn (outline-next-heading) (point)))))
11647 (goto-char beg)
11648 (if (re-search-forward org-property-start-re end t)
11649 (setq beg (1+ (match-end 0)))
11650 (if force
11651 (save-excursion
11652 (org-insert-property-drawer)
11653 (setq end (progn (outline-next-heading) (point))))
11654 (throw 'exit nil))
11655 (goto-char beg)
11656 (if (re-search-forward org-property-start-re end t)
11657 (setq beg (1+ (match-end 0)))))
11658 (if (re-search-forward org-property-end-re end t)
11659 (setq end (match-beginning 0))
11660 (or force (throw 'exit nil))
11661 (goto-char beg)
11662 (setq end beg)
11663 (org-indent-line-function)
11664 (insert ":END:\n"))
11665 (cons beg end)))))
11667 (defun org-entry-properties (&optional pom which)
11668 "Get all properties of the entry at point-or-marker POM.
11669 This includes the TODO keyword, the tags, time strings for deadline,
11670 scheduled, and clocking, and any additional properties defined in the
11671 entry. The return value is an alist, keys may occur multiple times
11672 if the property key was used several times.
11673 POM may also be nil, in which case the current entry is used.
11674 If WHICH is nil or `all', get all properties. If WHICH is
11675 `special' or `standard', only get that subclass."
11676 (setq which (or which 'all))
11677 (org-with-point-at pom
11678 (let ((clockstr (substring org-clock-string 0 -1))
11679 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11680 beg end range props sum-props key value string clocksum)
11681 (save-excursion
11682 (when (condition-case nil
11683 (and (org-mode-p) (org-back-to-heading t))
11684 (error nil))
11685 (setq beg (point))
11686 (setq sum-props (get-text-property (point) 'org-summaries))
11687 (setq clocksum (get-text-property (point) :org-clock-minutes))
11688 (outline-next-heading)
11689 (setq end (point))
11690 (when (memq which '(all special))
11691 ;; Get the special properties, like TODO and tags
11692 (goto-char beg)
11693 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11694 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11695 (when (looking-at org-priority-regexp)
11696 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11697 (when (and (setq value (org-get-tags-string))
11698 (string-match "\\S-" value))
11699 (push (cons "TAGS" value) props))
11700 (when (setq value (org-get-tags-at))
11701 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11702 props))
11703 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11704 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11705 string (if (equal key clockstr)
11706 (org-no-properties
11707 (org-trim
11708 (buffer-substring
11709 (match-beginning 3) (goto-char (point-at-eol)))))
11710 (substring (org-match-string-no-properties 3) 1 -1)))
11711 (unless key
11712 (if (= (char-after (match-beginning 3)) ?\[)
11713 (setq key "TIMESTAMP_IA")
11714 (setq key "TIMESTAMP")))
11715 (when (or (equal key clockstr) (not (assoc key props)))
11716 (push (cons key string) props)))
11720 (when (memq which '(all standard))
11721 ;; Get the standard properties, like :PROP: ...
11722 (setq range (org-get-property-block beg end))
11723 (when range
11724 (goto-char (car range))
11725 (while (re-search-forward
11726 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11727 (cdr range) t)
11728 (setq key (org-match-string-no-properties 1)
11729 value (org-trim (or (org-match-string-no-properties 2) "")))
11730 (unless (member key excluded)
11731 (push (cons key (or value "")) props)))))
11732 (if clocksum
11733 (push (cons "CLOCKSUM"
11734 (org-columns-number-to-string (/ (float clocksum) 60.)
11735 'add_times))
11736 props))
11737 (unless (assoc "CATEGORY" props)
11738 (setq value (or (org-get-category)
11739 (progn (org-refresh-category-properties)
11740 (org-get-category))))
11741 (push (cons "CATEGORY" value) props))
11742 (append sum-props (nreverse props)))))))
11744 (defun org-entry-get (pom property &optional inherit)
11745 "Get value of PROPERTY for entry at point-or-marker POM.
11746 If INHERIT is non-nil and the entry does not have the property,
11747 then also check higher levels of the hierarchy.
11748 If INHERIT is the symbol `selective', use inheritance only if the setting
11749 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11750 If the property is present but empty, the return value is the empty string.
11751 If the property is not present at all, nil is returned."
11752 (org-with-point-at pom
11753 (if (and inherit (if (eq inherit 'selective)
11754 (org-property-inherit-p property)
11756 (org-entry-get-with-inheritance property)
11757 (if (member property org-special-properties)
11758 ;; We need a special property. Use brute force, get all properties.
11759 (cdr (assoc property (org-entry-properties nil 'special)))
11760 (let ((range (org-get-property-block)))
11761 (if (and range
11762 (goto-char (car range))
11763 (re-search-forward
11764 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11765 (cdr range) t))
11766 ;; Found the property, return it.
11767 (if (match-end 1)
11768 (org-match-string-no-properties 1)
11769 "")))))))
11771 (defun org-property-or-variable-value (var &optional inherit)
11772 "Check if there is a property fixing the value of VAR.
11773 If yes, return this value. If not, return the current value of the variable."
11774 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11775 (if (and prop (stringp prop) (string-match "\\S-" prop))
11776 (read prop)
11777 (symbol-value var))))
11779 (defun org-entry-delete (pom property)
11780 "Delete the property PROPERTY from entry at point-or-marker POM."
11781 (org-with-point-at pom
11782 (if (member property org-special-properties)
11783 nil ; cannot delete these properties.
11784 (let ((range (org-get-property-block)))
11785 (if (and range
11786 (goto-char (car range))
11787 (re-search-forward
11788 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11789 (cdr range) t))
11790 (progn
11791 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11793 nil)))))
11795 ;; Multi-values properties are properties that contain multiple values
11796 ;; These values are assumed to be single words, separated by whitespace.
11797 (defun org-entry-add-to-multivalued-property (pom property value)
11798 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11799 (let* ((old (org-entry-get pom property))
11800 (values (and old (org-split-string old "[ \t]"))))
11801 (setq value (org-entry-protect-space value))
11802 (unless (member value values)
11803 (setq values (cons value values))
11804 (org-entry-put pom property
11805 (mapconcat 'identity values " ")))))
11807 (defun org-entry-remove-from-multivalued-property (pom property value)
11808 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11809 (let* ((old (org-entry-get pom property))
11810 (values (and old (org-split-string old "[ \t]"))))
11811 (setq value (org-entry-protect-space value))
11812 (when (member value values)
11813 (setq values (delete value values))
11814 (org-entry-put pom property
11815 (mapconcat 'identity values " ")))))
11817 (defun org-entry-member-in-multivalued-property (pom property value)
11818 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11819 (let* ((old (org-entry-get pom property))
11820 (values (and old (org-split-string old "[ \t]"))))
11821 (setq value (org-entry-protect-space value))
11822 (member value values)))
11824 (defun org-entry-get-multivalued-property (pom property)
11825 "Return a list of values in a multivalued property."
11826 (let* ((value (org-entry-get pom property))
11827 (values (and value (org-split-string value "[ \t]"))))
11828 (mapcar 'org-entry-restore-space values)))
11830 (defun org-entry-put-multivalued-property (pom property &rest values)
11831 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11832 VALUES should be a list of strings. Spaces will be protected."
11833 (org-entry-put pom property
11834 (mapconcat 'org-entry-protect-space values " "))
11835 (let* ((value (org-entry-get pom property))
11836 (values (and value (org-split-string value "[ \t]"))))
11837 (mapcar 'org-entry-restore-space values)))
11839 (defun org-entry-protect-space (s)
11840 "Protect spaces and newline in string S."
11841 (while (string-match " " s)
11842 (setq s (replace-match "%20" t t s)))
11843 (while (string-match "\n" s)
11844 (setq s (replace-match "%0A" t t s)))
11847 (defun org-entry-restore-space (s)
11848 "Restore spaces and newline in string S."
11849 (while (string-match "%20" s)
11850 (setq s (replace-match " " t t s)))
11851 (while (string-match "%0A" s)
11852 (setq s (replace-match "\n" t t s)))
11855 (defvar org-entry-property-inherited-from (make-marker)
11856 "Marker pointing to the entry from where a property was inherited.
11857 Each call to `org-entry-get-with-inheritance' will set this marker to the
11858 location of the entry where the inheritance search matched. If there was
11859 no match, the marker will point nowhere.
11860 Note that also `org-entry-get' calls this function, if the INHERIT flag
11861 is set.")
11863 (defun org-entry-get-with-inheritance (property)
11864 "Get entry property, and search higher levels if not present."
11865 (move-marker org-entry-property-inherited-from nil)
11866 (let (tmp)
11867 (save-excursion
11868 (save-restriction
11869 (widen)
11870 (catch 'ex
11871 (while t
11872 (when (setq tmp (org-entry-get nil property))
11873 (org-back-to-heading t)
11874 (move-marker org-entry-property-inherited-from (point))
11875 (throw 'ex tmp))
11876 (or (org-up-heading-safe) (throw 'ex nil)))))
11877 (or tmp
11878 (cdr (assoc property org-file-properties))
11879 (cdr (assoc property org-global-properties))
11880 (cdr (assoc property org-global-properties-fixed))))))
11882 (defun org-entry-put (pom property value)
11883 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11884 (org-with-point-at pom
11885 (org-back-to-heading t)
11886 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11887 range)
11888 (cond
11889 ((equal property "TODO")
11890 (when (and (stringp value) (string-match "\\S-" value)
11891 (not (member value org-todo-keywords-1)))
11892 (error "\"%s\" is not a valid TODO state" value))
11893 (if (or (not value)
11894 (not (string-match "\\S-" value)))
11895 (setq value 'none))
11896 (org-todo value)
11897 (org-set-tags nil 'align))
11898 ((equal property "PRIORITY")
11899 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11900 (string-to-char value) ?\ ))
11901 (org-set-tags nil 'align))
11902 ((equal property "SCHEDULED")
11903 (if (re-search-forward org-scheduled-time-regexp end t)
11904 (cond
11905 ((eq value 'earlier) (org-timestamp-change -1 'day))
11906 ((eq value 'later) (org-timestamp-change 1 'day))
11907 (t (call-interactively 'org-schedule)))
11908 (call-interactively 'org-schedule)))
11909 ((equal property "DEADLINE")
11910 (if (re-search-forward org-deadline-time-regexp end t)
11911 (cond
11912 ((eq value 'earlier) (org-timestamp-change -1 'day))
11913 ((eq value 'later) (org-timestamp-change 1 'day))
11914 (t (call-interactively 'org-deadline)))
11915 (call-interactively 'org-deadline)))
11916 ((member property org-special-properties)
11917 (error "The %s property can not yet be set with `org-entry-put'"
11918 property))
11919 (t ; a non-special property
11920 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11921 (setq range (org-get-property-block beg end 'force))
11922 (goto-char (car range))
11923 (if (re-search-forward
11924 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11925 (progn
11926 (delete-region (match-beginning 1) (match-end 1))
11927 (goto-char (match-beginning 1)))
11928 (goto-char (cdr range))
11929 (insert "\n")
11930 (backward-char 1)
11931 (org-indent-line-function)
11932 (insert ":" property ":"))
11933 (and value (insert " " value))
11934 (org-indent-line-function)))))))
11936 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11937 "Get all property keys in the current buffer.
11938 With INCLUDE-SPECIALS, also list the special properties that reflect things
11939 like tags and TODO state.
11940 With INCLUDE-DEFAULTS, also include properties that has special meaning
11941 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11942 With INCLUDE-COLUMNS, also include property names given in COLUMN
11943 formats in the current buffer."
11944 (let (rtn range cfmt s p)
11945 (save-excursion
11946 (save-restriction
11947 (widen)
11948 (goto-char (point-min))
11949 (while (re-search-forward org-property-start-re nil t)
11950 (setq range (org-get-property-block))
11951 (goto-char (car range))
11952 (while (re-search-forward
11953 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11954 (cdr range) t)
11955 (add-to-list 'rtn (org-match-string-no-properties 1)))
11956 (outline-next-heading))))
11958 (when include-specials
11959 (setq rtn (append org-special-properties rtn)))
11961 (when include-defaults
11962 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11963 (add-to-list 'rtn org-effort-property))
11965 (when include-columns
11966 (save-excursion
11967 (save-restriction
11968 (widen)
11969 (goto-char (point-min))
11970 (while (re-search-forward
11971 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11972 nil t)
11973 (setq cfmt (match-string 2) s 0)
11974 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11975 cfmt s)
11976 (setq s (match-end 0)
11977 p (match-string 1 cfmt))
11978 (unless (or (equal p "ITEM")
11979 (member p org-special-properties))
11980 (add-to-list 'rtn (match-string 1 cfmt))))))))
11982 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11984 (defun org-property-values (key)
11985 "Return a list of all values of property KEY."
11986 (save-excursion
11987 (save-restriction
11988 (widen)
11989 (goto-char (point-min))
11990 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11991 values)
11992 (while (re-search-forward re nil t)
11993 (add-to-list 'values (org-trim (match-string 1))))
11994 (delete "" values)))))
11996 (defun org-insert-property-drawer ()
11997 "Insert a property drawer into the current entry."
11998 (interactive)
11999 (org-back-to-heading t)
12000 (looking-at outline-regexp)
12001 (let ((indent (if org-adapt-indentation
12002 (- (match-end 0)(match-beginning 0))
12004 (beg (point))
12005 (re (concat "^[ \t]*" org-keyword-time-regexp))
12006 end hiddenp)
12007 (outline-next-heading)
12008 (setq end (point))
12009 (goto-char beg)
12010 (while (re-search-forward re end t))
12011 (setq hiddenp (org-invisible-p))
12012 (end-of-line 1)
12013 (and (equal (char-after) ?\n) (forward-char 1))
12014 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12015 (if (member (match-string 1) '("CLOCK:" ":END:"))
12016 ;; just skip this line
12017 (beginning-of-line 2)
12018 ;; Drawer start, find the end
12019 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12020 (beginning-of-line 1)))
12021 (org-skip-over-state-notes)
12022 (skip-chars-backward " \t\n\r")
12023 (if (eq (char-before) ?*) (forward-char 1))
12024 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12025 (beginning-of-line 0)
12026 (org-indent-to-column indent)
12027 (beginning-of-line 2)
12028 (org-indent-to-column indent)
12029 (beginning-of-line 0)
12030 (if hiddenp
12031 (save-excursion
12032 (org-back-to-heading t)
12033 (hide-entry))
12034 (org-flag-drawer t))))
12036 (defun org-set-property (property value)
12037 "In the current entry, set PROPERTY to VALUE.
12038 When called interactively, this will prompt for a property name, offering
12039 completion on existing and default properties. And then it will prompt
12040 for a value, offering completion either on allowed values (via an inherited
12041 xxx_ALL property) or on existing values in other instances of this property
12042 in the current file."
12043 (interactive
12044 (let* ((completion-ignore-case t)
12045 (keys (org-buffer-property-keys nil t t))
12046 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12047 (prop (if (member prop0 keys)
12048 prop0
12049 (or (cdr (assoc (downcase prop0)
12050 (mapcar (lambda (x) (cons (downcase x) x))
12051 keys)))
12052 prop0)))
12053 (cur (org-entry-get nil prop))
12054 (allowed (org-property-get-allowed-values nil prop 'table))
12055 (existing (mapcar 'list (org-property-values prop)))
12056 (val (if allowed
12057 (org-completing-read "Value: " allowed nil 'req-match)
12058 (let (org-completion-use-ido org-completion-use-iswitchb)
12059 (org-completing-read
12060 (concat "Value" (if (and cur (string-match "\\S-" cur))
12061 (concat "[" cur "]") "")
12062 ": ")
12063 existing nil nil "" nil cur)))))
12064 (list prop (if (equal val "") cur val))))
12065 (unless (equal (org-entry-get nil property) value)
12066 (org-entry-put nil property value)))
12068 (defun org-delete-property (property)
12069 "In the current entry, delete PROPERTY."
12070 (interactive
12071 (let* ((completion-ignore-case t)
12072 (prop (org-icompleting-read
12073 "Property: " (org-entry-properties nil 'standard))))
12074 (list prop)))
12075 (message "Property %s %s" property
12076 (if (org-entry-delete nil property)
12077 "deleted"
12078 "was not present in the entry")))
12080 (defun org-delete-property-globally (property)
12081 "Remove PROPERTY globally, from all entries."
12082 (interactive
12083 (let* ((completion-ignore-case t)
12084 (prop (org-icompleting-read
12085 "Globally remove property: "
12086 (mapcar 'list (org-buffer-property-keys)))))
12087 (list prop)))
12088 (save-excursion
12089 (save-restriction
12090 (widen)
12091 (goto-char (point-min))
12092 (let ((cnt 0))
12093 (while (re-search-forward
12094 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12095 nil t)
12096 (setq cnt (1+ cnt))
12097 (replace-match ""))
12098 (message "Property \"%s\" removed from %d entries" property cnt)))))
12100 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12102 (defun org-compute-property-at-point ()
12103 "Compute the property at point.
12104 This looks for an enclosing column format, extracts the operator and
12105 then applies it to the property in the column format's scope."
12106 (interactive)
12107 (unless (org-at-property-p)
12108 (error "Not at a property"))
12109 (let ((prop (org-match-string-no-properties 2)))
12110 (org-columns-get-format-and-top-level)
12111 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12112 (error "No operator defined for property %s" prop))
12113 (org-columns-compute prop)))
12115 (defun org-property-get-allowed-values (pom property &optional table)
12116 "Get allowed values for the property PROPERTY.
12117 When TABLE is non-nil, return an alist that can directly be used for
12118 completion."
12119 (let (vals)
12120 (cond
12121 ((equal property "TODO")
12122 (setq vals (org-with-point-at pom
12123 (append org-todo-keywords-1 '("")))))
12124 ((equal property "PRIORITY")
12125 (let ((n org-lowest-priority))
12126 (while (>= n org-highest-priority)
12127 (push (char-to-string n) vals)
12128 (setq n (1- n)))))
12129 ((member property org-special-properties))
12131 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12133 (when (and vals (string-match "\\S-" vals))
12134 (setq vals (car (read-from-string (concat "(" vals ")"))))
12135 (setq vals (mapcar (lambda (x)
12136 (cond ((stringp x) x)
12137 ((numberp x) (number-to-string x))
12138 ((symbolp x) (symbol-name x))
12139 (t "???")))
12140 vals)))))
12141 (if table (mapcar 'list vals) vals)))
12143 (defun org-property-previous-allowed-value (&optional previous)
12144 "Switch to the next allowed value for this property."
12145 (interactive)
12146 (org-property-next-allowed-value t))
12148 (defun org-property-next-allowed-value (&optional previous)
12149 "Switch to the next allowed value for this property."
12150 (interactive)
12151 (unless (org-at-property-p)
12152 (error "Not at a property"))
12153 (let* ((key (match-string 2))
12154 (value (match-string 3))
12155 (allowed (or (org-property-get-allowed-values (point) key)
12156 (and (member value '("[ ]" "[-]" "[X]"))
12157 '("[ ]" "[X]"))))
12158 nval)
12159 (unless allowed
12160 (error "Allowed values for this property have not been defined"))
12161 (if previous (setq allowed (reverse allowed)))
12162 (if (member value allowed)
12163 (setq nval (car (cdr (member value allowed)))))
12164 (setq nval (or nval (car allowed)))
12165 (if (equal nval value)
12166 (error "Only one allowed value for this property"))
12167 (org-at-property-p)
12168 (replace-match (concat " :" key ": " nval) t t)
12169 (org-indent-line-function)
12170 (beginning-of-line 1)
12171 (skip-chars-forward " \t")))
12173 (defun org-find-entry-with-id (ident)
12174 "Locate the entry that contains the ID property with exact value IDENT.
12175 IDENT can be a string, a symbol or a number, this function will search for
12176 the string representation of it.
12177 Return the position where this entry starts, or nil if there is no such entry."
12178 (interactive "sID: ")
12179 (let ((id (cond
12180 ((stringp ident) ident)
12181 ((symbol-name ident) (symbol-name ident))
12182 ((numberp ident) (number-to-string ident))
12183 (t (error "IDENT %s must be a string, symbol or number" ident))))
12184 (case-fold-search nil))
12185 (save-excursion
12186 (save-restriction
12187 (widen)
12188 (goto-char (point-min))
12189 (when (re-search-forward
12190 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12191 nil t)
12192 (org-back-to-heading t)
12193 (point))))))
12195 ;;;; Timestamps
12197 (defvar org-last-changed-timestamp nil)
12198 (defvar org-last-inserted-timestamp nil
12199 "The last time stamp inserted with `org-insert-time-stamp'.")
12200 (defvar org-time-was-given) ; dynamically scoped parameter
12201 (defvar org-end-time-was-given) ; dynamically scoped parameter
12202 (defvar org-ts-what) ; dynamically scoped parameter
12204 (defun org-time-stamp (arg &optional inactive)
12205 "Prompt for a date/time and insert a time stamp.
12206 If the user specifies a time like HH:MM, or if this command is called
12207 with a prefix argument, the time stamp will contain date and time.
12208 Otherwise, only the date will be included. All parts of a date not
12209 specified by the user will be filled in from the current date/time.
12210 So if you press just return without typing anything, the time stamp
12211 will represent the current date/time. If there is already a timestamp
12212 at the cursor, it will be modified."
12213 (interactive "P")
12214 (let* ((ts nil)
12215 (default-time
12216 ;; Default time is either today, or, when entering a range,
12217 ;; the range start.
12218 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12219 (save-excursion
12220 (re-search-backward
12221 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12222 (- (point) 20) t)))
12223 (apply 'encode-time (org-parse-time-string (match-string 1)))
12224 (current-time)))
12225 (default-input (and ts (org-get-compact-tod ts)))
12226 org-time-was-given org-end-time-was-given time)
12227 (cond
12228 ((and (org-at-timestamp-p t)
12229 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12230 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12231 (insert "--")
12232 (setq time (let ((this-command this-command))
12233 (org-read-date arg 'totime nil nil
12234 default-time default-input)))
12235 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12236 ((org-at-timestamp-p t)
12237 (setq time (let ((this-command this-command))
12238 (org-read-date arg 'totime nil nil default-time default-input)))
12239 (when (org-at-timestamp-p t) ; just to get the match data
12240 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12241 (replace-match "")
12242 (setq org-last-changed-timestamp
12243 (org-insert-time-stamp
12244 time (or org-time-was-given arg)
12245 inactive nil nil (list org-end-time-was-given))))
12246 (message "Timestamp updated"))
12248 (setq time (let ((this-command this-command))
12249 (org-read-date arg 'totime nil nil default-time default-input)))
12250 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12251 nil nil (list org-end-time-was-given))))))
12253 ;; FIXME: can we use this for something else, like computing time differences?
12254 (defun org-get-compact-tod (s)
12255 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12256 (let* ((t1 (match-string 1 s))
12257 (h1 (string-to-number (match-string 2 s)))
12258 (m1 (string-to-number (match-string 3 s)))
12259 (t2 (and (match-end 4) (match-string 5 s)))
12260 (h2 (and t2 (string-to-number (match-string 6 s))))
12261 (m2 (and t2 (string-to-number (match-string 7 s))))
12262 dh dm)
12263 (if (not t2)
12265 (setq dh (- h2 h1) dm (- m2 m1))
12266 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12267 (concat t1 "+" (number-to-string dh)
12268 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12270 (defun org-time-stamp-inactive (&optional arg)
12271 "Insert an inactive time stamp.
12272 An inactive time stamp is enclosed in square brackets instead of angle
12273 brackets. It is inactive in the sense that it does not trigger agenda entries,
12274 does not link to the calendar and cannot be changed with the S-cursor keys.
12275 So these are more for recording a certain time/date."
12276 (interactive "P")
12277 (org-time-stamp arg 'inactive))
12279 (defvar org-date-ovl (org-make-overlay 1 1))
12280 (org-overlay-put org-date-ovl 'face 'org-warning)
12281 (org-detach-overlay org-date-ovl)
12283 (defvar org-ans1) ; dynamically scoped parameter
12284 (defvar org-ans2) ; dynamically scoped parameter
12286 (defvar org-plain-time-of-day-regexp) ; defined below
12288 (defvar org-overriding-default-time nil) ; dynamically scoped
12289 (defvar org-read-date-overlay nil)
12290 (defvar org-dcst nil) ; dynamically scoped
12291 (defvar org-read-date-history nil)
12292 (defvar org-read-date-final-answer nil)
12294 (defun org-read-date (&optional with-time to-time from-string prompt
12295 default-time default-input)
12296 "Read a date, possibly a time, and make things smooth for the user.
12297 The prompt will suggest to enter an ISO date, but you can also enter anything
12298 which will at least partially be understood by `parse-time-string'.
12299 Unrecognized parts of the date will default to the current day, month, year,
12300 hour and minute. If this command is called to replace a timestamp at point,
12301 of to enter the second timestamp of a range, the default time is taken from the
12302 existing stamp. For example,
12303 3-2-5 --> 2003-02-05
12304 feb 15 --> currentyear-02-15
12305 sep 12 9 --> 2009-09-12
12306 12:45 --> today 12:45
12307 22 sept 0:34 --> currentyear-09-22 0:34
12308 12 --> currentyear-currentmonth-12
12309 Fri --> nearest Friday (today or later)
12310 etc.
12312 Furthermore you can specify a relative date by giving, as the *first* thing
12313 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12314 change in days weeks, months, years.
12315 With a single plus or minus, the date is relative to today. With a double
12316 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12317 +4d --> four days from today
12318 +4 --> same as above
12319 +2w --> two weeks from today
12320 ++5 --> five days from default date
12322 The function understands only English month and weekday abbreviations,
12323 but this can be configured with the variables `parse-time-months' and
12324 `parse-time-weekdays'.
12326 While prompting, a calendar is popped up - you can also select the
12327 date with the mouse (button 1). The calendar shows a period of three
12328 months. To scroll it to other months, use the keys `>' and `<'.
12329 If you don't like the calendar, turn it off with
12330 \(setq org-read-date-popup-calendar nil)
12332 With optional argument TO-TIME, the date will immediately be converted
12333 to an internal time.
12334 With an optional argument WITH-TIME, the prompt will suggest to also
12335 insert a time. Note that when WITH-TIME is not set, you can still
12336 enter a time, and this function will inform the calling routine about
12337 this change. The calling routine may then choose to change the format
12338 used to insert the time stamp into the buffer to include the time.
12339 With optional argument FROM-STRING, read from this string instead from
12340 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12341 the time/date that is used for everything that is not specified by the
12342 user."
12343 (require 'parse-time)
12344 (let* ((org-time-stamp-rounding-minutes
12345 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12346 (org-dcst org-display-custom-times)
12347 (ct (org-current-time))
12348 (def (or org-overriding-default-time default-time ct))
12349 (defdecode (decode-time def))
12350 (dummy (progn
12351 (when (< (nth 2 defdecode) org-extend-today-until)
12352 (setcar (nthcdr 2 defdecode) -1)
12353 (setcar (nthcdr 1 defdecode) 59)
12354 (setq def (apply 'encode-time defdecode)
12355 defdecode (decode-time def)))))
12356 (calendar-frame-setup nil)
12357 (calendar-move-hook nil)
12358 (calendar-view-diary-initially-flag nil)
12359 (view-diary-entries-initially nil)
12360 (calendar-view-holidays-initially-flag nil)
12361 (view-calendar-holidays-initially nil)
12362 (timestr (format-time-string
12363 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12364 (prompt (concat (if prompt (concat prompt " ") "")
12365 (format "Date+time [%s]: " timestr)))
12366 ans (org-ans0 "") org-ans1 org-ans2 final)
12368 (cond
12369 (from-string (setq ans from-string))
12370 (org-read-date-popup-calendar
12371 (save-excursion
12372 (save-window-excursion
12373 (calendar)
12374 (calendar-forward-day (- (time-to-days def)
12375 (calendar-absolute-from-gregorian
12376 (calendar-current-date))))
12377 (org-eval-in-calendar nil t)
12378 (let* ((old-map (current-local-map))
12379 (map (copy-keymap calendar-mode-map))
12380 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12381 (org-defkey map (kbd "RET") 'org-calendar-select)
12382 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12383 'org-calendar-select-mouse)
12384 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12385 'org-calendar-select-mouse)
12386 (org-defkey minibuffer-local-map [(meta shift left)]
12387 (lambda () (interactive)
12388 (org-eval-in-calendar '(calendar-backward-month 1))))
12389 (org-defkey minibuffer-local-map [(meta shift right)]
12390 (lambda () (interactive)
12391 (org-eval-in-calendar '(calendar-forward-month 1))))
12392 (org-defkey minibuffer-local-map [(meta shift up)]
12393 (lambda () (interactive)
12394 (org-eval-in-calendar '(calendar-backward-year 1))))
12395 (org-defkey minibuffer-local-map [(meta shift down)]
12396 (lambda () (interactive)
12397 (org-eval-in-calendar '(calendar-forward-year 1))))
12398 (org-defkey minibuffer-local-map [?\e (shift left)]
12399 (lambda () (interactive)
12400 (org-eval-in-calendar '(calendar-backward-month 1))))
12401 (org-defkey minibuffer-local-map [?\e (shift right)]
12402 (lambda () (interactive)
12403 (org-eval-in-calendar '(calendar-forward-month 1))))
12404 (org-defkey minibuffer-local-map [?\e (shift up)]
12405 (lambda () (interactive)
12406 (org-eval-in-calendar '(calendar-backward-year 1))))
12407 (org-defkey minibuffer-local-map [?\e (shift down)]
12408 (lambda () (interactive)
12409 (org-eval-in-calendar '(calendar-forward-year 1))))
12410 (org-defkey minibuffer-local-map [(shift up)]
12411 (lambda () (interactive)
12412 (org-eval-in-calendar '(calendar-backward-week 1))))
12413 (org-defkey minibuffer-local-map [(shift down)]
12414 (lambda () (interactive)
12415 (org-eval-in-calendar '(calendar-forward-week 1))))
12416 (org-defkey minibuffer-local-map [(shift left)]
12417 (lambda () (interactive)
12418 (org-eval-in-calendar '(calendar-backward-day 1))))
12419 (org-defkey minibuffer-local-map [(shift right)]
12420 (lambda () (interactive)
12421 (org-eval-in-calendar '(calendar-forward-day 1))))
12422 (org-defkey minibuffer-local-map ">"
12423 (lambda () (interactive)
12424 (org-eval-in-calendar '(scroll-calendar-left 1))))
12425 (org-defkey minibuffer-local-map "<"
12426 (lambda () (interactive)
12427 (org-eval-in-calendar '(scroll-calendar-right 1))))
12428 (run-hooks 'org-read-date-minibuffer-setup-hook)
12429 (unwind-protect
12430 (progn
12431 (use-local-map map)
12432 (add-hook 'post-command-hook 'org-read-date-display)
12433 (setq org-ans0 (read-string prompt default-input
12434 'org-read-date-history nil))
12435 ;; org-ans0: from prompt
12436 ;; org-ans1: from mouse click
12437 ;; org-ans2: from calendar motion
12438 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12439 (remove-hook 'post-command-hook 'org-read-date-display)
12440 (use-local-map old-map)
12441 (when org-read-date-overlay
12442 (org-delete-overlay org-read-date-overlay)
12443 (setq org-read-date-overlay nil)))))))
12445 (t ; Naked prompt only
12446 (unwind-protect
12447 (setq ans (read-string prompt default-input
12448 'org-read-date-history timestr))
12449 (when org-read-date-overlay
12450 (org-delete-overlay org-read-date-overlay)
12451 (setq org-read-date-overlay nil)))))
12453 (setq final (org-read-date-analyze ans def defdecode))
12454 (setq org-read-date-final-answer ans)
12456 (if to-time
12457 (apply 'encode-time final)
12458 (if (and (boundp 'org-time-was-given) org-time-was-given)
12459 (format "%04d-%02d-%02d %02d:%02d"
12460 (nth 5 final) (nth 4 final) (nth 3 final)
12461 (nth 2 final) (nth 1 final))
12462 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12464 (defvar def)
12465 (defvar defdecode)
12466 (defvar with-time)
12467 (defun org-read-date-display ()
12468 "Display the current date prompt interpretation in the minibuffer."
12469 (when org-read-date-display-live
12470 (when org-read-date-overlay
12471 (org-delete-overlay org-read-date-overlay))
12472 (let ((p (point)))
12473 (end-of-line 1)
12474 (while (not (equal (buffer-substring
12475 (max (point-min) (- (point) 4)) (point))
12476 " "))
12477 (insert " "))
12478 (goto-char p))
12479 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12480 " " (or org-ans1 org-ans2)))
12481 (org-end-time-was-given nil)
12482 (f (org-read-date-analyze ans def defdecode))
12483 (fmts (if org-dcst
12484 org-time-stamp-custom-formats
12485 org-time-stamp-formats))
12486 (fmt (if (or with-time
12487 (and (boundp 'org-time-was-given) org-time-was-given))
12488 (cdr fmts)
12489 (car fmts)))
12490 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12491 (when (and org-end-time-was-given
12492 (string-match org-plain-time-of-day-regexp txt))
12493 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12494 org-end-time-was-given
12495 (substring txt (match-end 0)))))
12496 (setq org-read-date-overlay
12497 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12498 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12500 (defun org-read-date-analyze (ans def defdecode)
12501 "Analyse the combined answer of the date prompt."
12502 ;; FIXME: cleanup and comment
12503 (let (delta deltan deltaw deltadef year month day
12504 hour minute second wday pm h2 m2 tl wday1
12505 iso-year iso-weekday iso-week iso-year iso-date)
12507 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12508 (setq ans "+0"))
12510 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12511 (setq ans (replace-match "" t t ans)
12512 deltan (car delta)
12513 deltaw (nth 1 delta)
12514 deltadef (nth 2 delta)))
12516 ;; Check if there is an iso week date in there
12517 ;; If yes, sore the info and postpone interpreting it until the rest
12518 ;; of the parsing is done
12519 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12520 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12521 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12522 iso-week (string-to-number (match-string 2 ans)))
12523 (setq ans (replace-match "" t t ans)))
12525 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12526 (when (string-match
12527 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12528 (setq year (if (match-end 2)
12529 (string-to-number (match-string 2 ans))
12530 (string-to-number (format-time-string "%Y")))
12531 month (string-to-number (match-string 3 ans))
12532 day (string-to-number (match-string 4 ans)))
12533 (if (< year 100) (setq year (+ 2000 year)))
12534 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12535 t nil ans)))
12536 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12537 ;; If there is a time with am/pm, and *no* time without it, we convert
12538 ;; so that matching will be successful.
12539 (loop for i from 1 to 2 do ; twice, for end time as well
12540 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12541 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12542 (setq hour (string-to-number (match-string 1 ans))
12543 minute (if (match-end 3)
12544 (string-to-number (match-string 3 ans))
12546 pm (equal ?p
12547 (string-to-char (downcase (match-string 4 ans)))))
12548 (if (and (= hour 12) (not pm))
12549 (setq hour 0)
12550 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12551 (setq ans (replace-match (format "%02d:%02d" hour minute)
12552 t t ans))))
12554 ;; Check if a time range is given as a duration
12555 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12556 (setq hour (string-to-number (match-string 1 ans))
12557 h2 (+ hour (string-to-number (match-string 3 ans)))
12558 minute (string-to-number (match-string 2 ans))
12559 m2 (+ minute (if (match-end 5) (string-to-number
12560 (match-string 5 ans))0)))
12561 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12562 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12563 t t ans)))
12565 ;; Check if there is a time range
12566 (when (boundp 'org-end-time-was-given)
12567 (setq org-time-was-given nil)
12568 (when (and (string-match org-plain-time-of-day-regexp ans)
12569 (match-end 8))
12570 (setq org-end-time-was-given (match-string 8 ans))
12571 (setq ans (concat (substring ans 0 (match-beginning 7))
12572 (substring ans (match-end 7))))))
12574 (setq tl (parse-time-string ans)
12575 day (or (nth 3 tl) (nth 3 defdecode))
12576 month (or (nth 4 tl)
12577 (if (and org-read-date-prefer-future
12578 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12579 (1+ (nth 4 defdecode))
12580 (nth 4 defdecode)))
12581 year (or (nth 5 tl)
12582 (if (and org-read-date-prefer-future
12583 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12584 (1+ (nth 5 defdecode))
12585 (nth 5 defdecode)))
12586 hour (or (nth 2 tl) (nth 2 defdecode))
12587 minute (or (nth 1 tl) (nth 1 defdecode))
12588 second (or (nth 0 tl) 0)
12589 wday (nth 6 tl))
12591 ;; Special date definitions below
12592 (cond
12593 (iso-week
12594 ;; There was an iso week
12595 (setq year (or iso-year year)
12596 day (or iso-weekday wday 1)
12597 wday nil ; to make sure that the trigger below does not match
12598 iso-date (calendar-gregorian-from-absolute
12599 (calendar-absolute-from-iso
12600 (list iso-week day year))))
12601 ; FIXME: Should we also push ISO weeks into the future?
12602 ; (when (and org-read-date-prefer-future
12603 ; (not iso-year)
12604 ; (< (calendar-absolute-from-gregorian iso-date)
12605 ; (time-to-days (current-time))))
12606 ; (setq year (1+ year)
12607 ; iso-date (calendar-gregorian-from-absolute
12608 ; (calendar-absolute-from-iso
12609 ; (list iso-week day year)))))
12610 (setq month (car iso-date)
12611 year (nth 2 iso-date)
12612 day (nth 1 iso-date)))
12613 (deltan
12614 (unless deltadef
12615 (let ((now (decode-time (current-time))))
12616 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12617 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12618 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12619 ((equal deltaw "m") (setq month (+ month deltan)))
12620 ((equal deltaw "y") (setq year (+ year deltan)))))
12621 ((and wday (not (nth 3 tl)))
12622 ;; Weekday was given, but no day, so pick that day in the week
12623 ;; on or after the derived date.
12624 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12625 (unless (equal wday wday1)
12626 (setq day (+ day (% (- wday wday1 -7) 7))))))
12627 (if (and (boundp 'org-time-was-given)
12628 (nth 2 tl))
12629 (setq org-time-was-given t))
12630 (if (< year 100) (setq year (+ 2000 year)))
12631 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12632 (list second minute hour day month year)))
12634 (defvar parse-time-weekdays)
12636 (defun org-read-date-get-relative (s today default)
12637 "Check string S for special relative date string.
12638 TODAY and DEFAULT are internal times, for today and for a default.
12639 Return shift list (N what def-flag)
12640 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12641 N is the number of WHATs to shift.
12642 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12643 the DEFAULT date rather than TODAY."
12644 (when (and
12645 (string-match
12646 (concat
12647 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12648 "\\([0-9]+\\)?"
12649 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12650 "\\([ \t]\\|$\\)") s)
12651 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12652 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12653 (string-to-char (substring (match-string 1 s) -1))
12654 ?+))
12655 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12656 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12657 (what (if (match-end 3) (match-string 3 s) "d"))
12658 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12659 (date (if rel default today))
12660 (wday (nth 6 (decode-time date)))
12661 delta)
12662 (if wday1
12663 (progn
12664 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12665 (if (= dir ?-) (setq delta (- delta 7)))
12666 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12667 (list delta "d" rel))
12668 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12670 (defun org-eval-in-calendar (form &optional keepdate)
12671 "Eval FORM in the calendar window and return to current window.
12672 Also, store the cursor date in variable org-ans2."
12673 (let ((sf (selected-frame))
12674 (sw (selected-window)))
12675 (select-window (get-buffer-window "*Calendar*" t))
12676 (eval form)
12677 (when (and (not keepdate) (calendar-cursor-to-date))
12678 (let* ((date (calendar-cursor-to-date))
12679 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12680 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12681 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12682 (select-window sw)
12683 (select-frame-set-input-focus sf)))
12685 (defun org-calendar-select ()
12686 "Return to `org-read-date' with the date currently selected.
12687 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12688 (interactive)
12689 (when (calendar-cursor-to-date)
12690 (let* ((date (calendar-cursor-to-date))
12691 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12692 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12693 (if (active-minibuffer-window) (exit-minibuffer))))
12695 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12696 "Insert a date stamp for the date given by the internal TIME.
12697 WITH-HM means, use the stamp format that includes the time of the day.
12698 INACTIVE means use square brackets instead of angular ones, so that the
12699 stamp will not contribute to the agenda.
12700 PRE and POST are optional strings to be inserted before and after the
12701 stamp.
12702 The command returns the inserted time stamp."
12703 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12704 stamp)
12705 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12706 (insert-before-markers (or pre ""))
12707 (insert-before-markers (setq stamp (format-time-string fmt time)))
12708 (when (listp extra)
12709 (setq extra (car extra))
12710 (if (and (stringp extra)
12711 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12712 (setq extra (format "-%02d:%02d"
12713 (string-to-number (match-string 1 extra))
12714 (string-to-number (match-string 2 extra))))
12715 (setq extra nil)))
12716 (when extra
12717 (backward-char 1)
12718 (insert-before-markers extra)
12719 (forward-char 1))
12720 (insert-before-markers (or post ""))
12721 (setq org-last-inserted-timestamp stamp)))
12723 (defun org-toggle-time-stamp-overlays ()
12724 "Toggle the use of custom time stamp formats."
12725 (interactive)
12726 (setq org-display-custom-times (not org-display-custom-times))
12727 (unless org-display-custom-times
12728 (let ((p (point-min)) (bmp (buffer-modified-p)))
12729 (while (setq p (next-single-property-change p 'display))
12730 (if (and (get-text-property p 'display)
12731 (eq (get-text-property p 'face) 'org-date))
12732 (remove-text-properties
12733 p (setq p (next-single-property-change p 'display))
12734 '(display t))))
12735 (set-buffer-modified-p bmp)))
12736 (if (featurep 'xemacs)
12737 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12738 (org-restart-font-lock)
12739 (setq org-table-may-need-update t)
12740 (if org-display-custom-times
12741 (message "Time stamps are overlayed with custom format")
12742 (message "Time stamp overlays removed")))
12744 (defun org-display-custom-time (beg end)
12745 "Overlay modified time stamp format over timestamp between BEG and END."
12746 (let* ((ts (buffer-substring beg end))
12747 t1 w1 with-hm tf time str w2 (off 0))
12748 (save-match-data
12749 (setq t1 (org-parse-time-string ts t))
12750 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12751 (setq off (- (match-end 0) (match-beginning 0)))))
12752 (setq end (- end off))
12753 (setq w1 (- end beg)
12754 with-hm (and (nth 1 t1) (nth 2 t1))
12755 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12756 time (org-fix-decoded-time t1)
12757 str (org-add-props
12758 (format-time-string
12759 (substring tf 1 -1) (apply 'encode-time time))
12760 nil 'mouse-face 'highlight)
12761 w2 (length str))
12762 (if (not (= w2 w1))
12763 (add-text-properties (1+ beg) (+ 2 beg)
12764 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12765 (if (featurep 'xemacs)
12766 (progn
12767 (put-text-property beg end 'invisible t)
12768 (put-text-property beg end 'end-glyph (make-glyph str)))
12769 (put-text-property beg end 'display str))))
12771 (defun org-translate-time (string)
12772 "Translate all timestamps in STRING to custom format.
12773 But do this only if the variable `org-display-custom-times' is set."
12774 (when org-display-custom-times
12775 (save-match-data
12776 (let* ((start 0)
12777 (re org-ts-regexp-both)
12778 t1 with-hm inactive tf time str beg end)
12779 (while (setq start (string-match re string start))
12780 (setq beg (match-beginning 0)
12781 end (match-end 0)
12782 t1 (save-match-data
12783 (org-parse-time-string (substring string beg end) t))
12784 with-hm (and (nth 1 t1) (nth 2 t1))
12785 inactive (equal (substring string beg (1+ beg)) "[")
12786 tf (funcall (if with-hm 'cdr 'car)
12787 org-time-stamp-custom-formats)
12788 time (org-fix-decoded-time t1)
12789 str (format-time-string
12790 (concat
12791 (if inactive "[" "<") (substring tf 1 -1)
12792 (if inactive "]" ">"))
12793 (apply 'encode-time time))
12794 string (replace-match str t t string)
12795 start (+ start (length str)))))))
12796 string)
12798 (defun org-fix-decoded-time (time)
12799 "Set 0 instead of nil for the first 6 elements of time.
12800 Don't touch the rest."
12801 (let ((n 0))
12802 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12804 (defun org-days-to-time (timestamp-string)
12805 "Difference between TIMESTAMP-STRING and now in days."
12806 (- (time-to-days (org-time-string-to-time timestamp-string))
12807 (time-to-days (current-time))))
12809 (defun org-deadline-close (timestamp-string &optional ndays)
12810 "Is the time in TIMESTAMP-STRING close to the current date?"
12811 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12812 (and (< (org-days-to-time timestamp-string) ndays)
12813 (not (org-entry-is-done-p))))
12815 (defun org-get-wdays (ts)
12816 "Get the deadline lead time appropriate for timestring TS."
12817 (cond
12818 ((<= org-deadline-warning-days 0)
12819 ;; 0 or negative, enforce this value no matter what
12820 (- org-deadline-warning-days))
12821 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12822 ;; lead time is specified.
12823 (floor (* (string-to-number (match-string 1 ts))
12824 (cdr (assoc (match-string 2 ts)
12825 '(("d" . 1) ("w" . 7)
12826 ("m" . 30.4) ("y" . 365.25)))))))
12827 ;; go for the default.
12828 (t org-deadline-warning-days)))
12830 (defun org-calendar-select-mouse (ev)
12831 "Return to `org-read-date' with the date currently selected.
12832 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12833 (interactive "e")
12834 (mouse-set-point ev)
12835 (when (calendar-cursor-to-date)
12836 (let* ((date (calendar-cursor-to-date))
12837 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12838 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12839 (if (active-minibuffer-window) (exit-minibuffer))))
12841 (defun org-check-deadlines (ndays)
12842 "Check if there are any deadlines due or past due.
12843 A deadline is considered due if it happens within `org-deadline-warning-days'
12844 days from today's date. If the deadline appears in an entry marked DONE,
12845 it is not shown. The prefix arg NDAYS can be used to test that many
12846 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12847 (interactive "P")
12848 (let* ((org-warn-days
12849 (cond
12850 ((equal ndays '(4)) 100000)
12851 (ndays (prefix-numeric-value ndays))
12852 (t (abs org-deadline-warning-days))))
12853 (case-fold-search nil)
12854 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12855 (callback
12856 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12858 (message "%d deadlines past-due or due within %d days"
12859 (org-occur regexp nil callback)
12860 org-warn-days)))
12862 (defun org-check-before-date (date)
12863 "Check if there are deadlines or scheduled entries before DATE."
12864 (interactive (list (org-read-date)))
12865 (let ((case-fold-search nil)
12866 (regexp (concat "\\<\\(" org-deadline-string
12867 "\\|" org-scheduled-string
12868 "\\) *<\\([^>]+\\)>"))
12869 (callback
12870 (lambda () (time-less-p
12871 (org-time-string-to-time (match-string 2))
12872 (org-time-string-to-time date)))))
12873 (message "%d entries before %s"
12874 (org-occur regexp nil callback) date)))
12876 (defun org-check-after-date (date)
12877 "Check if there are deadlines or scheduled entries after DATE."
12878 (interactive (list (org-read-date)))
12879 (let ((case-fold-search nil)
12880 (regexp (concat "\\<\\(" org-deadline-string
12881 "\\|" org-scheduled-string
12882 "\\) *<\\([^>]+\\)>"))
12883 (callback
12884 (lambda () (not
12885 (time-less-p
12886 (org-time-string-to-time (match-string 2))
12887 (org-time-string-to-time date))))))
12888 (message "%d entries after %s"
12889 (org-occur regexp nil callback) date)))
12891 (defun org-evaluate-time-range (&optional to-buffer)
12892 "Evaluate a time range by computing the difference between start and end.
12893 Normally the result is just printed in the echo area, but with prefix arg
12894 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12895 If the time range is actually in a table, the result is inserted into the
12896 next column.
12897 For time difference computation, a year is assumed to be exactly 365
12898 days in order to avoid rounding problems."
12899 (interactive "P")
12901 (org-clock-update-time-maybe)
12902 (save-excursion
12903 (unless (org-at-date-range-p t)
12904 (goto-char (point-at-bol))
12905 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12906 (if (not (org-at-date-range-p t))
12907 (error "Not at a time-stamp range, and none found in current line")))
12908 (let* ((ts1 (match-string 1))
12909 (ts2 (match-string 2))
12910 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12911 (match-end (match-end 0))
12912 (time1 (org-time-string-to-time ts1))
12913 (time2 (org-time-string-to-time ts2))
12914 (t1 (time-to-seconds time1))
12915 (t2 (time-to-seconds time2))
12916 (diff (abs (- t2 t1)))
12917 (negative (< (- t2 t1) 0))
12918 ;; (ys (floor (* 365 24 60 60)))
12919 (ds (* 24 60 60))
12920 (hs (* 60 60))
12921 (fy "%dy %dd %02d:%02d")
12922 (fy1 "%dy %dd")
12923 (fd "%dd %02d:%02d")
12924 (fd1 "%dd")
12925 (fh "%02d:%02d")
12926 y d h m align)
12927 (if havetime
12928 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12930 d (floor (/ diff ds)) diff (mod diff ds)
12931 h (floor (/ diff hs)) diff (mod diff hs)
12932 m (floor (/ diff 60)))
12933 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12935 d (floor (+ (/ diff ds) 0.5))
12936 h 0 m 0))
12937 (if (not to-buffer)
12938 (message "%s" (org-make-tdiff-string y d h m))
12939 (if (org-at-table-p)
12940 (progn
12941 (goto-char match-end)
12942 (setq align t)
12943 (and (looking-at " *|") (goto-char (match-end 0))))
12944 (goto-char match-end))
12945 (if (looking-at
12946 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12947 (replace-match ""))
12948 (if negative (insert " -"))
12949 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12950 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12951 (insert " " (format fh h m))))
12952 (if align (org-table-align))
12953 (message "Time difference inserted")))))
12955 (defun org-make-tdiff-string (y d h m)
12956 (let ((fmt "")
12957 (l nil))
12958 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12959 l (push y l)))
12960 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12961 l (push d l)))
12962 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12963 l (push h l)))
12964 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12965 l (push m l)))
12966 (apply 'format fmt (nreverse l))))
12968 (defun org-time-string-to-time (s)
12969 (apply 'encode-time (org-parse-time-string s)))
12970 (defun org-time-string-to-seconds (s)
12971 (time-to-seconds (org-time-string-to-time s)))
12973 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12974 "Convert a time stamp to an absolute day number.
12975 If there is a specifyer for a cyclic time stamp, get the closest date to
12976 DAYNR.
12977 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12978 the variable date is bound by the calendar when this is called."
12979 (cond
12980 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12981 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12982 daynr
12983 (+ daynr 1000)))
12984 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12985 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12986 (time-to-days (current-time))) (match-string 0 s)
12987 prefer show-all))
12988 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12990 (defun org-days-to-iso-week (days)
12991 "Return the iso week number."
12992 (require 'cal-iso)
12993 (car (calendar-iso-from-absolute days)))
12995 (defun org-small-year-to-year (year)
12996 "Convert 2-digit years into 4-digit years.
12997 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12998 The year 2000 cannot be abbreviated. Any year larger than 99
12999 is returned unchanged."
13000 (if (< year 38)
13001 (setq year (+ 2000 year))
13002 (if (< year 100)
13003 (setq year (+ 1900 year))))
13004 year)
13006 (defun org-time-from-absolute (d)
13007 "Return the time corresponding to date D.
13008 D may be an absolute day number, or a calendar-type list (month day year)."
13009 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13010 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13012 (defun org-calendar-holiday ()
13013 "List of holidays, for Diary display in Org-mode."
13014 (require 'holidays)
13015 (let ((hl (funcall
13016 (if (fboundp 'calendar-check-holidays)
13017 'calendar-check-holidays 'check-calendar-holidays) date)))
13018 (if hl (mapconcat 'identity hl "; "))))
13020 (defun org-diary-sexp-entry (sexp entry date)
13021 "Process a SEXP diary ENTRY for DATE."
13022 (require 'diary-lib)
13023 (let ((result (if calendar-debug-sexp
13024 (let ((stack-trace-on-error t))
13025 (eval (car (read-from-string sexp))))
13026 (condition-case nil
13027 (eval (car (read-from-string sexp)))
13028 (error
13029 (beep)
13030 (message "Bad sexp at line %d in %s: %s"
13031 (org-current-line)
13032 (buffer-file-name) sexp)
13033 (sleep-for 2))))))
13034 (cond ((stringp result) result)
13035 ((and (consp result)
13036 (stringp (cdr result))) (cdr result))
13037 (result entry)
13038 (t nil))))
13040 (defun org-diary-to-ical-string (frombuf)
13041 "Get iCalendar entries from diary entries in buffer FROMBUF.
13042 This uses the icalendar.el library."
13043 (let* ((tmpdir (if (featurep 'xemacs)
13044 (temp-directory)
13045 temporary-file-directory))
13046 (tmpfile (make-temp-name
13047 (expand-file-name "orgics" tmpdir)))
13048 buf rtn b e)
13049 (save-excursion
13050 (set-buffer frombuf)
13051 (icalendar-export-region (point-min) (point-max) tmpfile)
13052 (setq buf (find-buffer-visiting tmpfile))
13053 (set-buffer buf)
13054 (goto-char (point-min))
13055 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13056 (setq b (match-beginning 0)))
13057 (goto-char (point-max))
13058 (if (re-search-backward "^END:VEVENT" nil t)
13059 (setq e (match-end 0)))
13060 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13061 (kill-buffer buf)
13062 (delete-file tmpfile)
13063 rtn))
13065 (defun org-closest-date (start current change prefer show-all)
13066 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13067 When PREFER is `past' return a date that is either CURRENT or past.
13068 When PREFER is `future', return a date that is either CURRENT or future.
13069 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13070 ;; Make the proper lists from the dates
13071 (catch 'exit
13072 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13073 dn dw sday cday n1 n2 n0
13074 d m y y1 y2 date1 date2 nmonths nm ny m2)
13076 (setq start (org-date-to-gregorian start)
13077 current (org-date-to-gregorian
13078 (if show-all
13079 current
13080 (time-to-days (current-time))))
13081 sday (calendar-absolute-from-gregorian start)
13082 cday (calendar-absolute-from-gregorian current))
13084 (if (<= cday sday) (throw 'exit sday))
13086 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13087 (setq dn (string-to-number (match-string 1 change))
13088 dw (cdr (assoc (match-string 2 change) a1)))
13089 (error "Invalid change specifyer: %s" change))
13090 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13091 (cond
13092 ((eq dw 'day)
13093 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13094 n2 (+ n1 dn)))
13095 ((eq dw 'year)
13096 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13097 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13098 (setq date1 (list m d y1)
13099 n1 (calendar-absolute-from-gregorian date1)
13100 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13101 n2 (calendar-absolute-from-gregorian date2)))
13102 ((eq dw 'month)
13103 ;; approx number of month between the two dates
13104 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13105 ;; How often does dn fit in there?
13106 (setq d (nth 1 start) m (car start) y (nth 2 start)
13107 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13108 m (+ m nm)
13109 ny (floor (/ m 12))
13110 y (+ y ny)
13111 m (- m (* ny 12)))
13112 (while (> m 12) (setq m (- m 12) y (1+ y)))
13113 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13114 (setq m2 (+ m dn) y2 y)
13115 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13116 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13117 (while (<= n2 cday)
13118 (setq n1 n2 m m2 y y2)
13119 (setq m2 (+ m dn) y2 y)
13120 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13121 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13122 ;; Make sure n1 is the earlier date
13123 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13124 (if show-all
13125 (cond
13126 ((eq prefer 'past) n1)
13127 ((eq prefer 'future) (if (= cday n1) n1 n2))
13128 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13129 (cond
13130 ((eq prefer 'past) n1)
13131 ((eq prefer 'future) (if (= cday n1) n1 n2))
13132 (t (if (= cday n1) n1 n2)))))))
13134 (defun org-date-to-gregorian (date)
13135 "Turn any specification of DATE into a gregorian date for the calendar."
13136 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13137 ((and (listp date) (= (length date) 3)) date)
13138 ((stringp date)
13139 (setq date (org-parse-time-string date))
13140 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13141 ((listp date)
13142 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13144 (defun org-parse-time-string (s &optional nodefault)
13145 "Parse the standard Org-mode time string.
13146 This should be a lot faster than the normal `parse-time-string'.
13147 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13148 hour and minute fields will be nil if not given."
13149 (if (string-match org-ts-regexp0 s)
13150 (list 0
13151 (if (or (match-beginning 8) (not nodefault))
13152 (string-to-number (or (match-string 8 s) "0")))
13153 (if (or (match-beginning 7) (not nodefault))
13154 (string-to-number (or (match-string 7 s) "0")))
13155 (string-to-number (match-string 4 s))
13156 (string-to-number (match-string 3 s))
13157 (string-to-number (match-string 2 s))
13158 nil nil nil)
13159 (error "Not a standard Org-mode time string: %s" s)))
13161 (defun org-timestamp-up (&optional arg)
13162 "Increase the date item at the cursor by one.
13163 If the cursor is on the year, change the year. If it is on the month or
13164 the day, change that.
13165 With prefix ARG, change by that many units."
13166 (interactive "p")
13167 (org-timestamp-change (prefix-numeric-value arg)))
13169 (defun org-timestamp-down (&optional arg)
13170 "Decrease the date item at the cursor by one.
13171 If the cursor is on the year, change the year. If it is on the month or
13172 the day, change that.
13173 With prefix ARG, change by that many units."
13174 (interactive "p")
13175 (org-timestamp-change (- (prefix-numeric-value arg))))
13177 (defun org-timestamp-up-day (&optional arg)
13178 "Increase the date in the time stamp by one day.
13179 With prefix ARG, change that many days."
13180 (interactive "p")
13181 (if (and (not (org-at-timestamp-p t))
13182 (org-on-heading-p))
13183 (org-todo 'up)
13184 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13186 (defun org-timestamp-down-day (&optional arg)
13187 "Decrease the date in the time stamp by one day.
13188 With prefix ARG, change that many days."
13189 (interactive "p")
13190 (if (and (not (org-at-timestamp-p t))
13191 (org-on-heading-p))
13192 (org-todo 'down)
13193 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13195 (defun org-at-timestamp-p (&optional inactive-ok)
13196 "Determine if the cursor is in or at a timestamp."
13197 (interactive)
13198 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13199 (pos (point))
13200 (ans (or (looking-at tsr)
13201 (save-excursion
13202 (skip-chars-backward "^[<\n\r\t")
13203 (if (> (point) (point-min)) (backward-char 1))
13204 (and (looking-at tsr)
13205 (> (- (match-end 0) pos) -1))))))
13206 (and ans
13207 (boundp 'org-ts-what)
13208 (setq org-ts-what
13209 (cond
13210 ((= pos (match-beginning 0)) 'bracket)
13211 ((= pos (1- (match-end 0))) 'bracket)
13212 ((org-pos-in-match-range pos 2) 'year)
13213 ((org-pos-in-match-range pos 3) 'month)
13214 ((org-pos-in-match-range pos 7) 'hour)
13215 ((org-pos-in-match-range pos 8) 'minute)
13216 ((or (org-pos-in-match-range pos 4)
13217 (org-pos-in-match-range pos 5)) 'day)
13218 ((and (> pos (or (match-end 8) (match-end 5)))
13219 (< pos (match-end 0)))
13220 (- pos (or (match-end 8) (match-end 5))))
13221 (t 'day))))
13222 ans))
13224 (defun org-toggle-timestamp-type ()
13225 "Toggle the type (<active> or [inactive]) of a time stamp."
13226 (interactive)
13227 (when (org-at-timestamp-p t)
13228 (let ((beg (match-beginning 0)) (end (match-end 0))
13229 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13230 (save-excursion
13231 (goto-char beg)
13232 (while (re-search-forward "[][<>]" end t)
13233 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13234 t t)))
13235 (message "Timestamp is now %sactive"
13236 (if (equal (char-after beg) ?<) "" "in")))))
13238 (defun org-timestamp-change (n &optional what)
13239 "Change the date in the time stamp at point.
13240 The date will be changed by N times WHAT. WHAT can be `day', `month',
13241 `year', `minute', `second'. If WHAT is not given, the cursor position
13242 in the timestamp determines what will be changed."
13243 (let ((pos (point))
13244 with-hm inactive
13245 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13246 org-ts-what
13247 extra rem
13248 ts time time0)
13249 (if (not (org-at-timestamp-p t))
13250 (error "Not at a timestamp"))
13251 (if (and (not what) (eq org-ts-what 'bracket))
13252 (org-toggle-timestamp-type)
13253 (if (and (not what) (not (eq org-ts-what 'day))
13254 org-display-custom-times
13255 (get-text-property (point) 'display)
13256 (not (get-text-property (1- (point)) 'display)))
13257 (setq org-ts-what 'day))
13258 (setq org-ts-what (or what org-ts-what)
13259 inactive (= (char-after (match-beginning 0)) ?\[)
13260 ts (match-string 0))
13261 (replace-match "")
13262 (if (string-match
13263 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13265 (setq extra (match-string 1 ts)))
13266 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13267 (setq with-hm t))
13268 (setq time0 (org-parse-time-string ts))
13269 (when (and (eq org-ts-what 'minute)
13270 (eq current-prefix-arg nil))
13271 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13272 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13273 (setcar (cdr time0) (+ (nth 1 time0)
13274 (if (> n 0) (- rem) (- dm rem))))))
13275 (setq time
13276 (encode-time (or (car time0) 0)
13277 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13278 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13279 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13280 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13281 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13282 (nthcdr 6 time0)))
13283 (when (and (member org-ts-what '(hour minute))
13284 extra
13285 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13286 (setq extra (org-modify-ts-extra
13287 extra
13288 (if (eq org-ts-what 'hour) 2 5)
13289 n dm)))
13290 (when (integerp org-ts-what)
13291 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13292 (if (eq what 'calendar)
13293 (let ((cal-date (org-get-date-from-calendar)))
13294 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13295 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13296 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13297 (setcar time0 (or (car time0) 0))
13298 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13299 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13300 (setq time (apply 'encode-time time0))))
13301 (setq org-last-changed-timestamp
13302 (org-insert-time-stamp time with-hm inactive nil nil extra))
13303 (org-clock-update-time-maybe)
13304 (goto-char pos)
13305 ;; Try to recenter the calendar window, if any
13306 (if (and org-calendar-follow-timestamp-change
13307 (get-buffer-window "*Calendar*" t)
13308 (memq org-ts-what '(day month year)))
13309 (org-recenter-calendar (time-to-days time))))))
13311 (defun org-modify-ts-extra (s pos n dm)
13312 "Change the different parts of the lead-time and repeat fields in timestamp."
13313 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13314 ng h m new rem)
13315 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13316 (cond
13317 ((or (org-pos-in-match-range pos 2)
13318 (org-pos-in-match-range pos 3))
13319 (setq m (string-to-number (match-string 3 s))
13320 h (string-to-number (match-string 2 s)))
13321 (if (org-pos-in-match-range pos 2)
13322 (setq h (+ h n))
13323 (setq n (* dm (org-no-warnings (signum n))))
13324 (when (not (= 0 (setq rem (% m dm))))
13325 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13326 (setq m (+ m n)))
13327 (if (< m 0) (setq m (+ m 60) h (1- h)))
13328 (if (> m 59) (setq m (- m 60) h (1+ h)))
13329 (setq h (min 24 (max 0 h)))
13330 (setq ng 1 new (format "-%02d:%02d" h m)))
13331 ((org-pos-in-match-range pos 6)
13332 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13333 ((org-pos-in-match-range pos 5)
13334 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13336 ((org-pos-in-match-range pos 9)
13337 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13338 ((org-pos-in-match-range pos 8)
13339 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13341 (when ng
13342 (setq s (concat
13343 (substring s 0 (match-beginning ng))
13345 (substring s (match-end ng))))))
13348 (defun org-recenter-calendar (date)
13349 "If the calendar is visible, recenter it to DATE."
13350 (let* ((win (selected-window))
13351 (cwin (get-buffer-window "*Calendar*" t))
13352 (calendar-move-hook nil))
13353 (when cwin
13354 (select-window cwin)
13355 (calendar-goto-date (if (listp date) date
13356 (calendar-gregorian-from-absolute date)))
13357 (select-window win))))
13359 (defun org-goto-calendar (&optional arg)
13360 "Go to the Emacs calendar at the current date.
13361 If there is a time stamp in the current line, go to that date.
13362 A prefix ARG can be used to force the current date."
13363 (interactive "P")
13364 (let ((tsr org-ts-regexp) diff
13365 (calendar-move-hook nil)
13366 (calendar-view-holidays-initially-flag nil)
13367 (view-calendar-holidays-initially nil)
13368 (calendar-view-diary-initially-flag nil)
13369 (view-diary-entries-initially nil))
13370 (if (or (org-at-timestamp-p)
13371 (save-excursion
13372 (beginning-of-line 1)
13373 (looking-at (concat ".*" tsr))))
13374 (let ((d1 (time-to-days (current-time)))
13375 (d2 (time-to-days
13376 (org-time-string-to-time (match-string 1)))))
13377 (setq diff (- d2 d1))))
13378 (calendar)
13379 (calendar-goto-today)
13380 (if (and diff (not arg)) (calendar-forward-day diff))))
13382 (defun org-get-date-from-calendar ()
13383 "Return a list (month day year) of date at point in calendar."
13384 (with-current-buffer "*Calendar*"
13385 (save-match-data
13386 (calendar-cursor-to-date))))
13388 (defun org-date-from-calendar ()
13389 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13390 If there is already a time stamp at the cursor position, update it."
13391 (interactive)
13392 (if (org-at-timestamp-p t)
13393 (org-timestamp-change 0 'calendar)
13394 (let ((cal-date (org-get-date-from-calendar)))
13395 (org-insert-time-stamp
13396 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13398 (defun org-minutes-to-hh:mm-string (m)
13399 "Compute H:MM from a number of minutes."
13400 (let ((h (/ m 60)))
13401 (setq m (- m (* 60 h)))
13402 (format org-time-clocksum-format h m)))
13404 (defun org-hh:mm-string-to-minutes (s)
13405 "Convert a string H:MM to a number of minutes.
13406 If the string is just a number, interprete it as minutes.
13407 In fact, the first hh:mm or number in the string will be taken,
13408 there can be extra stuff in the string.
13409 If no number is found, the return value is 0."
13410 (cond
13411 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13412 (+ (* (string-to-number (match-string 1 s)) 60)
13413 (string-to-number (match-string 2 s))))
13414 ((string-match "\\([0-9]+\\)" s)
13415 (string-to-number (match-string 1 s)))
13416 (t 0)))
13418 ;;;; Files
13420 (defun org-save-all-org-buffers ()
13421 "Save all Org-mode buffers without user confirmation."
13422 (interactive)
13423 (message "Saving all Org-mode buffers...")
13424 (save-some-buffers t 'org-mode-p)
13425 (when (featurep 'org-id) (org-id-locations-save))
13426 (message "Saving all Org-mode buffers... done"))
13428 (defun org-revert-all-org-buffers ()
13429 "Revert all Org-mode buffers.
13430 Prompt for confirmation when there are unsaved changes.
13431 Be sure you know what you are doing before letting this function
13432 overwrite your changes.
13434 This function is useful in a setup where one tracks org files
13435 with a version control system, to revert on one machine after pulling
13436 changes from another. I believe the procedure must be like this:
13438 1. M-x org-save-all-org-buffers
13439 2. Pull changes from the other machine, resolve conflicts
13440 3. M-x org-revert-all-org-buffers"
13441 (interactive)
13442 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13443 (error "Abort"))
13444 (save-excursion
13445 (save-window-excursion
13446 (mapc
13447 (lambda (b)
13448 (when (and (with-current-buffer b (org-mode-p))
13449 (with-current-buffer b buffer-file-name))
13450 (switch-to-buffer b)
13451 (revert-buffer t 'no-confirm)))
13452 (buffer-list))
13453 (when (and (featurep 'org-id) org-id-track-globally)
13454 (org-id-locations-load)))))
13456 ;;;; Agenda files
13458 ;;;###autoload
13459 (defun org-iswitchb (&optional arg)
13460 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13461 With a prefix argument, restrict available to files.
13462 With two prefix arguments, restrict available buffers to agenda files.
13464 Due to some yet unresolved reason, the global function
13465 `iswitchb-mode' needs to be active for this function to work."
13466 (interactive "P")
13467 (require 'iswitchb)
13468 (let ((enabled iswitchb-mode) blist)
13469 (or enabled (iswitchb-mode 1))
13470 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13471 ((equal arg '(16)) (org-buffer-list 'agenda))
13472 (t (org-buffer-list))))
13473 (unwind-protect
13474 (let ((iswitchb-make-buflist-hook
13475 (lambda ()
13476 (setq iswitchb-temp-buflist
13477 (mapcar 'buffer-name blist)))))
13478 (switch-to-buffer
13479 (iswitchb-read-buffer
13480 "Switch-to: " nil t)))
13481 (or enabled (iswitchb-mode -1)))))
13483 ;;;###autoload
13484 (defun org-iswitchb (&optional arg)
13485 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13486 With a prefix argument, restrict available to files.
13487 With two prefix arguments, restrict available buffers to agenda files."
13488 (interactive "P")
13489 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13490 ((equal arg '(16)) (org-buffer-list 'agenda))
13491 (t (org-buffer-list)))))
13492 (switch-to-buffer
13493 (org-icompleting-read "Org buffer: "
13494 (mapcar 'list (mapcar 'buffer-name blist))
13495 nil t))))
13497 ;;;###autoload
13498 (defalias 'org-ido-switchb 'org-iswitchb)
13500 (defun org-buffer-list (&optional predicate exclude-tmp)
13501 "Return a list of Org buffers.
13502 PREDICATE can be `export', `files' or `agenda'.
13504 export restrict the list to Export buffers.
13505 files restrict the list to buffers visiting Org files.
13506 agenda restrict the list to buffers visiting agenda files.
13508 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13509 (let* ((bfn nil)
13510 (agenda-files (and (eq predicate 'agenda)
13511 (mapcar 'file-truename (org-agenda-files t))))
13512 (filter
13513 (cond
13514 ((eq predicate 'files)
13515 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13516 ((eq predicate 'export)
13517 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13518 ((eq predicate 'agenda)
13519 (lambda (b)
13520 (with-current-buffer b
13521 (and (eq major-mode 'org-mode)
13522 (setq bfn (buffer-file-name b))
13523 (member (file-truename bfn) agenda-files)))))
13524 (t (lambda (b) (with-current-buffer b
13525 (or (eq major-mode 'org-mode)
13526 (string-match "\*Org .*Export"
13527 (buffer-name b)))))))))
13528 (delq nil
13529 (mapcar
13530 (lambda(b)
13531 (if (and (funcall filter b)
13532 (or (not exclude-tmp)
13533 (not (string-match "tmp" (buffer-name b)))))
13535 nil))
13536 (buffer-list)))))
13538 (defun org-agenda-files (&optional unrestricted archives)
13539 "Get the list of agenda files.
13540 Optional UNRESTRICTED means return the full list even if a restriction
13541 is currently in place.
13542 When ARCHIVES is t, include all archive files hat are really being
13543 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13544 `org-agenda-archives-mode' is t."
13545 (let ((files
13546 (cond
13547 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13548 ((stringp org-agenda-files) (org-read-agenda-file-list))
13549 ((listp org-agenda-files) org-agenda-files)
13550 (t (error "Invalid value of `org-agenda-files'")))))
13551 (setq files (apply 'append
13552 (mapcar (lambda (f)
13553 (if (file-directory-p f)
13554 (directory-files
13555 f t org-agenda-file-regexp)
13556 (list f)))
13557 files)))
13558 (when org-agenda-skip-unavailable-files
13559 (setq files (delq nil
13560 (mapcar (function
13561 (lambda (file)
13562 (and (file-readable-p file) file)))
13563 files))))
13564 (when (or (eq archives t)
13565 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13566 (setq files (org-add-archive-files files)))
13567 files))
13569 (defun org-edit-agenda-file-list ()
13570 "Edit the list of agenda files.
13571 Depending on setup, this either uses customize to edit the variable
13572 `org-agenda-files', or it visits the file that is holding the list. In the
13573 latter case, the buffer is set up in a way that saving it automatically kills
13574 the buffer and restores the previous window configuration."
13575 (interactive)
13576 (if (stringp org-agenda-files)
13577 (let ((cw (current-window-configuration)))
13578 (find-file org-agenda-files)
13579 (org-set-local 'org-window-configuration cw)
13580 (org-add-hook 'after-save-hook
13581 (lambda ()
13582 (set-window-configuration
13583 (prog1 org-window-configuration
13584 (kill-buffer (current-buffer))))
13585 (org-install-agenda-files-menu)
13586 (message "New agenda file list installed"))
13587 nil 'local)
13588 (message "%s" (substitute-command-keys
13589 "Edit list and finish with \\[save-buffer]")))
13590 (customize-variable 'org-agenda-files)))
13592 (defun org-store-new-agenda-file-list (list)
13593 "Set new value for the agenda file list and save it correctly."
13594 (if (stringp org-agenda-files)
13595 (let ((f org-agenda-files) b)
13596 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13597 (with-temp-file f
13598 (insert (mapconcat 'identity list "\n") "\n")))
13599 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13600 (setq org-agenda-files list)
13601 (customize-save-variable 'org-agenda-files org-agenda-files))))
13603 (defun org-read-agenda-file-list ()
13604 "Read the list of agenda files from a file."
13605 (when (file-directory-p org-agenda-files)
13606 (error "`org-agenda-files' cannot be a single directory"))
13607 (when (stringp org-agenda-files)
13608 (with-temp-buffer
13609 (insert-file-contents org-agenda-files)
13610 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13613 ;;;###autoload
13614 (defun org-cycle-agenda-files ()
13615 "Cycle through the files in `org-agenda-files'.
13616 If the current buffer visits an agenda file, find the next one in the list.
13617 If the current buffer does not, find the first agenda file."
13618 (interactive)
13619 (let* ((fs (org-agenda-files t))
13620 (files (append fs (list (car fs))))
13621 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13622 file)
13623 (unless files (error "No agenda files"))
13624 (catch 'exit
13625 (while (setq file (pop files))
13626 (if (equal (file-truename file) tcf)
13627 (when (car files)
13628 (find-file (car files))
13629 (throw 'exit t))))
13630 (find-file (car fs)))
13631 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13633 (defun org-agenda-file-to-front (&optional to-end)
13634 "Move/add the current file to the top of the agenda file list.
13635 If the file is not present in the list, it is added to the front. If it is
13636 present, it is moved there. With optional argument TO-END, add/move to the
13637 end of the list."
13638 (interactive "P")
13639 (let ((org-agenda-skip-unavailable-files nil)
13640 (file-alist (mapcar (lambda (x)
13641 (cons (file-truename x) x))
13642 (org-agenda-files t)))
13643 (ctf (file-truename buffer-file-name))
13644 x had)
13645 (setq x (assoc ctf file-alist) had x)
13647 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13648 (if to-end
13649 (setq file-alist (append (delq x file-alist) (list x)))
13650 (setq file-alist (cons x (delq x file-alist))))
13651 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13652 (org-install-agenda-files-menu)
13653 (message "File %s to %s of agenda file list"
13654 (if had "moved" "added") (if to-end "end" "front"))))
13656 (defun org-remove-file (&optional file)
13657 "Remove current file from the list of files in variable `org-agenda-files'.
13658 These are the files which are being checked for agenda entries.
13659 Optional argument FILE means, use this file instead of the current."
13660 (interactive)
13661 (let* ((org-agenda-skip-unavailable-files nil)
13662 (file (or file buffer-file-name))
13663 (true-file (file-truename file))
13664 (afile (abbreviate-file-name file))
13665 (files (delq nil (mapcar
13666 (lambda (x)
13667 (if (equal true-file
13668 (file-truename x))
13669 nil x))
13670 (org-agenda-files t)))))
13671 (if (not (= (length files) (length (org-agenda-files t))))
13672 (progn
13673 (org-store-new-agenda-file-list files)
13674 (org-install-agenda-files-menu)
13675 (message "Removed file: %s" afile))
13676 (message "File was not in list: %s (not removed)" afile))))
13678 (defun org-file-menu-entry (file)
13679 (vector file (list 'find-file file) t))
13681 (defun org-check-agenda-file (file)
13682 "Make sure FILE exists. If not, ask user what to do."
13683 (when (not (file-exists-p file))
13684 (message "non-existent file %s. [R]emove from list or [A]bort?"
13685 (abbreviate-file-name file))
13686 (let ((r (downcase (read-char-exclusive))))
13687 (cond
13688 ((equal r ?r)
13689 (org-remove-file file)
13690 (throw 'nextfile t))
13691 (t (error "Abort"))))))
13693 (defun org-get-agenda-file-buffer (file)
13694 "Get a buffer visiting FILE. If the buffer needs to be created, add
13695 it to the list of buffers which might be released later."
13696 (let ((buf (org-find-base-buffer-visiting file)))
13697 (if buf
13698 buf ; just return it
13699 ;; Make a new buffer and remember it
13700 (setq buf (find-file-noselect file))
13701 (if buf (push buf org-agenda-new-buffers))
13702 buf)))
13704 (defun org-release-buffers (blist)
13705 "Release all buffers in list, asking the user for confirmation when needed.
13706 When a buffer is unmodified, it is just killed. When modified, it is saved
13707 \(if the user agrees) and then killed."
13708 (let (buf file)
13709 (while (setq buf (pop blist))
13710 (setq file (buffer-file-name buf))
13711 (when (and (buffer-modified-p buf)
13712 file
13713 (y-or-n-p (format "Save file %s? " file)))
13714 (with-current-buffer buf (save-buffer)))
13715 (kill-buffer buf))))
13717 (defun org-prepare-agenda-buffers (files)
13718 "Create buffers for all agenda files, protect archived trees and comments."
13719 (interactive)
13720 (let ((pa '(:org-archived t))
13721 (pc '(:org-comment t))
13722 (pall '(:org-archived t :org-comment t))
13723 (inhibit-read-only t)
13724 (rea (concat ":" org-archive-tag ":"))
13725 bmp file re)
13726 (save-excursion
13727 (save-restriction
13728 (while (setq file (pop files))
13729 (catch 'nextfile
13730 (if (bufferp file)
13731 (set-buffer file)
13732 (org-check-agenda-file file)
13733 (set-buffer (org-get-agenda-file-buffer file)))
13734 (widen)
13735 (setq bmp (buffer-modified-p))
13736 (org-refresh-category-properties)
13737 (setq org-todo-keywords-for-agenda
13738 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13739 (setq org-done-keywords-for-agenda
13740 (append org-done-keywords-for-agenda org-done-keywords))
13741 (setq org-todo-keyword-alist-for-agenda
13742 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13743 (setq org-tag-alist-for-agenda
13744 (append org-tag-alist-for-agenda org-tag-alist))
13746 (save-excursion
13747 (remove-text-properties (point-min) (point-max) pall)
13748 (when org-agenda-skip-archived-trees
13749 (goto-char (point-min))
13750 (while (re-search-forward rea nil t)
13751 (if (org-on-heading-p t)
13752 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13753 (goto-char (point-min))
13754 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13755 (while (re-search-forward re nil t)
13756 (add-text-properties
13757 (match-beginning 0) (org-end-of-subtree t) pc)))
13758 (set-buffer-modified-p bmp)))))
13759 (setq org-todo-keyword-alist-for-agenda
13760 (org-uniquify org-todo-keyword-alist-for-agenda)
13761 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13763 ;;;; Embedded LaTeX
13765 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13766 "Keymap for the minor `org-cdlatex-mode'.")
13768 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13769 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13770 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13771 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13772 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13774 (defvar org-cdlatex-texmathp-advice-is-done nil
13775 "Flag remembering if we have applied the advice to texmathp already.")
13777 (define-minor-mode org-cdlatex-mode
13778 "Toggle the minor `org-cdlatex-mode'.
13779 This mode supports entering LaTeX environment and math in LaTeX fragments
13780 in Org-mode.
13781 \\{org-cdlatex-mode-map}"
13782 nil " OCDL" nil
13783 (when org-cdlatex-mode (require 'cdlatex))
13784 (unless org-cdlatex-texmathp-advice-is-done
13785 (setq org-cdlatex-texmathp-advice-is-done t)
13786 (defadvice texmathp (around org-math-always-on activate)
13787 "Always return t in org-mode buffers.
13788 This is because we want to insert math symbols without dollars even outside
13789 the LaTeX math segments. If Orgmode thinks that point is actually inside
13790 an embedded LaTeX fragment, let texmathp do its job.
13791 \\[org-cdlatex-mode-map]"
13792 (interactive)
13793 (let (p)
13794 (cond
13795 ((not (org-mode-p)) ad-do-it)
13796 ((eq this-command 'cdlatex-math-symbol)
13797 (setq ad-return-value t
13798 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13800 (let ((p (org-inside-LaTeX-fragment-p)))
13801 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13802 (setq ad-return-value t
13803 texmathp-why '("Org-mode embedded math" . 0))
13804 (if p ad-do-it)))))))))
13806 (defun turn-on-org-cdlatex ()
13807 "Unconditionally turn on `org-cdlatex-mode'."
13808 (org-cdlatex-mode 1))
13810 (defun org-inside-LaTeX-fragment-p ()
13811 "Test if point is inside a LaTeX fragment.
13812 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13813 sequence appearing also before point.
13814 Even though the matchers for math are configurable, this function assumes
13815 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13816 delimiters are skipped when they have been removed by customization.
13817 The return value is nil, or a cons cell with the delimiter and
13818 and the position of this delimiter.
13820 This function does a reasonably good job, but can locally be fooled by
13821 for example currency specifications. For example it will assume being in
13822 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13823 fragments that are properly closed, but during editing, we have to live
13824 with the uncertainty caused by missing closing delimiters. This function
13825 looks only before point, not after."
13826 (catch 'exit
13827 (let ((pos (point))
13828 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13829 (lim (progn
13830 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13831 (point)))
13832 dd-on str (start 0) m re)
13833 (goto-char pos)
13834 (when dodollar
13835 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13836 re (nth 1 (assoc "$" org-latex-regexps)))
13837 (while (string-match re str start)
13838 (cond
13839 ((= (match-end 0) (length str))
13840 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13841 ((= (match-end 0) (- (length str) 5))
13842 (throw 'exit nil))
13843 (t (setq start (match-end 0))))))
13844 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13845 (goto-char pos)
13846 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13847 (and (match-beginning 2) (throw 'exit nil))
13848 ;; count $$
13849 (while (re-search-backward "\\$\\$" lim t)
13850 (setq dd-on (not dd-on)))
13851 (goto-char pos)
13852 (if dd-on (cons "$$" m))))))
13855 (defun org-try-cdlatex-tab ()
13856 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13857 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13858 - inside a LaTeX fragment, or
13859 - after the first word in a line, where an abbreviation expansion could
13860 insert a LaTeX environment."
13861 (when org-cdlatex-mode
13862 (cond
13863 ((save-excursion
13864 (skip-chars-backward "a-zA-Z0-9*")
13865 (skip-chars-backward " \t")
13866 (bolp))
13867 (cdlatex-tab) t)
13868 ((org-inside-LaTeX-fragment-p)
13869 (cdlatex-tab) t)
13870 (t nil))))
13872 (defun org-cdlatex-underscore-caret (&optional arg)
13873 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13874 Revert to the normal definition outside of these fragments."
13875 (interactive "P")
13876 (if (org-inside-LaTeX-fragment-p)
13877 (call-interactively 'cdlatex-sub-superscript)
13878 (let (org-cdlatex-mode)
13879 (call-interactively (key-binding (vector last-input-event))))))
13881 (defun org-cdlatex-math-modify (&optional arg)
13882 "Execute `cdlatex-math-modify' in LaTeX fragments.
13883 Revert to the normal definition outside of these fragments."
13884 (interactive "P")
13885 (if (org-inside-LaTeX-fragment-p)
13886 (call-interactively 'cdlatex-math-modify)
13887 (let (org-cdlatex-mode)
13888 (call-interactively (key-binding (vector last-input-event))))))
13890 (defvar org-latex-fragment-image-overlays nil
13891 "List of overlays carrying the images of latex fragments.")
13892 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13894 (defun org-remove-latex-fragment-image-overlays ()
13895 "Remove all overlays with LaTeX fragment images in current buffer."
13896 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13897 (setq org-latex-fragment-image-overlays nil))
13899 (defun org-preview-latex-fragment (&optional subtree)
13900 "Preview the LaTeX fragment at point, or all locally or globally.
13901 If the cursor is in a LaTeX fragment, create the image and overlay
13902 it over the source code. If there is no fragment at point, display
13903 all fragments in the current text, from one headline to the next. With
13904 prefix SUBTREE, display all fragments in the current subtree. With a
13905 double prefix `C-u C-u', or when the cursor is before the first headline,
13906 display all fragments in the buffer.
13907 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13908 (interactive "P")
13909 (org-remove-latex-fragment-image-overlays)
13910 (save-excursion
13911 (save-restriction
13912 (let (beg end at msg)
13913 (cond
13914 ((or (equal subtree '(16))
13915 (not (save-excursion
13916 (re-search-backward (concat "^" outline-regexp) nil t))))
13917 (setq beg (point-min) end (point-max)
13918 msg "Creating images for buffer...%s"))
13919 ((equal subtree '(4))
13920 (org-back-to-heading)
13921 (setq beg (point) end (org-end-of-subtree t)
13922 msg "Creating images for subtree...%s"))
13924 (if (setq at (org-inside-LaTeX-fragment-p))
13925 (goto-char (max (point-min) (- (cdr at) 2)))
13926 (org-back-to-heading))
13927 (setq beg (point) end (progn (outline-next-heading) (point))
13928 msg (if at "Creating image...%s"
13929 "Creating images for entry...%s"))))
13930 (message msg "")
13931 (narrow-to-region beg end)
13932 (goto-char beg)
13933 (org-format-latex
13934 (concat "ltxpng/" (file-name-sans-extension
13935 (file-name-nondirectory
13936 buffer-file-name)))
13937 default-directory 'overlays msg at 'forbuffer)
13938 (message msg "done. Use `C-c C-c' to remove images.")))))
13940 (defvar org-latex-regexps
13941 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13942 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13943 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13944 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13945 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13946 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13947 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
13948 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
13949 "Regular expressions for matching embedded LaTeX.")
13951 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13952 "Replace LaTeX fragments with links to an image, and produce images."
13953 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13954 (let* ((prefixnodir (file-name-nondirectory prefix))
13955 (absprefix (expand-file-name prefix dir))
13956 (todir (file-name-directory absprefix))
13957 (opt org-format-latex-options)
13958 (matchers (plist-get opt :matchers))
13959 (re-list org-latex-regexps)
13960 (cnt 0) txt link beg end re e checkdir
13961 executables-checked
13962 m n block linkfile movefile ov)
13963 ;; Check if there are old images files with this prefix, and remove them
13964 (when (file-directory-p todir)
13965 (mapc 'delete-file
13966 (directory-files
13967 todir 'full
13968 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13969 ;; Check the different regular expressions
13970 (while (setq e (pop re-list))
13971 (setq m (car e) re (nth 1 e) n (nth 2 e)
13972 block (if (nth 3 e) "\n\n" ""))
13973 (when (member m matchers)
13974 (goto-char (point-min))
13975 (while (re-search-forward re nil t)
13976 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13977 (not (get-text-property (match-beginning n)
13978 'org-protected))
13979 (or (not overlays)
13980 (not (eq (get-char-property (match-beginning n)
13981 'org-overlay-type)
13982 'org-latex-overlay))))
13983 (setq txt (match-string n)
13984 beg (match-beginning n) end (match-end n)
13985 cnt (1+ cnt)
13986 linkfile (format "%s_%04d.png" prefix cnt)
13987 movefile (format "%s_%04d.png" absprefix cnt)
13988 link (concat block "[[file:" linkfile "]]" block))
13989 (if msg (message msg cnt))
13990 (goto-char beg)
13991 (unless checkdir ; make sure the directory exists
13992 (setq checkdir t)
13993 (or (file-directory-p todir) (make-directory todir)))
13995 (unless executables-checked
13996 (org-check-external-command
13997 "latex" "needed to convert LaTeX fragments to images")
13998 (org-check-external-command
13999 "dvipng" "needed to convert LaTeX fragments to images")
14000 (setq executables-checked t))
14002 (org-create-formula-image
14003 txt movefile opt forbuffer)
14004 (if overlays
14005 (progn
14006 (mapc (lambda (o)
14007 (if (eq (org-overlay-get o 'org-overlay-type)
14008 'org-latex-overlay)
14009 (org-delete-overlay o)))
14010 (org-overlays-in beg end))
14011 (setq ov (org-make-overlay beg end))
14012 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14013 (if (featurep 'xemacs)
14014 (progn
14015 (org-overlay-put ov 'invisible t)
14016 (org-overlay-put
14017 ov 'end-glyph
14018 (make-glyph (vector 'png :file movefile))))
14019 (org-overlay-put
14020 ov 'display
14021 (list 'image :type 'png :file movefile :ascent 'center)))
14022 (push ov org-latex-fragment-image-overlays)
14023 (goto-char end))
14024 (delete-region beg end)
14025 (insert link))))))))
14027 ;; This function borrows from Ganesh Swami's latex2png.el
14028 (defun org-create-formula-image (string tofile options buffer)
14029 (require 'org-latex)
14030 (let* ((tmpdir (if (featurep 'xemacs)
14031 (temp-directory)
14032 temporary-file-directory))
14033 (texfilebase (make-temp-name
14034 (expand-file-name "orgtex" tmpdir)))
14035 (texfile (concat texfilebase ".tex"))
14036 (dvifile (concat texfilebase ".dvi"))
14037 (pngfile (concat texfilebase ".png"))
14038 (fnh (if (featurep 'xemacs)
14039 (font-height (get-face-font 'default))
14040 (face-attribute 'default :height nil)))
14041 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14042 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14043 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14044 "Black"))
14045 (bg (or (plist-get options (if buffer :background :html-background))
14046 "Transparent")))
14047 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14048 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14049 (with-temp-file texfile
14050 (insert org-format-latex-header
14051 (if org-export-latex-packages-alist
14052 (concat "\n"
14053 (mapconcat (lambda(p)
14054 (if (equal "" (car p))
14055 (format "\\usepackage{%s}" (cadr p))
14056 (format "\\usepackage[%s]{%s}"
14057 (car p) (cadr p))))
14058 org-export-latex-packages-alist "\n"))
14060 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14061 (let ((dir default-directory))
14062 (condition-case nil
14063 (progn
14064 (cd tmpdir)
14065 (call-process "latex" nil nil nil texfile))
14066 (error nil))
14067 (cd dir))
14068 (if (not (file-exists-p dvifile))
14069 (progn (message "Failed to create dvi file from %s" texfile) nil)
14070 (condition-case nil
14071 (call-process "dvipng" nil nil nil
14072 "-fg" fg "-bg" bg
14073 "-D" dpi
14074 ;;"-x" scale "-y" scale
14075 "-T" "tight"
14076 "-o" pngfile
14077 dvifile)
14078 (error nil))
14079 (if (not (file-exists-p pngfile))
14080 (progn (message "Failed to create png file from %s" texfile) nil)
14081 ;; Use the requested file name and clean up
14082 (copy-file pngfile tofile 'replace)
14083 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14084 (delete-file (concat texfilebase e)))
14085 pngfile))))
14087 (defun org-dvipng-color (attr)
14088 "Return an rgb color specification for dvipng."
14089 (apply 'format "rgb %s %s %s"
14090 (mapcar 'org-normalize-color
14091 (color-values (face-attribute 'default attr nil)))))
14093 (defun org-normalize-color (value)
14094 "Return string to be used as color value for an RGB component."
14095 (format "%g" (/ value 65535.0)))
14097 ;;;; Key bindings
14099 ;; Make `C-c C-x' a prefix key
14100 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14102 ;; TAB key with modifiers
14103 (org-defkey org-mode-map "\C-i" 'org-cycle)
14104 (org-defkey org-mode-map [(tab)] 'org-cycle)
14105 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14106 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14107 (org-defkey org-mode-map "\M-\t" 'org-complete)
14108 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14109 ;; The following line is necessary under Suse GNU/Linux
14110 (unless (featurep 'xemacs)
14111 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14112 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14113 (define-key org-mode-map [backtab] 'org-shifttab)
14115 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14116 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14117 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14119 ;; Cursor keys with modifiers
14120 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14121 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14122 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14123 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14125 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14126 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14127 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14128 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14130 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14131 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14132 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14133 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14135 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14136 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14138 ;;; Extra keys for tty access.
14139 ;; We only set them when really needed because otherwise the
14140 ;; menus don't show the simple keys
14142 (when (or org-use-extra-keys
14143 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14144 (not window-system))
14145 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14146 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14147 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14148 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14149 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14150 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14151 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14152 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14153 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14154 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14155 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14156 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14157 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14158 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14159 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14160 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14161 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14162 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14163 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14164 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14165 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14166 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14167 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14168 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14169 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14170 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14171 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14172 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14174 ;; All the other keys
14176 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14177 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14178 (if (boundp 'narrow-map)
14179 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14180 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14181 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14182 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14183 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14184 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14185 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14186 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14187 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14188 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14189 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14190 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14191 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14192 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14193 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14194 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14195 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14196 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14197 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14198 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14199 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14200 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14201 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14202 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14203 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14204 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14205 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14206 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14207 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14208 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14209 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14210 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14211 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14212 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14213 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14214 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14215 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14216 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14217 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14218 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14219 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14220 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14221 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14222 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14223 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14224 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14225 (org-defkey org-mode-map "\C-c^" 'org-sort)
14226 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14227 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14228 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
14229 (org-defkey org-mode-map "\C-m" 'org-return)
14230 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14231 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14232 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14233 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14234 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14235 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14236 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14237 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14238 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14239 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14240 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14241 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14242 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14243 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14244 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14245 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14246 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14247 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14248 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14250 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14251 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14252 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14253 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14255 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14256 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14257 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14258 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14259 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14260 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14261 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14262 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14263 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14264 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14265 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14266 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14267 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14268 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14270 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14271 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14272 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14273 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14275 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14277 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14279 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14280 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14282 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14285 (when (featurep 'xemacs)
14286 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14289 (defvar org-self-insert-command-undo-counter 0)
14291 (defvar org-table-auto-blank-field) ; defined in org-table.el
14292 (defun org-self-insert-command (N)
14293 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14294 If the cursor is in a table looking at whitespace, the whitespace is
14295 overwritten, and the table is not marked as requiring realignment."
14296 (interactive "p")
14297 (if (and
14298 (org-table-p)
14299 (progn
14300 ;; check if we blank the field, and if that triggers align
14301 (and (featurep 'org-table) org-table-auto-blank-field
14302 (member last-command
14303 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14304 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14305 ;; got extra space, this field does not determine column width
14306 (let (org-table-may-need-update) (org-table-blank-field))
14307 ;; no extra space, this field may determine column width
14308 (org-table-blank-field)))
14310 (eq N 1)
14311 (looking-at "[^|\n]* |"))
14312 (let (org-table-may-need-update)
14313 (goto-char (1- (match-end 0)))
14314 (delete-backward-char 1)
14315 (goto-char (match-beginning 0))
14316 (self-insert-command N))
14317 (setq org-table-may-need-update t)
14318 (self-insert-command N)
14319 (org-fix-tags-on-the-fly)
14320 (if org-self-insert-cluster-for-undo
14321 (if (not (eq last-command 'org-self-insert-command))
14322 (setq org-self-insert-command-undo-counter 1)
14323 (if (>= org-self-insert-command-undo-counter 20)
14324 (setq org-self-insert-command-undo-counter 1)
14325 (and (> org-self-insert-command-undo-counter 0)
14326 buffer-undo-list
14327 (not (cadr buffer-undo-list)) ; remove nil entry
14328 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14329 (setq org-self-insert-command-undo-counter
14330 (1+ org-self-insert-command-undo-counter)))))))
14332 (defun org-fix-tags-on-the-fly ()
14333 (when (and (equal (char-after (point-at-bol)) ?*)
14334 (org-on-heading-p))
14335 (org-align-tags-here org-tags-column)))
14337 (defun org-delete-backward-char (N)
14338 "Like `delete-backward-char', insert whitespace at field end in tables.
14339 When deleting backwards, in tables this function will insert whitespace in
14340 front of the next \"|\" separator, to keep the table aligned. The table will
14341 still be marked for re-alignment if the field did fill the entire column,
14342 because, in this case the deletion might narrow the column."
14343 (interactive "p")
14344 (if (and (org-table-p)
14345 (eq N 1)
14346 (string-match "|" (buffer-substring (point-at-bol) (point)))
14347 (looking-at ".*?|"))
14348 (let ((pos (point))
14349 (noalign (looking-at "[^|\n\r]* |"))
14350 (c org-table-may-need-update))
14351 (backward-delete-char N)
14352 (skip-chars-forward "^|")
14353 (insert " ")
14354 (goto-char (1- pos))
14355 ;; noalign: if there were two spaces at the end, this field
14356 ;; does not determine the width of the column.
14357 (if noalign (setq org-table-may-need-update c)))
14358 (backward-delete-char N)
14359 (org-fix-tags-on-the-fly)))
14361 (defun org-delete-char (N)
14362 "Like `delete-char', but insert whitespace at field end in tables.
14363 When deleting characters, in tables this function will insert whitespace in
14364 front of the next \"|\" separator, to keep the table aligned. The table will
14365 still be marked for re-alignment if the field did fill the entire column,
14366 because, in this case the deletion might narrow the column."
14367 (interactive "p")
14368 (if (and (org-table-p)
14369 (not (bolp))
14370 (not (= (char-after) ?|))
14371 (eq N 1))
14372 (if (looking-at ".*?|")
14373 (let ((pos (point))
14374 (noalign (looking-at "[^|\n\r]* |"))
14375 (c org-table-may-need-update))
14376 (replace-match (concat
14377 (substring (match-string 0) 1 -1)
14378 " |"))
14379 (goto-char pos)
14380 ;; noalign: if there were two spaces at the end, this field
14381 ;; does not determine the width of the column.
14382 (if noalign (setq org-table-may-need-update c)))
14383 (delete-char N))
14384 (delete-char N)
14385 (org-fix-tags-on-the-fly)))
14387 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14388 (put 'org-self-insert-command 'delete-selection t)
14389 (put 'orgtbl-self-insert-command 'delete-selection t)
14390 (put 'org-delete-char 'delete-selection 'supersede)
14391 (put 'org-delete-backward-char 'delete-selection 'supersede)
14392 (put 'org-yank 'delete-selection 'yank)
14394 ;; Make `flyspell-mode' delay after some commands
14395 (put 'org-self-insert-command 'flyspell-delayed t)
14396 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14397 (put 'org-delete-char 'flyspell-delayed t)
14398 (put 'org-delete-backward-char 'flyspell-delayed t)
14400 ;; Make pabbrev-mode expand after org-mode commands
14401 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14402 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14404 ;; How to do this: Measure non-white length of current string
14405 ;; If equal to column width, we should realign.
14407 (defun org-remap (map &rest commands)
14408 "In MAP, remap the functions given in COMMANDS.
14409 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14410 (let (new old)
14411 (while commands
14412 (setq old (pop commands) new (pop commands))
14413 (if (fboundp 'command-remapping)
14414 (org-defkey map (vector 'remap old) new)
14415 (substitute-key-definition old new map global-map)))))
14417 (when (eq org-enable-table-editor 'optimized)
14418 ;; If the user wants maximum table support, we need to hijack
14419 ;; some standard editing functions
14420 (org-remap org-mode-map
14421 'self-insert-command 'org-self-insert-command
14422 'delete-char 'org-delete-char
14423 'delete-backward-char 'org-delete-backward-char)
14424 (org-defkey org-mode-map "|" 'org-force-self-insert))
14426 (defvar org-ctrl-c-ctrl-c-hook nil
14427 "Hook for functions attaching themselves to `C-c C-c'.
14428 This can be used to add additional functionality to the C-c C-c key which
14429 executes context-dependent commands.
14430 Each function will be called with no arguments. The function must check
14431 if the context is appropriate for it to act. If yes, it should do its
14432 thing and then return a non-nil value. If the context is wrong,
14433 just do nothing and return nil.")
14435 (defvar org-tab-first-hook nil
14436 "Hook for functions to attach themselves to TAB.
14437 See `org-ctrl-c-ctrl-c-hook' for more information.
14438 This hook runs as the first action when TAB is pressed, even before
14439 `org-cycle' messes around with the `outline-regexp' to cater for
14440 inline tasks and plain list item folding.
14441 If any function in this hook returns t, not other actions like table
14442 field motion visibility cycling will be done.")
14444 (defvar org-tab-after-check-for-table-hook nil
14445 "Hook for functions to attach themselves to TAB.
14446 See `org-ctrl-c-ctrl-c-hook' for more information.
14447 This hook runs after it has been established that the cursor is not in a
14448 table, but before checking if the cursor is in a headline or if global cycling
14449 should be done.
14450 If any function in this hook returns t, not other actions like visibility
14451 cycling will be done.")
14453 (defvar org-tab-after-check-for-cycling-hook nil
14454 "Hook for functions to attach themselves to TAB.
14455 See `org-ctrl-c-ctrl-c-hook' for more information.
14456 This hook runs after it has been established that not table field motion and
14457 not visibility should be done because of current context. This is probably
14458 the place where a package like yasnippets can hook in.")
14460 (defvar org-metaleft-hook nil
14461 "Hook for functions attaching themselves to `M-left'.
14462 See `org-ctrl-c-ctrl-c-hook' for more information.")
14463 (defvar org-metaright-hook nil
14464 "Hook for functions attaching themselves to `M-right'.
14465 See `org-ctrl-c-ctrl-c-hook' for more information.")
14466 (defvar org-metaup-hook nil
14467 "Hook for functions attaching themselves to `M-up'.
14468 See `org-ctrl-c-ctrl-c-hook' for more information.")
14469 (defvar org-metadown-hook nil
14470 "Hook for functions attaching themselves to `M-down'.
14471 See `org-ctrl-c-ctrl-c-hook' for more information.")
14472 (defvar org-shiftmetaleft-hook nil
14473 "Hook for functions attaching themselves to `M-S-left'.
14474 See `org-ctrl-c-ctrl-c-hook' for more information.")
14475 (defvar org-shiftmetaright-hook nil
14476 "Hook for functions attaching themselves to `M-S-right'.
14477 See `org-ctrl-c-ctrl-c-hook' for more information.")
14478 (defvar org-shiftmetaup-hook nil
14479 "Hook for functions attaching themselves to `M-S-up'.
14480 See `org-ctrl-c-ctrl-c-hook' for more information.")
14481 (defvar org-shiftmetadown-hook nil
14482 "Hook for functions attaching themselves to `M-S-down'.
14483 See `org-ctrl-c-ctrl-c-hook' for more information.")
14484 (defvar org-metareturn-hook nil
14485 "Hook for functions attaching themselves to `M-RET'.
14486 See `org-ctrl-c-ctrl-c-hook' for more information.")
14488 (defun org-modifier-cursor-error ()
14489 "Throw an error, a modified cursor command was applied in wrong context."
14490 (error "This command is active in special context like tables, headlines or items"))
14492 (defun org-shiftselect-error ()
14493 "Throw an error because Shift-Cursor command was applied in wrong context."
14494 (if (and (boundp 'shift-select-mode) shift-select-mode)
14495 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14496 (error "This command works only in special context like headlines or timestamps.")))
14498 (defun org-call-for-shift-select (cmd)
14499 (let ((this-command-keys-shift-translated t))
14500 (call-interactively cmd)))
14502 (defun org-shifttab (&optional arg)
14503 "Global visibility cycling or move to previous table field.
14504 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14505 on context.
14506 See the individual commands for more information."
14507 (interactive "P")
14508 (cond
14509 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14510 ((integerp arg)
14511 (message "Content view to level: %d" arg)
14512 (org-content (prefix-numeric-value arg))
14513 (setq org-cycle-global-status 'overview))
14514 (t (call-interactively 'org-global-cycle))))
14516 (defun org-shiftmetaleft ()
14517 "Promote subtree or delete table column.
14518 Calls `org-promote-subtree', `org-outdent-item',
14519 or `org-table-delete-column', depending on context.
14520 See the individual commands for more information."
14521 (interactive)
14522 (cond
14523 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14524 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14525 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14526 ((org-at-item-p) (call-interactively 'org-outdent-item))
14527 (t (org-modifier-cursor-error))))
14529 (defun org-shiftmetaright ()
14530 "Demote subtree or insert table column.
14531 Calls `org-demote-subtree', `org-indent-item',
14532 or `org-table-insert-column', depending on context.
14533 See the individual commands for more information."
14534 (interactive)
14535 (cond
14536 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14537 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14538 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14539 ((org-at-item-p) (call-interactively 'org-indent-item))
14540 (t (org-modifier-cursor-error))))
14542 (defun org-shiftmetaup (&optional arg)
14543 "Move subtree up or kill table row.
14544 Calls `org-move-subtree-up' or `org-table-kill-row' or
14545 `org-move-item-up' depending on context. See the individual commands
14546 for more information."
14547 (interactive "P")
14548 (cond
14549 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14550 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14551 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14552 ((org-at-item-p) (call-interactively 'org-move-item-up))
14553 (t (org-modifier-cursor-error))))
14555 (defun org-shiftmetadown (&optional arg)
14556 "Move subtree down or insert table row.
14557 Calls `org-move-subtree-down' or `org-table-insert-row' or
14558 `org-move-item-down', depending on context. See the individual
14559 commands for more information."
14560 (interactive "P")
14561 (cond
14562 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14563 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14564 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14565 ((org-at-item-p) (call-interactively 'org-move-item-down))
14566 (t (org-modifier-cursor-error))))
14568 (defun org-metaleft (&optional arg)
14569 "Promote heading or move table column to left.
14570 Calls `org-do-promote' or `org-table-move-column', depending on context.
14571 With no specific context, calls the Emacs default `backward-word'.
14572 See the individual commands for more information."
14573 (interactive "P")
14574 (cond
14575 ((run-hook-with-args-until-success 'org-metaleft-hook))
14576 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14577 ((or (org-on-heading-p)
14578 (and (org-region-active-p)
14579 (save-excursion
14580 (goto-char (region-beginning))
14581 (org-on-heading-p))))
14582 (call-interactively 'org-do-promote))
14583 ((or (org-at-item-p)
14584 (and (org-region-active-p)
14585 (save-excursion
14586 (goto-char (region-beginning))
14587 (org-at-item-p))))
14588 (call-interactively 'org-outdent-item))
14589 (t (call-interactively 'backward-word))))
14591 (defun org-metaright (&optional arg)
14592 "Demote subtree or move table column to right.
14593 Calls `org-do-demote' or `org-table-move-column', depending on context.
14594 With no specific context, calls the Emacs default `forward-word'.
14595 See the individual commands for more information."
14596 (interactive "P")
14597 (cond
14598 ((run-hook-with-args-until-success 'org-metaright-hook))
14599 ((org-at-table-p) (call-interactively 'org-table-move-column))
14600 ((or (org-on-heading-p)
14601 (and (org-region-active-p)
14602 (save-excursion
14603 (goto-char (region-beginning))
14604 (org-on-heading-p))))
14605 (call-interactively 'org-do-demote))
14606 ((or (org-at-item-p)
14607 (and (org-region-active-p)
14608 (save-excursion
14609 (goto-char (region-beginning))
14610 (org-at-item-p))))
14611 (call-interactively 'org-indent-item))
14612 (t (call-interactively 'forward-word))))
14614 (defun org-metaup (&optional arg)
14615 "Move subtree up or move table row up.
14616 Calls `org-move-subtree-up' or `org-table-move-row' or
14617 `org-move-item-up', depending on context. See the individual commands
14618 for more information."
14619 (interactive "P")
14620 (cond
14621 ((run-hook-with-args-until-success 'org-metaup-hook))
14622 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14623 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14624 ((org-at-item-p) (call-interactively 'org-move-item-up))
14625 (t (transpose-lines 1) (beginning-of-line -1))))
14627 (defun org-metadown (&optional arg)
14628 "Move subtree down or move table row down.
14629 Calls `org-move-subtree-down' or `org-table-move-row' or
14630 `org-move-item-down', depending on context. See the individual
14631 commands for more information."
14632 (interactive "P")
14633 (cond
14634 ((run-hook-with-args-until-success 'org-metadown-hook))
14635 ((org-at-table-p) (call-interactively 'org-table-move-row))
14636 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14637 ((org-at-item-p) (call-interactively 'org-move-item-down))
14638 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14640 (defun org-shiftup (&optional arg)
14641 "Increase item in timestamp or increase priority of current headline.
14642 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14643 depending on context. See the individual commands for more information."
14644 (interactive "P")
14645 (cond
14646 ((and org-support-shift-select (org-region-active-p))
14647 (org-call-for-shift-select 'previous-line))
14648 ((org-at-timestamp-p t)
14649 (call-interactively (if org-edit-timestamp-down-means-later
14650 'org-timestamp-down 'org-timestamp-up)))
14651 ((and (not (eq org-support-shift-select 'always))
14652 org-enable-priority-commands
14653 (org-on-heading-p))
14654 (call-interactively 'org-priority-up))
14655 ((and (not org-support-shift-select) (org-at-item-p))
14656 (call-interactively 'org-previous-item))
14657 ((org-clocktable-try-shift 'up arg))
14658 (org-support-shift-select
14659 (org-call-for-shift-select 'previous-line))
14660 (t (org-shiftselect-error))))
14662 (defun org-shiftdown (&optional arg)
14663 "Decrease item in timestamp or decrease priority of current headline.
14664 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14665 depending on context. See the individual commands for more information."
14666 (interactive "P")
14667 (cond
14668 ((and org-support-shift-select (org-region-active-p))
14669 (org-call-for-shift-select 'next-line))
14670 ((org-at-timestamp-p t)
14671 (call-interactively (if org-edit-timestamp-down-means-later
14672 'org-timestamp-up 'org-timestamp-down)))
14673 ((and (not (eq org-support-shift-select 'always))
14674 org-enable-priority-commands
14675 (org-on-heading-p))
14676 (call-interactively 'org-priority-down))
14677 ((and (not org-support-shift-select) (org-at-item-p))
14678 (call-interactively 'org-next-item))
14679 ((org-clocktable-try-shift 'down arg))
14680 (org-support-shift-select
14681 (org-call-for-shift-select 'next-line))
14682 (t (org-shiftselect-error))))
14684 (defun org-shiftright (&optional arg)
14685 "Cycle the thing at point or in the current line, depending on context.
14686 Depending on context, this does one of the following:
14688 - switch a timestamp at point one day into the future
14689 - on a headline, switch to the next TODO keyword.
14690 - on an item, switch entire list to the next bullet type
14691 - on a property line, switch to the next allowed value
14692 - on a clocktable definition line, move time block into the future"
14693 (interactive "P")
14694 (cond
14695 ((and org-support-shift-select (org-region-active-p))
14696 (org-call-for-shift-select 'forward-char))
14697 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14698 ((and (not (eq org-support-shift-select 'always))
14699 (org-on-heading-p))
14700 (let ((org-inhibit-logging
14701 (not org-treat-S-cursor-todo-selection-as-state-change))
14702 (org-inhibit-blocking
14703 (not org-treat-S-cursor-todo-selection-as-state-change)))
14704 (org-call-with-arg 'org-todo 'right)))
14705 ((or (and org-support-shift-select
14706 (not (eq org-support-shift-select 'always))
14707 (org-at-item-bullet-p))
14708 (and (not org-support-shift-select) (org-at-item-p)))
14709 (org-call-with-arg 'org-cycle-list-bullet nil))
14710 ((and (not (eq org-support-shift-select 'always))
14711 (org-at-property-p))
14712 (call-interactively 'org-property-next-allowed-value))
14713 ((org-clocktable-try-shift 'right arg))
14714 (org-support-shift-select
14715 (org-call-for-shift-select 'forward-char))
14716 (t (org-shiftselect-error))))
14718 (defun org-shiftleft (&optional arg)
14719 "Cycle the thing at point or in the current line, depending on context.
14720 Depending on context, this does one of the following:
14722 - switch a timestamp at point one day into the past
14723 - on a headline, switch to the previous TODO keyword.
14724 - on an item, switch entire list to the previous bullet type
14725 - on a property line, switch to the previous allowed value
14726 - on a clocktable definition line, move time block into the past"
14727 (interactive "P")
14728 (cond
14729 ((and org-support-shift-select (org-region-active-p))
14730 (org-call-for-shift-select 'backward-char))
14731 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14732 ((and (not (eq org-support-shift-select 'always))
14733 (org-on-heading-p))
14734 (let ((org-inhibit-logging
14735 (not org-treat-S-cursor-todo-selection-as-state-change))
14736 (org-inhibit-blocking
14737 (not org-treat-S-cursor-todo-selection-as-state-change)))
14738 (org-call-with-arg 'org-todo 'left)))
14739 ((or (and org-support-shift-select
14740 (not (eq org-support-shift-select 'always))
14741 (org-at-item-bullet-p))
14742 (and (not org-support-shift-select) (org-at-item-p)))
14743 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14744 ((and (not (eq org-support-shift-select 'always))
14745 (org-at-property-p))
14746 (call-interactively 'org-property-previous-allowed-value))
14747 ((org-clocktable-try-shift 'left arg))
14748 (org-support-shift-select
14749 (org-call-for-shift-select 'backward-char))
14750 (t (org-shiftselect-error))))
14752 (defun org-shiftcontrolright ()
14753 "Switch to next TODO set."
14754 (interactive)
14755 (cond
14756 ((and org-support-shift-select (org-region-active-p))
14757 (org-call-for-shift-select 'forward-word))
14758 ((and (not (eq org-support-shift-select 'always))
14759 (org-on-heading-p))
14760 (org-call-with-arg 'org-todo 'nextset))
14761 (org-support-shift-select
14762 (org-call-for-shift-select 'forward-word))
14763 (t (org-shiftselect-error))))
14765 (defun org-shiftcontrolleft ()
14766 "Switch to previous TODO set."
14767 (interactive)
14768 (cond
14769 ((and org-support-shift-select (org-region-active-p))
14770 (org-call-for-shift-select 'backward-word))
14771 ((and (not (eq org-support-shift-select 'always))
14772 (org-on-heading-p))
14773 (org-call-with-arg 'org-todo 'previousset))
14774 (org-support-shift-select
14775 (org-call-for-shift-select 'backward-word))
14776 (t (org-shiftselect-error))))
14778 (defun org-ctrl-c-ret ()
14779 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14780 (interactive)
14781 (cond
14782 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14783 (t (call-interactively 'org-insert-heading))))
14785 (defun org-copy-special ()
14786 "Copy region in table or copy current subtree.
14787 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14788 See the individual commands for more information."
14789 (interactive)
14790 (call-interactively
14791 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14793 (defun org-cut-special ()
14794 "Cut region in table or cut current subtree.
14795 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14796 See the individual commands for more information."
14797 (interactive)
14798 (call-interactively
14799 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14801 (defun org-paste-special (arg)
14802 "Paste rectangular region into table, or past subtree relative to level.
14803 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14804 See the individual commands for more information."
14805 (interactive "P")
14806 (if (org-at-table-p)
14807 (org-table-paste-rectangle)
14808 (org-paste-subtree arg)))
14810 (defun org-edit-special ()
14811 "Call a special editor for the stuff at point.
14812 When at a table, call the formula editor with `org-table-edit-formulas'.
14813 When at the first line of an src example, call `org-edit-src-code'.
14814 When in an #+include line, visit the include file. Otherwise call
14815 `ffap' to visit the file at point."
14816 (interactive)
14817 (cond
14818 ((org-at-table-p)
14819 (call-interactively 'org-table-edit-formulas))
14820 ((save-excursion
14821 (beginning-of-line 1)
14822 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14823 (find-file (org-trim (match-string 1))))
14824 ((org-edit-src-code))
14825 ((org-edit-fixed-width-region))
14826 (t (call-interactively 'ffap))))
14829 (defun org-ctrl-c-ctrl-c (&optional arg)
14830 "Set tags in headline, or update according to changed information at point.
14832 This command does many different things, depending on context:
14834 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14835 this is what we do.
14837 - If the cursor is in a headline, prompt for tags and insert them
14838 into the current line, aligned to `org-tags-column'. When called
14839 with prefix arg, realign all tags in the current buffer.
14841 - If the cursor is in one of the special #+KEYWORD lines, this
14842 triggers scanning the buffer for these lines and updating the
14843 information.
14845 - If the cursor is inside a table, realign the table. This command
14846 works even if the automatic table editor has been turned off.
14848 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14849 the entire table.
14851 - If the cursor is at a footnote reference or definition, jump to
14852 the corresponding definition or references, respectively.
14854 - If the cursor is a the beginning of a dynamic block, update it.
14856 - If the cursor is inside a table created by the table.el package,
14857 activate that table.
14859 - If the current buffer is a remember buffer, close note and file
14860 it. A prefix argument of 1 files to the default location
14861 without further interaction. A prefix argument of 2 files to
14862 the currently clocking task.
14864 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14865 links in this buffer.
14867 - If the cursor is on a numbered item in a plain list, renumber the
14868 ordered list.
14870 - If the cursor is on a checkbox, toggle it."
14871 (interactive "P")
14872 (let ((org-enable-table-editor t))
14873 (cond
14874 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14875 org-occur-highlights
14876 org-latex-fragment-image-overlays)
14877 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14878 (org-remove-occur-highlights)
14879 (org-remove-latex-fragment-image-overlays)
14880 (message "Temporary highlights/overlays removed from current buffer"))
14881 ((and (local-variable-p 'org-finish-function (current-buffer))
14882 (fboundp org-finish-function))
14883 (funcall org-finish-function))
14884 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14885 ((org-at-property-p)
14886 (call-interactively 'org-property-action))
14887 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14888 ((org-on-heading-p) (call-interactively 'org-set-tags))
14889 ((org-at-table.el-p)
14890 (require 'table)
14891 (beginning-of-line 1)
14892 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14893 (call-interactively 'table-recognize-table))
14894 ((org-at-table-p)
14895 (org-table-maybe-eval-formula)
14896 (if arg
14897 (call-interactively 'org-table-recalculate)
14898 (org-table-maybe-recalculate-line))
14899 (call-interactively 'org-table-align))
14900 ((or (org-footnote-at-reference-p)
14901 (org-footnote-at-definition-p))
14902 (call-interactively 'org-footnote-action))
14903 ((org-at-item-checkbox-p)
14904 (call-interactively 'org-toggle-checkbox))
14905 ((org-at-item-p)
14906 (if arg
14907 (call-interactively 'org-toggle-checkbox)
14908 (call-interactively 'org-maybe-renumber-ordered-list)))
14909 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14910 ;; Dynamic block
14911 (beginning-of-line 1)
14912 (save-excursion (org-update-dblock)))
14913 ((save-excursion
14914 (beginning-of-line 1)
14915 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14916 (cond
14917 ((equal (match-string 1) "TBLFM")
14918 ;; Recalculate the table before this line
14919 (save-excursion
14920 (beginning-of-line 1)
14921 (skip-chars-backward " \r\n\t")
14922 (if (org-at-table-p)
14923 (org-call-with-arg 'org-table-recalculate t))))
14925 ; (org-set-regexps-and-options)
14926 ; (org-restart-font-lock)
14927 (let ((org-inhibit-startup t)) (org-mode-restart))
14928 (message "Local setup has been refreshed"))))
14929 ((org-clock-update-time-maybe))
14930 (t (error "C-c C-c can do nothing useful at this location.")))))
14932 (defun org-mode-restart ()
14933 "Restart Org-mode, to scan again for special lines.
14934 Also updates the keyword regular expressions."
14935 (interactive)
14936 (org-mode)
14937 (message "Org-mode restarted"))
14939 (defun org-kill-note-or-show-branches ()
14940 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14941 (interactive)
14942 (if (not org-finish-function)
14943 (call-interactively 'show-branches)
14944 (let ((org-note-abort t))
14945 (funcall org-finish-function))))
14947 (defun org-return (&optional indent)
14948 "Goto next table row or insert a newline.
14949 Calls `org-table-next-row' or `newline', depending on context.
14950 See the individual commands for more information."
14951 (interactive)
14952 (cond
14953 ((bobp) (if indent (newline-and-indent) (newline)))
14954 ((org-at-table-p)
14955 (org-table-justify-field-maybe)
14956 (call-interactively 'org-table-next-row))
14957 ((and org-return-follows-link
14958 (eq (get-text-property (point) 'face) 'org-link))
14959 (call-interactively 'org-open-at-point))
14960 ((and (org-at-heading-p)
14961 (looking-at
14962 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14963 (org-show-entry)
14964 (end-of-line 1)
14965 (newline))
14966 (t (if indent (newline-and-indent) (newline)))))
14968 (defun org-return-indent ()
14969 "Goto next table row or insert a newline and indent.
14970 Calls `org-table-next-row' or `newline-and-indent', depending on
14971 context. See the individual commands for more information."
14972 (interactive)
14973 (org-return t))
14975 (defun org-ctrl-c-star ()
14976 "Compute table, or change heading status of lines.
14977 Calls `org-table-recalculate' or `org-toggle-heading',
14978 depending on context."
14979 (interactive)
14980 (cond
14981 ((org-at-table-p)
14982 (call-interactively 'org-table-recalculate))
14984 ;; Convert all lines in region to list items
14985 (call-interactively 'org-toggle-heading))))
14987 (defun org-ctrl-c-minus ()
14988 "Insert separator line in table or modify bullet status of line.
14989 Also turns a plain line or a region of lines into list items.
14990 Calls `org-table-insert-hline', `org-toggle-item', or
14991 `org-cycle-list-bullet', depending on context."
14992 (interactive)
14993 (cond
14994 ((org-at-table-p)
14995 (call-interactively 'org-table-insert-hline))
14996 ((org-region-active-p)
14997 (call-interactively 'org-toggle-item))
14998 ((org-in-item-p)
14999 (call-interactively 'org-cycle-list-bullet))
15001 (call-interactively 'org-toggle-item))))
15003 (defun org-toggle-item ()
15004 "Convert headings or normal lines to items, items to normal lines.
15005 If there is no active region, only the current line is considered.
15007 If the first line in the region is a headline, convert all headlines to items.
15009 If the first line in the region is an item, convert all items to normal lines.
15011 If the first line is normal text, add an item bullet to each line."
15012 (interactive)
15013 (let (l2 l beg end)
15014 (if (org-region-active-p)
15015 (setq beg (region-beginning) end (region-end))
15016 (setq beg (point-at-bol)
15017 end (min (1+ (point-at-eol)) (point-max))))
15018 (save-excursion
15019 (goto-char end)
15020 (setq l2 (org-current-line))
15021 (goto-char beg)
15022 (beginning-of-line 1)
15023 (setq l (1- (org-current-line)))
15024 (if (org-at-item-p)
15025 ;; We already have items, de-itemize
15026 (while (< (setq l (1+ l)) l2)
15027 (when (org-at-item-p)
15028 (goto-char (match-beginning 2))
15029 (delete-region (match-beginning 2) (match-end 2))
15030 (and (looking-at "[ \t]+") (replace-match "")))
15031 (beginning-of-line 2))
15032 (if (org-on-heading-p)
15033 ;; Headings, convert to items
15034 (while (< (setq l (1+ l)) l2)
15035 (if (looking-at org-outline-regexp)
15036 (replace-match "- " t t))
15037 (beginning-of-line 2))
15038 ;; normal lines, turn them into items
15039 (while (< (setq l (1+ l)) l2)
15040 (unless (org-at-item-p)
15041 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15042 (replace-match "\\1- \\2")))
15043 (beginning-of-line 2)))))))
15045 (defun org-toggle-heading (&optional nstars)
15046 "Convert headings to normal text, or items or text to headings.
15047 If there is no active region, only the current line is considered.
15049 If the first line is a heading, remove the stars from all headlines
15050 in the region.
15052 If the first line is a plain list item, turn all plain list items
15053 into headings.
15055 If the first line is a normal line, turn each and every line in the
15056 region into a heading.
15058 When converting a line into a heading, the number of stars is chosen
15059 such that the lines become children of the current entry. However,
15060 when a prefix argument is given, its value determines the number of
15061 stars to add."
15062 (interactive "P")
15063 (let (l2 l itemp beg end)
15064 (if (org-region-active-p)
15065 (setq beg (region-beginning) end (region-end))
15066 (setq beg (point-at-bol)
15067 end (min (1+ (point-at-eol)) (point-max))))
15068 (save-excursion
15069 (goto-char end)
15070 (setq l2 (org-current-line))
15071 (goto-char beg)
15072 (beginning-of-line 1)
15073 (setq l (1- (org-current-line)))
15074 (if (org-on-heading-p)
15075 ;; We already have headlines, de-star them
15076 (while (< (setq l (1+ l)) l2)
15077 (when (org-on-heading-p t)
15078 (and (looking-at outline-regexp) (replace-match "")))
15079 (beginning-of-line 2))
15080 (setq itemp (org-at-item-p))
15081 (let* ((stars
15082 (if nstars
15083 (make-string (prefix-numeric-value current-prefix-arg)
15085 (save-excursion
15086 (if (re-search-backward org-complex-heading-regexp nil t)
15087 (match-string 1) ""))))
15088 (add-stars (cond (nstars "")
15089 ((equal stars "") "*")
15090 (org-odd-levels-only "**")
15091 (t "*")))
15092 (rpl (concat stars add-stars " ")))
15093 (while (< (setq l (1+ l)) l2)
15094 (if itemp
15095 (and (org-at-item-p) (replace-match rpl t t))
15096 (unless (org-on-heading-p)
15097 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15098 (replace-match (concat rpl (match-string 2))))))
15099 (beginning-of-line 2)))))))
15101 (defun org-meta-return (&optional arg)
15102 "Insert a new heading or wrap a region in a table.
15103 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15104 See the individual commands for more information."
15105 (interactive "P")
15106 (cond
15107 ((run-hook-with-args-until-success 'org-metareturn-hook))
15108 ((org-at-table-p)
15109 (call-interactively 'org-table-wrap-region))
15110 (t (call-interactively 'org-insert-heading))))
15112 ;;; Menu entries
15114 ;; Define the Org-mode menus
15115 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15116 '("Tbl"
15117 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15118 ["Next Field" org-cycle (org-at-table-p)]
15119 ["Previous Field" org-shifttab (org-at-table-p)]
15120 ["Next Row" org-return (org-at-table-p)]
15121 "--"
15122 ["Blank Field" org-table-blank-field (org-at-table-p)]
15123 ["Edit Field" org-table-edit-field (org-at-table-p)]
15124 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15125 "--"
15126 ("Column"
15127 ["Move Column Left" org-metaleft (org-at-table-p)]
15128 ["Move Column Right" org-metaright (org-at-table-p)]
15129 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15130 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15131 ("Row"
15132 ["Move Row Up" org-metaup (org-at-table-p)]
15133 ["Move Row Down" org-metadown (org-at-table-p)]
15134 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15135 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15136 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15137 "--"
15138 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15139 ("Rectangle"
15140 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15141 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15142 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15143 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15144 "--"
15145 ("Calculate"
15146 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15147 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15148 ["Edit Formulas" org-edit-special (org-at-table-p)]
15149 "--"
15150 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15151 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15152 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15153 "--"
15154 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15155 "--"
15156 ["Sum Column/Rectangle" org-table-sum
15157 (or (org-at-table-p) (org-region-active-p))]
15158 ["Which Column?" org-table-current-column (org-at-table-p)])
15159 ["Debug Formulas"
15160 org-table-toggle-formula-debugger
15161 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15162 ["Show Col/Row Numbers"
15163 org-table-toggle-coordinate-overlays
15164 :style toggle
15165 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15166 "--"
15167 ["Create" org-table-create (and (not (org-at-table-p))
15168 org-enable-table-editor)]
15169 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15170 ["Import from File" org-table-import (not (org-at-table-p))]
15171 ["Export to File" org-table-export (org-at-table-p)]
15172 "--"
15173 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15175 (easy-menu-define org-org-menu org-mode-map "Org menu"
15176 '("Org"
15177 ("Show/Hide"
15178 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15179 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15180 ["Sparse Tree..." org-sparse-tree t]
15181 ["Reveal Context" org-reveal t]
15182 ["Show All" show-all t]
15183 "--"
15184 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15185 "--"
15186 ["New Heading" org-insert-heading t]
15187 ("Navigate Headings"
15188 ["Up" outline-up-heading t]
15189 ["Next" outline-next-visible-heading t]
15190 ["Previous" outline-previous-visible-heading t]
15191 ["Next Same Level" outline-forward-same-level t]
15192 ["Previous Same Level" outline-backward-same-level t]
15193 "--"
15194 ["Jump" org-goto t])
15195 ("Edit Structure"
15196 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15197 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15198 "--"
15199 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15200 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15201 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15202 "--"
15203 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15204 "--"
15205 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15206 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15207 ["Demote Heading" org-metaright (not (org-at-table-p))]
15208 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15209 "--"
15210 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15211 "--"
15212 ["Convert to odd levels" org-convert-to-odd-levels t]
15213 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15214 ("Editing"
15215 ["Emphasis..." org-emphasize t]
15216 ["Edit Source Example" org-edit-special t]
15217 "--"
15218 ["Footnote new/jump" org-footnote-action t]
15219 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15220 ("Archive"
15221 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15222 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15223 ; :active t :keys "C-u C-c C-x C-a"]
15224 ["Sparse trees open ARCHIVE trees"
15225 (setq org-sparse-tree-open-archived-trees
15226 (not org-sparse-tree-open-archived-trees))
15227 :style toggle :selected org-sparse-tree-open-archived-trees]
15228 ["Cycling opens ARCHIVE trees"
15229 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15230 :style toggle :selected org-cycle-open-archived-trees]
15231 "--"
15232 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15233 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15234 ; ["Check and Move Children" (org-archive-subtree '(4))
15235 ; :active t :keys "C-u C-c C-x C-s"]
15237 "--"
15238 ("Hyperlinks"
15239 ["Store Link (Global)" org-store-link t]
15240 ["Find existing link to here" org-occur-link-in-agenda-files t]
15241 ["Insert Link" org-insert-link t]
15242 ["Follow Link" org-open-at-point t]
15243 "--"
15244 ["Next link" org-next-link t]
15245 ["Previous link" org-previous-link t]
15246 "--"
15247 ["Descriptive Links"
15248 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15249 :style radio
15250 :selected (member '(org-link) buffer-invisibility-spec)]
15251 ["Literal Links"
15252 (progn
15253 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15254 :style radio
15255 :selected (not (member '(org-link) buffer-invisibility-spec))])
15256 "--"
15257 ("TODO Lists"
15258 ["TODO/DONE/-" org-todo t]
15259 ("Select keyword"
15260 ["Next keyword" org-shiftright (org-on-heading-p)]
15261 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15262 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15263 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15264 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15265 ["Show TODO Tree" org-show-todo-tree t]
15266 ["Global TODO list" org-todo-list t]
15267 "--"
15268 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15269 :selected org-enforce-todo-dependencies :style toggle :active t]
15270 "Settings for tree at point"
15271 ["Do Children sequentially" org-toggle-ordered-property :style radio
15272 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15273 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15274 ["Do Children parallel" org-toggle-ordered-property :style radio
15275 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15276 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15277 "--"
15278 ["Set Priority" org-priority t]
15279 ["Priority Up" org-shiftup t]
15280 ["Priority Down" org-shiftdown t]
15281 "--"
15282 ["Get news from all feeds" org-feed-update-all t]
15283 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15284 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15285 ("TAGS and Properties"
15286 ["Set Tags" org-set-tags-command t]
15287 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15288 "--"
15289 ["Set property" org-set-property t]
15290 ["Column view of properties" org-columns t]
15291 ["Insert Column View DBlock" org-insert-columns-dblock t])
15292 ("Dates and Scheduling"
15293 ["Timestamp" org-time-stamp t]
15294 ["Timestamp (inactive)" org-time-stamp-inactive t]
15295 ("Change Date"
15296 ["1 Day Later" org-shiftright t]
15297 ["1 Day Earlier" org-shiftleft t]
15298 ["1 ... Later" org-shiftup t]
15299 ["1 ... Earlier" org-shiftdown t])
15300 ["Compute Time Range" org-evaluate-time-range t]
15301 ["Schedule Item" org-schedule t]
15302 ["Deadline" org-deadline t]
15303 "--"
15304 ["Custom time format" org-toggle-time-stamp-overlays
15305 :style radio :selected org-display-custom-times]
15306 "--"
15307 ["Goto Calendar" org-goto-calendar t]
15308 ["Date from Calendar" org-date-from-calendar t]
15309 "--"
15310 ["Start/Restart Timer" org-timer-start t]
15311 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15312 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15313 ["Insert Timer String" org-timer t]
15314 ["Insert Timer Item" org-timer-item t])
15315 ("Logging work"
15316 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15317 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15318 ["Clock out" org-clock-out t]
15319 ["Clock cancel" org-clock-cancel t]
15320 "--"
15321 ["Mark as default task" org-clock-mark-default-task t]
15322 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15323 ["Goto running clock" org-clock-goto t]
15324 "--"
15325 ["Display times" org-clock-display t]
15326 ["Create clock table" org-clock-report t]
15327 "--"
15328 ["Record DONE time"
15329 (progn (setq org-log-done (not org-log-done))
15330 (message "Switching to %s will %s record a timestamp"
15331 (car org-done-keywords)
15332 (if org-log-done "automatically" "not")))
15333 :style toggle :selected org-log-done])
15334 "--"
15335 ["Agenda Command..." org-agenda t]
15336 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15337 ("File List for Agenda")
15338 ("Special views current file"
15339 ["TODO Tree" org-show-todo-tree t]
15340 ["Check Deadlines" org-check-deadlines t]
15341 ["Timeline" org-timeline t]
15342 ["Tags/Property tree" org-match-sparse-tree t])
15343 "--"
15344 ["Export/Publish..." org-export t]
15345 ("LaTeX"
15346 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15347 :selected org-cdlatex-mode]
15348 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15349 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15350 ["Modify math symbol" org-cdlatex-math-modify
15351 (org-inside-LaTeX-fragment-p)]
15352 ["Insert citation" org-reftex-citation t]
15353 "--"
15354 ["Export LaTeX fragments as images"
15355 (if (featurep 'org-exp)
15356 (setq org-export-with-LaTeX-fragments
15357 (not org-export-with-LaTeX-fragments))
15358 (require 'org-exp))
15359 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15360 org-export-with-LaTeX-fragments)])
15361 "--"
15362 ("Documentation"
15363 ["Show Version" org-version t]
15364 ["Info Documentation" org-info t])
15365 ("Customize"
15366 ["Browse Org Group" org-customize t]
15367 "--"
15368 ["Expand This Menu" org-create-customize-menu
15369 (fboundp 'customize-menu-create)])
15370 ["Send bug report" org-submit-bug-report t]
15371 "--"
15372 ("Refresh/Reload"
15373 ["Refresh setup current buffer" org-mode-restart t]
15374 ["Reload Org (after update)" org-reload t]
15375 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15378 (defun org-info (&optional node)
15379 "Read documentation for Org-mode in the info system.
15380 With optional NODE, go directly to that node."
15381 (interactive)
15382 (info (format "(org)%s" (or node ""))))
15384 ;;;###autoload
15385 (defun org-submit-bug-report ()
15386 "Submit a bug report on Org-mode via mail.
15388 Don't hesitate to report any problems or inaccurate documentation.
15390 If you don't have setup sending mail from (X)Emacs, please copy the
15391 output buffer into your mail program, as it gives us important
15392 information about your Org-mode version and configuration."
15393 (interactive)
15394 (require 'reporter)
15395 (org-load-modules-maybe)
15396 (org-require-autoloaded-modules)
15397 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
15398 (reporter-submit-bug-report
15399 "emacs-orgmode@gnu.org"
15400 (org-version)
15401 (let (list)
15402 (save-window-excursion
15403 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
15404 (delete-other-windows)
15405 (erase-buffer)
15406 (insert "You are about to submit a bug report to the Org-mode mailing list.
15408 We would like to add your full Org-mode and Outline configuration to the
15409 bug report. This greatly simplifies the work of the maintainer and
15410 other experts on the mailing list.
15412 HOWEVER, some variables you have customized may contain private
15413 information. The names of customers, colleagues, or friends, might
15414 appear in the form of file names, tags, todo states, or search strings.
15415 If you answer yes to the prompt, you might want to check and remove
15416 such private information before sending the email.")
15417 (add-text-properties (point-min) (point-max) '(face org-warning))
15418 (when (yes-or-no-p "Include your Org-mode configuration ")
15419 (mapatoms
15420 (lambda (v)
15421 (and (boundp v)
15422 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
15423 (or (and (symbol-value v)
15424 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
15425 (and
15426 (get v 'custom-type) (get v 'standard-value)
15427 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
15428 (push v list)))))
15429 (kill-buffer (get-buffer "*Warn about privacy*"))
15430 list))
15431 nil nil
15432 "Remember to cover the basics, that is, what you expected to happen and
15433 what in fact did happen. You don't know hoe to make a good report? See
15435 http://orgmode.org/manual/Feedback.html#Feedback
15437 Your bug report will be posted to the Org-mode mailing list.
15438 ------------------------------------------------------------------------")))
15440 (defun org-install-agenda-files-menu ()
15441 (let ((bl (buffer-list)))
15442 (save-excursion
15443 (while bl
15444 (set-buffer (pop bl))
15445 (if (org-mode-p) (setq bl nil)))
15446 (when (org-mode-p)
15447 (easy-menu-change
15448 '("Org") "File List for Agenda"
15449 (append
15450 (list
15451 ["Edit File List" (org-edit-agenda-file-list) t]
15452 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15453 ["Remove Current File from List" org-remove-file t]
15454 ["Cycle through agenda files" org-cycle-agenda-files t]
15455 ["Occur in all agenda files" org-occur-in-agenda-files t]
15456 "--")
15457 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15459 ;;;; Documentation
15461 ;;;###autoload
15462 (defun org-require-autoloaded-modules ()
15463 (interactive)
15464 (mapc 'require
15465 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15466 org-docbook org-exp org-html org-icalendar
15467 org-id org-latex
15468 org-publish org-remember org-table
15469 org-timer org-xoxo)))
15471 ;;;###autoload
15472 (defun org-reload (&optional uncompiled)
15473 "Reload all org lisp files.
15474 With prefix arg UNCOMPILED, load the uncompiled versions."
15475 (interactive "P")
15476 (require 'find-func)
15477 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15478 (dir-org (file-name-directory (org-find-library-name "org")))
15479 (dir-org-contrib (ignore-errors
15480 (file-name-directory
15481 (org-find-library-name "org-contribdir"))))
15482 (files
15483 (append (directory-files dir-org t file-re)
15484 (and dir-org-contrib
15485 (directory-files dir-org-contrib t file-re))))
15486 (remove-re (concat (if (featurep 'xemacs)
15487 "org-colview" "org-colview-xemacs")
15488 "\\'")))
15489 (setq files (mapcar 'file-name-sans-extension files))
15490 (setq files (mapcar
15491 (lambda (x) (if (string-match remove-re x) nil x))
15492 files))
15493 (setq files (delq nil files))
15494 (mapc
15495 (lambda (f)
15496 (when (featurep (intern (file-name-nondirectory f)))
15497 (if (and (not uncompiled)
15498 (file-exists-p (concat f ".elc")))
15499 (load (concat f ".elc") nil nil t)
15500 (load (concat f ".el") nil nil t))))
15501 files))
15502 (org-version))
15504 ;;;###autoload
15505 (defun org-customize ()
15506 "Call the customize function with org as argument."
15507 (interactive)
15508 (org-load-modules-maybe)
15509 (org-require-autoloaded-modules)
15510 (customize-browse 'org))
15512 (defun org-create-customize-menu ()
15513 "Create a full customization menu for Org-mode, insert it into the menu."
15514 (interactive)
15515 (org-load-modules-maybe)
15516 (org-require-autoloaded-modules)
15517 (if (fboundp 'customize-menu-create)
15518 (progn
15519 (easy-menu-change
15520 '("Org") "Customize"
15521 `(["Browse Org group" org-customize t]
15522 "--"
15523 ,(customize-menu-create 'org)
15524 ["Set" Custom-set t]
15525 ["Save" Custom-save t]
15526 ["Reset to Current" Custom-reset-current t]
15527 ["Reset to Saved" Custom-reset-saved t]
15528 ["Reset to Standard Settings" Custom-reset-standard t]))
15529 (message "\"Org\"-menu now contains full customization menu"))
15530 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15532 ;;;; Miscellaneous stuff
15534 ;;; Generally useful functions
15536 (defun org-find-text-property-in-string (prop s)
15537 "Return the first non-nil value of property PROP in string S."
15538 (or (get-text-property 0 prop s)
15539 (get-text-property (or (next-single-property-change 0 prop s) 0)
15540 prop s)))
15542 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15543 "Display the given MESSAGE as a warning."
15544 (if (fboundp 'display-warning)
15545 (display-warning 'org message
15546 (if (featurep 'xemacs)
15547 'warning
15548 :warning))
15549 (let ((buf (get-buffer-create "*Org warnings*")))
15550 (with-current-buffer buf
15551 (goto-char (point-max))
15552 (insert "Warning (Org): " message)
15553 (unless (bolp)
15554 (newline)))
15555 (display-buffer buf)
15556 (sit-for 0))))
15558 (defun org-in-commented-line ()
15559 "Is point in a line starting with `#'?"
15560 (equal (char-after (point-at-bol)) ?#))
15562 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15563 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15564 (if (and marker (marker-buffer marker)
15565 (buffer-live-p (marker-buffer marker)))
15566 (progn
15567 (switch-to-buffer (marker-buffer marker))
15568 (if (or (> marker (point-max)) (< marker (point-min)))
15569 (widen))
15570 (goto-char marker)
15571 (org-show-context 'org-goto))
15572 (if bookmark
15573 (bookmark-jump bookmark)
15574 (error "Cannot find location"))))
15576 (defun org-quote-csv-field (s)
15577 "Quote field for inclusion in CSV material."
15578 (if (string-match "[\",]" s)
15579 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15582 (defun org-plist-delete (plist property)
15583 "Delete PROPERTY from PLIST.
15584 This is in contrast to merely setting it to 0."
15585 (let (p)
15586 (while plist
15587 (if (not (eq property (car plist)))
15588 (setq p (plist-put p (car plist) (nth 1 plist))))
15589 (setq plist (cddr plist)))
15592 (defun org-force-self-insert (N)
15593 "Needed to enforce self-insert under remapping."
15594 (interactive "p")
15595 (self-insert-command N))
15597 (defun org-string-width (s)
15598 "Compute width of string, ignoring invisible characters.
15599 This ignores character with invisibility property `org-link', and also
15600 characters with property `org-cwidth', because these will become invisible
15601 upon the next fontification round."
15602 (let (b l)
15603 (when (or (eq t buffer-invisibility-spec)
15604 (assq 'org-link buffer-invisibility-spec))
15605 (while (setq b (text-property-any 0 (length s)
15606 'invisible 'org-link s))
15607 (setq s (concat (substring s 0 b)
15608 (substring s (or (next-single-property-change
15609 b 'invisible s) (length s)))))))
15610 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15611 (setq s (concat (substring s 0 b)
15612 (substring s (or (next-single-property-change
15613 b 'org-cwidth s) (length s))))))
15614 (setq l (string-width s) b -1)
15615 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15616 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15619 (defun org-get-indentation (&optional line)
15620 "Get the indentation of the current line, interpreting tabs.
15621 When LINE is given, assume it represents a line and compute its indentation."
15622 (if line
15623 (if (string-match "^ *" (org-remove-tabs line))
15624 (match-end 0))
15625 (save-excursion
15626 (beginning-of-line 1)
15627 (skip-chars-forward " \t")
15628 (current-column))))
15630 (defun org-remove-tabs (s &optional width)
15631 "Replace tabulators in S with spaces.
15632 Assumes that s is a single line, starting in column 0."
15633 (setq width (or width tab-width))
15634 (while (string-match "\t" s)
15635 (setq s (replace-match
15636 (make-string
15637 (- (* width (/ (+ (match-beginning 0) width) width))
15638 (match-beginning 0)) ?\ )
15639 t t s)))
15642 (defun org-fix-indentation (line ind)
15643 "Fix indentation in LINE.
15644 IND is a cons cell with target and minimum indentation.
15645 If the current indentation in LINE is smaller than the minimum,
15646 leave it alone. If it is larger than ind, set it to the target."
15647 (let* ((l (org-remove-tabs line))
15648 (i (org-get-indentation l))
15649 (i1 (car ind)) (i2 (cdr ind)))
15650 (if (>= i i2) (setq l (substring line i2)))
15651 (if (> i1 0)
15652 (concat (make-string i1 ?\ ) l)
15653 l)))
15655 (defun org-remove-indentation (code &optional n)
15656 "Remove the maximum common indentation from the lines in CODE.
15657 N may optionally be the number of spaces to remove."
15658 (with-temp-buffer
15659 (insert code)
15660 (org-do-remove-indentation n)
15661 (buffer-string)))
15663 (defun org-do-remove-indentation (&optional n)
15664 "Remove the maximum common indentation from the buffer."
15665 (untabify (point-min) (point-max))
15666 (let ((min 10000) re)
15667 (if n
15668 (setq min n)
15669 (goto-char (point-min))
15670 (while (re-search-forward "^ *[^ \n]" nil t)
15671 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15672 (unless (or (= min 0) (= min 10000))
15673 (setq re (format "^ \\{%d\\}" min))
15674 (goto-char (point-min))
15675 (while (re-search-forward re nil t)
15676 (replace-match "")
15677 (end-of-line 1))
15678 min)))
15680 (defun org-base-buffer (buffer)
15681 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15682 (if (not buffer)
15683 buffer
15684 (or (buffer-base-buffer buffer)
15685 buffer)))
15687 (defun org-trim (s)
15688 "Remove whitespace at beginning and end of string."
15689 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15690 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15693 (defun org-wrap (string &optional width lines)
15694 "Wrap string to either a number of lines, or a width in characters.
15695 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15696 that costs. If there is a word longer than WIDTH, the text is actually
15697 wrapped to the length of that word.
15698 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15699 many lines, whatever width that takes.
15700 The return value is a list of lines, without newlines at the end."
15701 (let* ((words (org-split-string string "[ \t\n]+"))
15702 (maxword (apply 'max (mapcar 'org-string-width words)))
15703 w ll)
15704 (cond (width
15705 (org-do-wrap words (max maxword width)))
15706 (lines
15707 (setq w maxword)
15708 (setq ll (org-do-wrap words maxword))
15709 (if (<= (length ll) lines)
15711 (setq ll words)
15712 (while (> (length ll) lines)
15713 (setq w (1+ w))
15714 (setq ll (org-do-wrap words w)))
15715 ll))
15716 (t (error "Cannot wrap this")))))
15718 (defun org-do-wrap (words width)
15719 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15720 (let (lines line)
15721 (while words
15722 (setq line (pop words))
15723 (while (and words (< (+ (length line) (length (car words))) width))
15724 (setq line (concat line " " (pop words))))
15725 (setq lines (push line lines)))
15726 (nreverse lines)))
15728 (defun org-split-string (string &optional separators)
15729 "Splits STRING into substrings at SEPARATORS.
15730 No empty strings are returned if there are matches at the beginning
15731 and end of string."
15732 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15733 (start 0)
15734 notfirst
15735 (list nil))
15736 (while (and (string-match rexp string
15737 (if (and notfirst
15738 (= start (match-beginning 0))
15739 (< start (length string)))
15740 (1+ start) start))
15741 (< (match-beginning 0) (length string)))
15742 (setq notfirst t)
15743 (or (eq (match-beginning 0) 0)
15744 (and (eq (match-beginning 0) (match-end 0))
15745 (eq (match-beginning 0) start))
15746 (setq list
15747 (cons (substring string start (match-beginning 0))
15748 list)))
15749 (setq start (match-end 0)))
15750 (or (eq start (length string))
15751 (setq list
15752 (cons (substring string start)
15753 list)))
15754 (nreverse list)))
15756 (defun org-quote-vert (s)
15757 "Replace \"|\" with \"\\vert\"."
15758 (while (string-match "|" s)
15759 (setq s (replace-match "\\vert" t t s)))
15762 (defun org-uuidgen-p (s)
15763 "Is S an ID created by UUIDGEN?"
15764 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15766 (defun org-context ()
15767 "Return a list of contexts of the current cursor position.
15768 If several contexts apply, all are returned.
15769 Each context entry is a list with a symbol naming the context, and
15770 two positions indicating start and end of the context. Possible
15771 contexts are:
15773 :headline anywhere in a headline
15774 :headline-stars on the leading stars in a headline
15775 :todo-keyword on a TODO keyword (including DONE) in a headline
15776 :tags on the TAGS in a headline
15777 :priority on the priority cookie in a headline
15778 :item on the first line of a plain list item
15779 :item-bullet on the bullet/number of a plain list item
15780 :checkbox on the checkbox in a plain list item
15781 :table in an org-mode table
15782 :table-special on a special filed in a table
15783 :table-table in a table.el table
15784 :link on a hyperlink
15785 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15786 :target on a <<target>>
15787 :radio-target on a <<<radio-target>>>
15788 :latex-fragment on a LaTeX fragment
15789 :latex-preview on a LaTeX fragment with overlayed preview image
15791 This function expects the position to be visible because it uses font-lock
15792 faces as a help to recognize the following contexts: :table-special, :link,
15793 and :keyword."
15794 (let* ((f (get-text-property (point) 'face))
15795 (faces (if (listp f) f (list f)))
15796 (p (point)) clist o)
15797 ;; First the large context
15798 (cond
15799 ((org-on-heading-p t)
15800 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15801 (when (progn
15802 (beginning-of-line 1)
15803 (looking-at org-todo-line-tags-regexp))
15804 (push (org-point-in-group p 1 :headline-stars) clist)
15805 (push (org-point-in-group p 2 :todo-keyword) clist)
15806 (push (org-point-in-group p 4 :tags) clist))
15807 (goto-char p)
15808 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15809 (if (looking-at "\\[#[A-Z0-9]\\]")
15810 (push (org-point-in-group p 0 :priority) clist)))
15812 ((org-at-item-p)
15813 (push (org-point-in-group p 2 :item-bullet) clist)
15814 (push (list :item (point-at-bol)
15815 (save-excursion (org-end-of-item) (point)))
15816 clist)
15817 (and (org-at-item-checkbox-p)
15818 (push (org-point-in-group p 0 :checkbox) clist)))
15820 ((org-at-table-p)
15821 (push (list :table (org-table-begin) (org-table-end)) clist)
15822 (if (memq 'org-formula faces)
15823 (push (list :table-special
15824 (previous-single-property-change p 'face)
15825 (next-single-property-change p 'face)) clist)))
15826 ((org-at-table-p 'any)
15827 (push (list :table-table) clist)))
15828 (goto-char p)
15830 ;; Now the small context
15831 (cond
15832 ((org-at-timestamp-p)
15833 (push (org-point-in-group p 0 :timestamp) clist))
15834 ((memq 'org-link faces)
15835 (push (list :link
15836 (previous-single-property-change p 'face)
15837 (next-single-property-change p 'face)) clist))
15838 ((memq 'org-special-keyword faces)
15839 (push (list :keyword
15840 (previous-single-property-change p 'face)
15841 (next-single-property-change p 'face)) clist))
15842 ((org-on-target-p)
15843 (push (org-point-in-group p 0 :target) clist)
15844 (goto-char (1- (match-beginning 0)))
15845 (if (looking-at org-radio-target-regexp)
15846 (push (org-point-in-group p 0 :radio-target) clist))
15847 (goto-char p))
15848 ((setq o (car (delq nil
15849 (mapcar
15850 (lambda (x)
15851 (if (memq x org-latex-fragment-image-overlays) x))
15852 (org-overlays-at (point))))))
15853 (push (list :latex-fragment
15854 (org-overlay-start o) (org-overlay-end o)) clist)
15855 (push (list :latex-preview
15856 (org-overlay-start o) (org-overlay-end o)) clist))
15857 ((org-inside-LaTeX-fragment-p)
15858 ;; FIXME: positions wrong.
15859 (push (list :latex-fragment (point) (point)) clist)))
15861 (setq clist (nreverse (delq nil clist)))
15862 clist))
15864 ;; FIXME: Compare with at-regexp-p Do we need both?
15865 (defun org-in-regexp (re &optional nlines visually)
15866 "Check if point is inside a match of regexp.
15867 Normally only the current line is checked, but you can include NLINES extra
15868 lines both before and after point into the search.
15869 If VISUALLY is set, require that the cursor is not after the match but
15870 really on, so that the block visually is on the match."
15871 (catch 'exit
15872 (let ((pos (point))
15873 (eol (point-at-eol (+ 1 (or nlines 0))))
15874 (inc (if visually 1 0)))
15875 (save-excursion
15876 (beginning-of-line (- 1 (or nlines 0)))
15877 (while (re-search-forward re eol t)
15878 (if (and (<= (match-beginning 0) pos)
15879 (>= (+ inc (match-end 0)) pos))
15880 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15882 (defun org-at-regexp-p (regexp)
15883 "Is point inside a match of REGEXP in the current line?"
15884 (catch 'exit
15885 (save-excursion
15886 (let ((pos (point)) (end (point-at-eol)))
15887 (beginning-of-line 1)
15888 (while (re-search-forward regexp end t)
15889 (if (and (<= (match-beginning 0) pos)
15890 (>= (match-end 0) pos))
15891 (throw 'exit t)))
15892 nil))))
15894 (defun org-occur-in-agenda-files (regexp &optional nlines)
15895 "Call `multi-occur' with buffers for all agenda files."
15896 (interactive "sOrg-files matching: \np")
15897 (let* ((files (org-agenda-files))
15898 (tnames (mapcar 'file-truename files))
15899 (extra org-agenda-text-search-extra-files)
15901 (when (eq (car extra) 'agenda-archives)
15902 (setq extra (cdr extra))
15903 (setq files (org-add-archive-files files)))
15904 (while (setq f (pop extra))
15905 (unless (member (file-truename f) tnames)
15906 (add-to-list 'files f 'append)
15907 (add-to-list 'tnames (file-truename f) 'append)))
15908 (multi-occur
15909 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15910 regexp)))
15912 (if (boundp 'occur-mode-find-occurrence-hook)
15913 ;; Emacs 23
15914 (add-hook 'occur-mode-find-occurrence-hook
15915 (lambda ()
15916 (when (org-mode-p)
15917 (org-reveal))))
15918 ;; Emacs 22
15919 (defadvice occur-mode-goto-occurrence
15920 (after org-occur-reveal activate)
15921 (and (org-mode-p) (org-reveal)))
15922 (defadvice occur-mode-goto-occurrence-other-window
15923 (after org-occur-reveal activate)
15924 (and (org-mode-p) (org-reveal)))
15925 (defadvice occur-mode-display-occurrence
15926 (after org-occur-reveal activate)
15927 (when (org-mode-p)
15928 (let ((pos (occur-mode-find-occurrence)))
15929 (with-current-buffer (marker-buffer pos)
15930 (save-excursion
15931 (goto-char pos)
15932 (org-reveal)))))))
15934 (defun org-occur-link-in-agenda-files ()
15935 "Create a link and search for it in the agendas.
15936 The link is not stored in `org-stored-links', it is just created
15937 for the search purpose."
15938 (interactive)
15939 (let ((link (condition-case nil
15940 (org-store-link nil)
15941 (error "Unable to create a link to here"))))
15942 (org-occur-in-agenda-files (regexp-quote link))))
15944 (defun org-uniquify (list)
15945 "Remove duplicate elements from LIST."
15946 (let (res)
15947 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15948 res))
15950 (defun org-delete-all (elts list)
15951 "Remove all elements in ELTS from LIST."
15952 (while elts
15953 (setq list (delete (pop elts) list)))
15954 list)
15956 (defun org-back-over-empty-lines ()
15957 "Move backwards over whitespace, to the beginning of the first empty line.
15958 Returns the number of empty lines passed."
15959 (let ((pos (point)))
15960 (skip-chars-backward " \t\n\r")
15961 (beginning-of-line 2)
15962 (goto-char (min (point) pos))
15963 (count-lines (point) pos)))
15965 (defun org-skip-whitespace ()
15966 (skip-chars-forward " \t\n\r"))
15968 (defun org-point-in-group (point group &optional context)
15969 "Check if POINT is in match-group GROUP.
15970 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15971 match. If the match group does ot exist or point is not inside it,
15972 return nil."
15973 (and (match-beginning group)
15974 (>= point (match-beginning group))
15975 (<= point (match-end group))
15976 (if context
15977 (list context (match-beginning group) (match-end group))
15978 t)))
15980 (defun org-switch-to-buffer-other-window (&rest args)
15981 "Switch to buffer in a second window on the current frame.
15982 In particular, do not allow pop-up frames."
15983 (let (pop-up-frames special-display-buffer-names special-display-regexps
15984 special-display-function)
15985 (apply 'switch-to-buffer-other-window args)))
15987 (defun org-combine-plists (&rest plists)
15988 "Create a single property list from all plists in PLISTS.
15989 The process starts by copying the first list, and then setting properties
15990 from the other lists. Settings in the last list are the most significant
15991 ones and overrule settings in the other lists."
15992 (let ((rtn (copy-sequence (pop plists)))
15993 p v ls)
15994 (while plists
15995 (setq ls (pop plists))
15996 (while ls
15997 (setq p (pop ls) v (pop ls))
15998 (setq rtn (plist-put rtn p v))))
15999 rtn))
16001 (defun org-move-line-down (arg)
16002 "Move the current line down. With prefix argument, move it past ARG lines."
16003 (interactive "p")
16004 (let ((col (current-column))
16005 beg end pos)
16006 (beginning-of-line 1) (setq beg (point))
16007 (beginning-of-line 2) (setq end (point))
16008 (beginning-of-line (+ 1 arg))
16009 (setq pos (move-marker (make-marker) (point)))
16010 (insert (delete-and-extract-region beg end))
16011 (goto-char pos)
16012 (org-move-to-column col)))
16014 (defun org-move-line-up (arg)
16015 "Move the current line up. With prefix argument, move it past ARG lines."
16016 (interactive "p")
16017 (let ((col (current-column))
16018 beg end pos)
16019 (beginning-of-line 1) (setq beg (point))
16020 (beginning-of-line 2) (setq end (point))
16021 (beginning-of-line (- arg))
16022 (setq pos (move-marker (make-marker) (point)))
16023 (insert (delete-and-extract-region beg end))
16024 (goto-char pos)
16025 (org-move-to-column col)))
16027 (defun org-replace-escapes (string table)
16028 "Replace %-escapes in STRING with values in TABLE.
16029 TABLE is an association list with keys like \"%a\" and string values.
16030 The sequences in STRING may contain normal field width and padding information,
16031 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16032 so values can contain further %-escapes if they are define later in TABLE."
16033 (let ((case-fold-search nil)
16034 e re rpl)
16035 (while (setq e (pop table))
16036 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16037 (while (string-match re string)
16038 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16039 (cdr e)))
16040 (setq string (replace-match rpl t t string))))
16041 string))
16044 (defun org-sublist (list start end)
16045 "Return a section of LIST, from START to END.
16046 Counting starts at 1."
16047 (let (rtn (c start))
16048 (setq list (nthcdr (1- start) list))
16049 (while (and list (<= c end))
16050 (push (pop list) rtn)
16051 (setq c (1+ c)))
16052 (nreverse rtn)))
16054 (defun org-find-base-buffer-visiting (file)
16055 "Like `find-buffer-visiting' but always return the base buffer and
16056 not an indirect buffer."
16057 (let ((buf (or (get-file-buffer file)
16058 (find-buffer-visiting file))))
16059 (if buf
16060 (or (buffer-base-buffer buf) buf)
16061 nil)))
16063 (defun org-image-file-name-regexp (&optional extensions)
16064 "Return regexp matching the file names of images.
16065 If EXTENSIONS is given, only match these."
16066 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16067 (image-file-name-regexp)
16068 (let ((image-file-name-extensions
16069 (or extensions
16070 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16071 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16072 (concat "\\."
16073 (regexp-opt (nconc (mapcar 'upcase
16074 image-file-name-extensions)
16075 image-file-name-extensions)
16077 "\\'"))))
16079 (defun org-file-image-p (file &optional extensions)
16080 "Return non-nil if FILE is an image."
16081 (save-match-data
16082 (string-match (org-image-file-name-regexp extensions) file)))
16084 (defun org-get-cursor-date ()
16085 "Return the date at cursor in as a time.
16086 This works in the calendar and in the agenda, anywhere else it just
16087 returns the current time."
16088 (let (date day defd)
16089 (cond
16090 ((eq major-mode 'calendar-mode)
16091 (setq date (calendar-cursor-to-date)
16092 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16093 ((eq major-mode 'org-agenda-mode)
16094 (setq day (get-text-property (point) 'day))
16095 (if day
16096 (setq date (calendar-gregorian-from-absolute day)
16097 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16098 (nth 2 date))))))
16099 (or defd (current-time))))
16101 (defvar org-agenda-action-marker (make-marker)
16102 "Marker pointing to the entry for the next agenda action.")
16104 (defun org-mark-entry-for-agenda-action ()
16105 "Mark the current entry as target of an agenda action.
16106 Agenda actions are actions executed from the agenda with the key `k',
16107 which make use of the date at the cursor."
16108 (interactive)
16109 (move-marker org-agenda-action-marker
16110 (save-excursion (org-back-to-heading t) (point))
16111 (current-buffer))
16112 (message
16113 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16115 ;;; Paragraph filling stuff.
16116 ;; We want this to be just right, so use the full arsenal.
16118 (defun org-indent-line-function ()
16119 "Indent line like previous, but further if previous was headline or item."
16120 (interactive)
16121 (let* ((pos (point))
16122 (itemp (org-at-item-p))
16123 (case-fold-search t)
16124 (org-drawer-regexp (or org-drawer-regexp "\000"))
16125 column bpos bcol tpos tcol bullet btype bullet-type)
16126 ;; Find the previous relevant line
16127 (beginning-of-line 1)
16128 (cond
16129 ((looking-at "#") (setq column 0))
16130 ((looking-at "\\*+ ") (setq column 0))
16131 ((and (looking-at "[ \t]*:END:")
16132 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16133 (save-excursion
16134 (goto-char (1- (match-beginning 1)))
16135 (setq column (current-column))))
16136 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16137 (save-excursion
16138 (re-search-backward
16139 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16140 (setq column (org-get-indentation (match-string 0))))
16142 (beginning-of-line 0)
16143 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16144 (not (looking-at "[ \t]*:END:"))
16145 (not (looking-at org-drawer-regexp)))
16146 (beginning-of-line 0))
16147 (cond
16148 ((looking-at "\\*+[ \t]+")
16149 (if (not org-adapt-indentation)
16150 (setq column 0)
16151 (goto-char (match-end 0))
16152 (setq column (current-column))))
16153 ((looking-at org-drawer-regexp)
16154 (goto-char (1- (match-beginning 1)))
16155 (setq column (current-column)))
16156 ((looking-at "\\([ \t]*\\):END:")
16157 (goto-char (match-end 1))
16158 (setq column (current-column)))
16159 ((org-in-item-p)
16160 (org-beginning-of-item)
16161 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16162 (setq bpos (match-beginning 1) tpos (match-end 0)
16163 bcol (progn (goto-char bpos) (current-column))
16164 tcol (progn (goto-char tpos) (current-column))
16165 bullet (match-string 1)
16166 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16167 (if (> tcol (+ bcol org-description-max-indent))
16168 (setq tcol (+ bcol 5)))
16169 (if (not itemp)
16170 (setq column tcol)
16171 (goto-char pos)
16172 (beginning-of-line 1)
16173 (if (looking-at "\\S-")
16174 (progn
16175 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16176 (setq bullet (match-string 1)
16177 btype (if (string-match "[0-9]" bullet) "n" bullet))
16178 (setq column (if (equal btype bullet-type) bcol tcol)))
16179 (setq column (org-get-indentation)))))
16180 (t (setq column (org-get-indentation))))))
16181 (goto-char pos)
16182 (if (<= (current-column) (current-indentation))
16183 (org-indent-line-to column)
16184 (save-excursion (org-indent-line-to column)))
16185 (setq column (current-column))
16186 (beginning-of-line 1)
16187 (if (looking-at
16188 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16189 (replace-match (concat "\\1" (format org-property-format
16190 (match-string 2) (match-string 3)))
16191 t nil))
16192 (org-move-to-column column)))
16194 (defun org-set-autofill-regexps ()
16195 (interactive)
16196 ;; In the paragraph separator we include headlines, because filling
16197 ;; text in a line directly attached to a headline would otherwise
16198 ;; fill the headline as well.
16199 (org-set-local 'comment-start-skip "^#+[ \t]*")
16200 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
16201 ;; The paragraph starter includes hand-formatted lists.
16202 (org-set-local
16203 'paragraph-start
16204 (concat
16205 "\f" "\\|"
16206 "[ ]*$" "\\|"
16207 "\\*+ " "\\|"
16208 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16209 "[ \t]*[:|]" "\\|"
16210 "\\$\\$" "\\|"
16211 "\\\\\\(begin\\|end\\|[][]\\)"))
16212 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16213 ;; But only if the user has not turned off tables or fixed-width regions
16214 (org-set-local
16215 'auto-fill-inhibit-regexp
16216 (concat "\\*+ \\|#\\+"
16217 "\\|[ \t]*" org-keyword-time-regexp
16218 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16219 (concat
16220 "\\|[ \t]*["
16221 (if org-enable-table-editor "|" "")
16222 (if org-enable-fixed-width-editor ":" "")
16223 "]"))))
16224 ;; We use our own fill-paragraph function, to make sure that tables
16225 ;; and fixed-width regions are not wrapped. That function will pass
16226 ;; through to `fill-paragraph' when appropriate.
16227 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16228 ; Adaptive filling: To get full control, first make sure that
16229 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16230 (org-set-local 'adaptive-fill-regexp "\000")
16231 (org-set-local 'adaptive-fill-function
16232 'org-adaptive-fill-function)
16233 (org-set-local
16234 'align-mode-rules-list
16235 '((org-in-buffer-settings
16236 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16237 (modes . '(org-mode))))))
16239 (defun org-fill-paragraph (&optional justify)
16240 "Re-align a table, pass through to fill-paragraph if no table."
16241 (let ((table-p (org-at-table-p))
16242 (table.el-p (org-at-table.el-p)))
16243 (cond ((and (equal (char-after (point-at-bol)) ?*)
16244 (save-excursion (goto-char (point-at-bol))
16245 (looking-at outline-regexp)))
16246 t) ; skip headlines
16247 (table.el-p t) ; skip table.el tables
16248 (table-p (org-table-align) t) ; align org-mode tables
16249 (t nil)))) ; call paragraph-fill
16251 ;; For reference, this is the default value of adaptive-fill-regexp
16252 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16254 (defun org-adaptive-fill-function ()
16255 "Return a fill prefix for org-mode files.
16256 In particular, this makes sure hanging paragraphs for hand-formatted lists
16257 work correctly."
16258 (cond ((looking-at "#[ \t]+")
16259 (match-string 0))
16260 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16261 (save-excursion
16262 (if (> (match-end 1) (+ (match-beginning 1)
16263 org-description-max-indent))
16264 (goto-char (+ (match-beginning 1) 5))
16265 (goto-char (match-end 0)))
16266 (make-string (current-column) ?\ )))
16267 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16268 (save-excursion
16269 (goto-char (match-end 0))
16270 (make-string (current-column) ?\ )))
16271 (t nil)))
16273 ;;; Other stuff.
16275 (defun org-toggle-fixed-width-section (arg)
16276 "Toggle the fixed-width export.
16277 If there is no active region, the QUOTE keyword at the current headline is
16278 inserted or removed. When present, it causes the text between this headline
16279 and the next to be exported as fixed-width text, and unmodified.
16280 If there is an active region, this command adds or removes a colon as the
16281 first character of this line. If the first character of a line is a colon,
16282 this line is also exported in fixed-width font."
16283 (interactive "P")
16284 (let* ((cc 0)
16285 (regionp (org-region-active-p))
16286 (beg (if regionp (region-beginning) (point)))
16287 (end (if regionp (region-end)))
16288 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16289 (case-fold-search nil)
16290 (re "[ \t]*\\(: \\)")
16291 off)
16292 (if regionp
16293 (save-excursion
16294 (goto-char beg)
16295 (setq cc (current-column))
16296 (beginning-of-line 1)
16297 (setq off (looking-at re))
16298 (while (> nlines 0)
16299 (setq nlines (1- nlines))
16300 (beginning-of-line 1)
16301 (cond
16302 (arg
16303 (org-move-to-column cc t)
16304 (insert ": \n")
16305 (forward-line -1))
16306 ((and off (looking-at re))
16307 (replace-match "" t t nil 1))
16308 ((not off) (org-move-to-column cc t) (insert ": ")))
16309 (forward-line 1)))
16310 (save-excursion
16311 (org-back-to-heading)
16312 (if (looking-at (concat outline-regexp
16313 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16314 (replace-match "" t t nil 1)
16315 (if (looking-at outline-regexp)
16316 (progn
16317 (goto-char (match-end 0))
16318 (insert org-quote-string " "))))))))
16320 (defun org-reftex-citation ()
16321 "Use reftex-citation to insert a citation into the buffer.
16322 This looks for a line like
16324 #+BIBLIOGRAPHY: foo plain option:-d
16326 and derives from it that foo.bib is the bbliography file relevant
16327 for this document. It then installs the necessary environment for RefTeX
16328 to work in this buffer and calls `reftex-citation' to insert a citation
16329 into the buffer.
16331 Export of such citations to both LaTeX and HTML is handled by the contributed
16332 package org-exp-bibtex by Taru Karttunen."
16333 (interactive)
16334 (let ((reftex-docstruct-symbol 'rds)
16335 (reftex-cite-format "\\cite{%l}")
16336 rds bib)
16337 (save-excursion
16338 (save-restriction
16339 (widen)
16340 (let ((case-fold-search t)
16341 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16342 (if (not (save-excursion
16343 (or (re-search-forward re nil t)
16344 (re-search-backward re nil t))))
16345 (error "No bibliography defined in file")
16346 (setq bib (concat (match-string 1) ".bib")
16347 rds (list (list 'bib bib)))))))
16348 (call-interactively 'reftex-citation)))
16350 ;;;; Functions extending outline functionality
16352 (defun org-beginning-of-line (&optional arg)
16353 "Go to the beginning of the current line. If that is invisible, continue
16354 to a visible line beginning. This makes the function of C-a more intuitive.
16355 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16356 first attempt, and only move to after the tags when the cursor is already
16357 beyond the end of the headline."
16358 (interactive "P")
16359 (let ((pos (point))
16360 (special (if (consp org-special-ctrl-a/e)
16361 (car org-special-ctrl-a/e)
16362 org-special-ctrl-a/e))
16363 refpos)
16364 (if (org-bound-and-true-p line-move-visual)
16365 (beginning-of-visual-line 1)
16366 (beginning-of-line 1))
16367 (if (and arg (fboundp 'move-beginning-of-line))
16368 (call-interactively 'move-beginning-of-line)
16369 (if (bobp)
16371 (backward-char 1)
16372 (if (org-invisible-p)
16373 (while (and (not (bobp)) (org-invisible-p))
16374 (backward-char 1)
16375 (beginning-of-line 1))
16376 (forward-char 1))))
16377 (when special
16378 (cond
16379 ((and (looking-at org-complex-heading-regexp)
16380 (= (char-after (match-end 1)) ?\ ))
16381 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16382 (point-at-eol)))
16383 (goto-char
16384 (if (eq special t)
16385 (cond ((> pos refpos) refpos)
16386 ((= pos (point)) refpos)
16387 (t (point)))
16388 (cond ((> pos (point)) (point))
16389 ((not (eq last-command this-command)) (point))
16390 (t refpos)))))
16391 ((org-at-item-p)
16392 (goto-char
16393 (if (eq special t)
16394 (cond ((> pos (match-end 4)) (match-end 4))
16395 ((= pos (point)) (match-end 4))
16396 (t (point)))
16397 (cond ((> pos (point)) (point))
16398 ((not (eq last-command this-command)) (point))
16399 (t (match-end 4))))))))
16400 (org-no-warnings
16401 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16403 (defun org-end-of-line (&optional arg)
16404 "Go to the end of the line.
16405 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16406 first attempt, and only move to after the tags when the cursor is already
16407 beyond the end of the headline."
16408 (interactive "P")
16409 (let ((special (if (consp org-special-ctrl-a/e)
16410 (cdr org-special-ctrl-a/e)
16411 org-special-ctrl-a/e)))
16412 (if (or (not special)
16413 (not (org-on-heading-p))
16414 arg)
16415 (call-interactively
16416 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16417 ((fboundp 'move-end-of-line) 'move-end-of-line)
16418 (t 'end-of-line)))
16419 (let ((pos (point)))
16420 (beginning-of-line 1)
16421 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16422 (if (eq special t)
16423 (if (or (< pos (match-beginning 1))
16424 (= pos (match-end 0)))
16425 (goto-char (match-beginning 1))
16426 (goto-char (match-end 0)))
16427 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16428 (goto-char (match-end 0))
16429 (goto-char (match-beginning 1))))
16430 (call-interactively (if (fboundp 'move-end-of-line)
16431 'move-end-of-line
16432 'end-of-line)))))
16433 (org-no-warnings
16434 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16436 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16437 (define-key org-mode-map "\C-e" 'org-end-of-line)
16439 (defun org-backward-sentence (&optional arg)
16440 "Go to beginning of sentence, or beginning of table field.
16441 This will call `backward-sentence' or `org-table-beginning-of-field',
16442 depending on context."
16443 (interactive "P")
16444 (cond
16445 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16446 (t (call-interactively 'backward-sentence))))
16448 (defun org-forward-sentence (&optional arg)
16449 "Go to end of sentence, or end of table field.
16450 This will call `forward-sentence' or `org-table-end-of-field',
16451 depending on context."
16452 (interactive "P")
16453 (cond
16454 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16455 (t (call-interactively 'forward-sentence))))
16457 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16458 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16460 (defun org-kill-line (&optional arg)
16461 "Kill line, to tags or end of line."
16462 (interactive "P")
16463 (cond
16464 ((or (not org-special-ctrl-k)
16465 (bolp)
16466 (not (org-on-heading-p)))
16467 (call-interactively 'kill-line))
16468 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16469 (kill-region (point) (match-beginning 1))
16470 (org-set-tags nil t))
16471 (t (kill-region (point) (point-at-eol)))))
16473 (define-key org-mode-map "\C-k" 'org-kill-line)
16475 (defun org-yank (&optional arg)
16476 "Yank. If the kill is a subtree, treat it specially.
16477 This command will look at the current kill and check if is a single
16478 subtree, or a series of subtrees[1]. If it passes the test, and if the
16479 cursor is at the beginning of a line or after the stars of a currently
16480 empty headline, then the yank is handled specially. How exactly depends
16481 on the value of the following variables, both set by default.
16483 org-yank-folded-subtrees
16484 When set, the subtree(s) will be folded after insertion, but only
16485 if doing so would now swallow text after the yanked text.
16487 org-yank-adjusted-subtrees
16488 When set, the subtree will be promoted or demoted in order to
16489 fit into the local outline tree structure, which means that the level
16490 will be adjusted so that it becomes the smaller one of the two
16491 *visible* surrounding headings.
16493 Any prefix to this command will cause `yank' to be called directly with
16494 no special treatment. In particular, a simple `C-u' prefix will just
16495 plainly yank the text as it is.
16497 \[1] The test checks if the first non-white line is a heading
16498 and if there are no other headings with fewer stars."
16499 (interactive "P")
16500 (org-yank-generic 'yank arg))
16502 (defun org-yank-generic (command arg)
16503 "Perform some yank-like command.
16505 This function implements the behavior described in the `org-yank'
16506 documentation. However, it has been generalized to work for any
16507 interactive command with similar behavior."
16509 ;; pretend to be command COMMAND
16510 (setq this-command command)
16512 (if arg
16513 (call-interactively command)
16515 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16516 (and (org-kill-is-subtree-p)
16517 (or (bolp)
16518 (and (looking-at "[ \t]*$")
16519 (string-match
16520 "\\`\\*+\\'"
16521 (buffer-substring (point-at-bol) (point)))))))
16522 swallowp)
16523 (cond
16524 ((and subtreep org-yank-folded-subtrees)
16525 (let ((beg (point))
16526 end)
16527 (if (and subtreep org-yank-adjusted-subtrees)
16528 (org-paste-subtree nil nil 'for-yank)
16529 (call-interactively command))
16531 (setq end (point))
16532 (goto-char beg)
16533 (when (and (bolp) subtreep
16534 (not (setq swallowp
16535 (org-yank-folding-would-swallow-text beg end))))
16536 (or (looking-at outline-regexp)
16537 (re-search-forward (concat "^" outline-regexp) end t))
16538 (while (and (< (point) end) (looking-at outline-regexp))
16539 (hide-subtree)
16540 (org-cycle-show-empty-lines 'folded)
16541 (condition-case nil
16542 (outline-forward-same-level 1)
16543 (error (goto-char end)))))
16544 (when swallowp
16545 (message
16546 "Inserted text not folded because that would swallow text"))
16548 (goto-char end)
16549 (skip-chars-forward " \t\n\r")
16550 (beginning-of-line 1)
16551 (push-mark beg 'nomsg)))
16552 ((and subtreep org-yank-adjusted-subtrees)
16553 (let ((beg (point-at-bol)))
16554 (org-paste-subtree nil nil 'for-yank)
16555 (push-mark beg 'nomsg)))
16557 (call-interactively command))))))
16559 (defun org-yank-folding-would-swallow-text (beg end)
16560 "Would hide-subtree at BEG swallow any text after END?"
16561 (let (level)
16562 (save-excursion
16563 (goto-char beg)
16564 (when (or (looking-at outline-regexp)
16565 (re-search-forward (concat "^" outline-regexp) end t))
16566 (setq level (org-outline-level)))
16567 (goto-char end)
16568 (skip-chars-forward " \t\r\n\v\f")
16569 (if (or (eobp)
16570 (and (bolp) (looking-at org-outline-regexp)
16571 (<= (org-outline-level) level)))
16572 nil ; Nothing would be swallowed
16573 t)))) ; something would swallow
16575 (define-key org-mode-map "\C-y" 'org-yank)
16577 (defun org-invisible-p ()
16578 "Check if point is at a character currently not visible."
16579 ;; Early versions of noutline don't have `outline-invisible-p'.
16580 (if (fboundp 'outline-invisible-p)
16581 (outline-invisible-p)
16582 (get-char-property (point) 'invisible)))
16584 (defun org-invisible-p2 ()
16585 "Check if point is at a character currently not visible."
16586 (save-excursion
16587 (if (and (eolp) (not (bobp))) (backward-char 1))
16588 ;; Early versions of noutline don't have `outline-invisible-p'.
16589 (if (fboundp 'outline-invisible-p)
16590 (outline-invisible-p)
16591 (get-char-property (point) 'invisible))))
16593 (defun org-back-to-heading (&optional invisible-ok)
16594 "Call `outline-back-to-heading', but provide a better error message."
16595 (condition-case nil
16596 (outline-back-to-heading invisible-ok)
16597 (error (error "Before first headline at position %d in buffer %s"
16598 (point) (current-buffer)))))
16600 (defun org-before-first-heading-p ()
16601 "Before first heading?"
16602 (save-excursion
16603 (null (re-search-backward "^\\*+ " nil t))))
16605 (defalias 'org-on-heading-p 'outline-on-heading-p)
16606 (defalias 'org-at-heading-p 'outline-on-heading-p)
16607 (defun org-at-heading-or-item-p ()
16608 (or (org-on-heading-p) (org-at-item-p)))
16610 (defun org-on-target-p ()
16611 (or (org-in-regexp org-radio-target-regexp)
16612 (org-in-regexp org-target-regexp)))
16614 (defun org-up-heading-all (arg)
16615 "Move to the heading line of which the present line is a subheading.
16616 This function considers both visible and invisible heading lines.
16617 With argument, move up ARG levels."
16618 (if (fboundp 'outline-up-heading-all)
16619 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16620 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16622 (defun org-up-heading-safe ()
16623 "Move to the heading line of which the present line is a subheading.
16624 This version will not throw an error. It will return the level of the
16625 headline found, or nil if no higher level is found.
16627 Also, this function will be a lot faster than `outline-up-heading',
16628 because it relies on stars being the outline starters. This can really
16629 make a significant difference in outlines with very many siblings."
16630 (let (start-level re)
16631 (org-back-to-heading t)
16632 (setq start-level (funcall outline-level))
16633 (if (equal start-level 1)
16635 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16636 (if (re-search-backward re nil t)
16637 (funcall outline-level)))))
16639 (defun org-first-sibling-p ()
16640 "Is this heading the first child of its parents?"
16641 (interactive)
16642 (let ((re (concat "^" outline-regexp))
16643 level l)
16644 (unless (org-at-heading-p t)
16645 (error "Not at a heading"))
16646 (setq level (funcall outline-level))
16647 (save-excursion
16648 (if (not (re-search-backward re nil t))
16650 (setq l (funcall outline-level))
16651 (< l level)))))
16653 (defun org-goto-sibling (&optional previous)
16654 "Goto the next sibling, even if it is invisible.
16655 When PREVIOUS is set, go to the previous sibling instead. Returns t
16656 when a sibling was found. When none is found, return nil and don't
16657 move point."
16658 (let ((fun (if previous 're-search-backward 're-search-forward))
16659 (pos (point))
16660 (re (concat "^" outline-regexp))
16661 level l)
16662 (when (condition-case nil (org-back-to-heading t) (error nil))
16663 (setq level (funcall outline-level))
16664 (catch 'exit
16665 (or previous (forward-char 1))
16666 (while (funcall fun re nil t)
16667 (setq l (funcall outline-level))
16668 (when (< l level) (goto-char pos) (throw 'exit nil))
16669 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16670 (goto-char pos)
16671 nil))))
16673 (defun org-show-siblings ()
16674 "Show all siblings of the current headline."
16675 (save-excursion
16676 (while (org-goto-sibling) (org-flag-heading nil)))
16677 (save-excursion
16678 (while (org-goto-sibling 'previous)
16679 (org-flag-heading nil))))
16681 (defun org-show-hidden-entry ()
16682 "Show an entry where even the heading is hidden."
16683 (save-excursion
16684 (org-show-entry)))
16686 (defun org-flag-heading (flag &optional entry)
16687 "Flag the current heading. FLAG non-nil means make invisible.
16688 When ENTRY is non-nil, show the entire entry."
16689 (save-excursion
16690 (org-back-to-heading t)
16691 ;; Check if we should show the entire entry
16692 (if entry
16693 (progn
16694 (org-show-entry)
16695 (save-excursion
16696 (and (outline-next-heading)
16697 (org-flag-heading nil))))
16698 (outline-flag-region (max (point-min) (1- (point)))
16699 (save-excursion (outline-end-of-heading) (point))
16700 flag))))
16702 (defun org-get-next-sibling ()
16703 "Move to next heading of the same level, and return point.
16704 If there is no such heading, return nil.
16705 This is like outline-next-sibling, but invisible headings are ok."
16706 (let ((level (funcall outline-level)))
16707 (outline-next-heading)
16708 (while (and (not (eobp)) (> (funcall outline-level) level))
16709 (outline-next-heading))
16710 (if (or (eobp) (< (funcall outline-level) level))
16712 (point))))
16714 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16715 ;; This contains an exact copy of the original function, but it uses
16716 ;; `org-back-to-heading', to make it work also in invisible
16717 ;; trees. And is uses an invisible-OK argument.
16718 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16719 ;; Furthermore, when used inside Org, finding the end of a large subtree
16720 ;; with many children and grandchildren etc, this can be much faster
16721 ;; than the outline version.
16722 (org-back-to-heading invisible-OK)
16723 (let ((first t)
16724 (level (funcall outline-level)))
16725 (if (and (org-mode-p) (< level 1000))
16726 ;; A true heading (not a plain list item), in Org-mode
16727 ;; This means we can easily find the end by looking
16728 ;; only for the right number of stars. Using a regexp to do
16729 ;; this is so much faster than using a Lisp loop.
16730 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16731 (forward-char 1)
16732 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16733 ;; something else, do it the slow way
16734 (while (and (not (eobp))
16735 (or first (> (funcall outline-level) level)))
16736 (setq first nil)
16737 (outline-next-heading)))
16738 (unless to-heading
16739 (if (memq (preceding-char) '(?\n ?\^M))
16740 (progn
16741 ;; Go to end of line before heading
16742 (forward-char -1)
16743 (if (memq (preceding-char) '(?\n ?\^M))
16744 ;; leave blank line before heading
16745 (forward-char -1))))))
16746 (point))
16748 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16749 "Use Org version in org-mode, for dramatic speed-up."
16750 (if (eq major-mode 'org-mode)
16751 (progn
16752 (org-end-of-subtree nil t)
16753 (backward-char 1))
16754 ad-do-it))
16756 (defun org-forward-same-level (arg &optional invisible-ok)
16757 "Move forward to the arg'th subheading at same level as this one.
16758 Stop at the first and last subheadings of a superior heading."
16759 (interactive "p")
16760 (org-back-to-heading invisible-ok)
16761 (org-on-heading-p)
16762 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16763 (re (format "^\\*\\{1,%d\\} " level))
16765 (forward-char 1)
16766 (while (> arg 0)
16767 (while (and (re-search-forward re nil 'move)
16768 (setq l (- (match-end 0) (match-beginning 0) 1))
16769 (= l level)
16770 (not invisible-ok)
16771 (org-invisible-p))
16772 (if (< l level) (setq arg 1)))
16773 (setq arg (1- arg)))
16774 (beginning-of-line 1)))
16776 (defun org-backward-same-level (arg &optional invisible-ok)
16777 "Move backward to the arg'th subheading at same level as this one.
16778 Stop at the first and last subheadings of a superior heading."
16779 (interactive "p")
16780 (org-back-to-heading)
16781 (org-on-heading-p)
16782 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16783 (re (format "^\\*\\{1,%d\\} " level))
16785 (while (> arg 0)
16786 (while (and (re-search-backward re nil 'move)
16787 (setq l (- (match-end 0) (match-beginning 0) 1))
16788 (= l level)
16789 (not invisible-ok)
16790 (org-invisible-p))
16791 (if (< l level) (setq arg 1)))
16792 (setq arg (1- arg)))))
16794 (defun org-show-subtree ()
16795 "Show everything after this heading at deeper levels."
16796 (outline-flag-region
16797 (point)
16798 (save-excursion
16799 (outline-end-of-subtree) (outline-next-heading) (point))
16800 nil))
16802 (defun org-show-entry ()
16803 "Show the body directly following this heading.
16804 Show the heading too, if it is currently invisible."
16805 (interactive)
16806 (save-excursion
16807 (condition-case nil
16808 (progn
16809 (org-back-to-heading t)
16810 (outline-flag-region
16811 (max (point-min) (1- (point)))
16812 (save-excursion
16813 (if (re-search-forward
16814 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16815 (match-beginning 1)
16816 (point-max)))
16817 nil)
16818 (org-cycle-hide-drawers 'children))
16819 (error nil))))
16821 (defun org-make-options-regexp (kwds &optional extra)
16822 "Make a regular expression for keyword lines."
16823 (concat
16825 "#?[ \t]*\\+\\("
16826 (mapconcat 'regexp-quote kwds "\\|")
16827 (if extra (concat "\\|" extra))
16828 "\\):[ \t]*"
16829 "\\(.*\\)"))
16831 ;; Make isearch reveal the necessary context
16832 (defun org-isearch-end ()
16833 "Reveal context after isearch exits."
16834 (when isearch-success ; only if search was successful
16835 (if (featurep 'xemacs)
16836 ;; Under XEmacs, the hook is run in the correct place,
16837 ;; we directly show the context.
16838 (org-show-context 'isearch)
16839 ;; In Emacs the hook runs *before* restoring the overlays.
16840 ;; So we have to use a one-time post-command-hook to do this.
16841 ;; (Emacs 22 has a special variable, see function `org-mode')
16842 (unless (and (boundp 'isearch-mode-end-hook-quit)
16843 isearch-mode-end-hook-quit)
16844 ;; Only when the isearch was not quitted.
16845 (org-add-hook 'post-command-hook 'org-isearch-post-command
16846 'append 'local)))))
16848 (defun org-isearch-post-command ()
16849 "Remove self from hook, and show context."
16850 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16851 (org-show-context 'isearch))
16854 ;;;; Integration with and fixes for other packages
16856 ;;; Imenu support
16858 (defvar org-imenu-markers nil
16859 "All markers currently used by Imenu.")
16860 (make-variable-buffer-local 'org-imenu-markers)
16862 (defun org-imenu-new-marker (&optional pos)
16863 "Return a new marker for use by Imenu, and remember the marker."
16864 (let ((m (make-marker)))
16865 (move-marker m (or pos (point)))
16866 (push m org-imenu-markers)
16869 (defun org-imenu-get-tree ()
16870 "Produce the index for Imenu."
16871 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16872 (setq org-imenu-markers nil)
16873 (let* ((n org-imenu-depth)
16874 (re (concat "^" outline-regexp))
16875 (subs (make-vector (1+ n) nil))
16876 (last-level 0)
16877 m level head)
16878 (save-excursion
16879 (save-restriction
16880 (widen)
16881 (goto-char (point-max))
16882 (while (re-search-backward re nil t)
16883 (setq level (org-reduced-level (funcall outline-level)))
16884 (when (<= level n)
16885 (looking-at org-complex-heading-regexp)
16886 (setq head (org-link-display-format
16887 (org-match-string-no-properties 4))
16888 m (org-imenu-new-marker))
16889 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16890 (if (>= level last-level)
16891 (push (cons head m) (aref subs level))
16892 (push (cons head (aref subs (1+ level))) (aref subs level))
16893 (loop for i from (1+ level) to n do (aset subs i nil)))
16894 (setq last-level level)))))
16895 (aref subs 1)))
16897 (eval-after-load "imenu"
16898 '(progn
16899 (add-hook 'imenu-after-jump-hook
16900 (lambda ()
16901 (if (eq major-mode 'org-mode)
16902 (org-show-context 'org-goto))))))
16904 (defun org-link-display-format (link)
16905 "Replace a link with either the description, or the link target
16906 if no description is present"
16907 (save-match-data
16908 (if (string-match org-bracket-link-analytic-regexp link)
16909 (replace-match (or (match-string 5 link)
16910 (concat (match-string 1 link)
16911 (match-string 3 link)))
16912 nil nil link)
16913 link)))
16915 ;; Speedbar support
16917 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16918 "Overlay marking the agenda restriction line in speedbar.")
16919 (org-overlay-put org-speedbar-restriction-lock-overlay
16920 'face 'org-agenda-restriction-lock)
16921 (org-overlay-put org-speedbar-restriction-lock-overlay
16922 'help-echo "Agendas are currently limited to this item.")
16923 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16925 (defun org-speedbar-set-agenda-restriction ()
16926 "Restrict future agenda commands to the location at point in speedbar.
16927 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16928 (interactive)
16929 (require 'org-agenda)
16930 (let (p m tp np dir txt)
16931 (cond
16932 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16933 'org-imenu t))
16934 (setq m (get-text-property p 'org-imenu-marker))
16935 (save-excursion
16936 (save-restriction
16937 (set-buffer (marker-buffer m))
16938 (goto-char m)
16939 (org-agenda-set-restriction-lock 'subtree))))
16940 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16941 'speedbar-function 'speedbar-find-file))
16942 (setq tp (previous-single-property-change
16943 (1+ p) 'speedbar-function)
16944 np (next-single-property-change
16945 tp 'speedbar-function)
16946 dir (speedbar-line-directory)
16947 txt (buffer-substring-no-properties (or tp (point-min))
16948 (or np (point-max))))
16949 (save-excursion
16950 (save-restriction
16951 (set-buffer (find-file-noselect
16952 (let ((default-directory dir))
16953 (expand-file-name txt))))
16954 (unless (org-mode-p)
16955 (error "Cannot restrict to non-Org-mode file"))
16956 (org-agenda-set-restriction-lock 'file))))
16957 (t (error "Don't know how to restrict Org-mode's agenda")))
16958 (org-move-overlay org-speedbar-restriction-lock-overlay
16959 (point-at-bol) (point-at-eol))
16960 (setq current-prefix-arg nil)
16961 (org-agenda-maybe-redo)))
16963 (eval-after-load "speedbar"
16964 '(progn
16965 (speedbar-add-supported-extension ".org")
16966 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16967 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16968 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16969 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16970 (add-hook 'speedbar-visiting-tag-hook
16971 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16974 ;;; Fixes and Hacks for problems with other packages
16976 ;; Make flyspell not check words in links, to not mess up our keymap
16977 (defun org-mode-flyspell-verify ()
16978 "Don't let flyspell put overlays at active buttons."
16979 (and (not (get-text-property (point) 'keymap))
16980 (not (get-text-property (point) 'org-no-flyspell))))
16982 (defun org-remove-flyspell-overlays-in (beg end)
16983 "Remove flyspell overlays in region."
16984 (and (org-bound-and-true-p flyspell-mode)
16985 (fboundp 'flyspell-delete-region-overlays)
16986 (flyspell-delete-region-overlays beg end))
16987 (add-text-properties beg end '(org-no-flyspell t)))
16989 ;; Make `bookmark-jump' show the jump location if it was hidden.
16990 (eval-after-load "bookmark"
16991 '(if (boundp 'bookmark-after-jump-hook)
16992 ;; We can use the hook
16993 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16994 ;; Hook not available, use advice
16995 (defadvice bookmark-jump (after org-make-visible activate)
16996 "Make the position visible."
16997 (org-bookmark-jump-unhide))))
16999 ;; Make sure saveplace show the location if it was hidden
17000 (eval-after-load "saveplace"
17001 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17002 "Make the position visible."
17003 (org-bookmark-jump-unhide)))
17005 (defun org-bookmark-jump-unhide ()
17006 "Unhide the current position, to show the bookmark location."
17007 (and (org-mode-p)
17008 (or (org-invisible-p)
17009 (save-excursion (goto-char (max (point-min) (1- (point))))
17010 (org-invisible-p)))
17011 (org-show-context 'bookmark-jump)))
17013 ;; Make session.el ignore our circular variable
17014 (eval-after-load "session"
17015 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17017 ;;;; Experimental code
17019 (defun org-closed-in-range ()
17020 "Sparse tree of items closed in a certain time range.
17021 Still experimental, may disappear in the future."
17022 (interactive)
17023 ;; Get the time interval from the user.
17024 (let* ((time1 (time-to-seconds
17025 (org-read-date nil 'to-time nil "Starting date: ")))
17026 (time2 (time-to-seconds
17027 (org-read-date nil 'to-time nil "End date:")))
17028 ;; callback function
17029 (callback (lambda ()
17030 (let ((time
17031 (time-to-seconds
17032 (apply 'encode-time
17033 (org-parse-time-string
17034 (match-string 1))))))
17035 ;; check if time in interval
17036 (and (>= time time1) (<= time time2))))))
17037 ;; make tree, check each match with the callback
17038 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17040 ;;;; Finish up
17042 (provide 'org)
17044 (run-hooks 'org-load-hook)
17046 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17048 ;;; org.el ends here