Allow argument to `org-on-headling-p'
[org-mode.git] / lisp / org.el
blobfbdce0890d8a68d27c6e06ef718fcd9d6d8cf938
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.30trans
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.30trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let* ((version org-version)
106 (git-version)
107 (dir (concat (file-name-directory (locate-library "org")) "../" )))
108 (if (and (file-exists-p (expand-file-name ".git" dir))
109 (executable-find "git"))
110 (let ((pwd (substring (pwd) 10)))
111 (cd dir)
112 (if (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
113 (save-excursion
114 (set-buffer "*Shell Command Output*")
115 (goto-char (point-min))
116 (re-search-forward "[^\n]+")
117 (setq git-version (match-string 0))
118 (subst-char-in-string ?- ?. git-version t)
119 (shell-command "git diff-index --name-only HEAD --")
120 (unless (eql 1 (point-max))
121 (setq git-version (concat git-version ".dirty")))
122 (setq version (concat version " (" git-version ")")))
123 (cd pwd))))
124 (setq version (format "Org-mode version %s" version))
125 (if here (insert version))
126 (message version)
127 version))
129 ;;; Compatibility constants
131 ;;; The custom variables
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
140 (defcustom org-load-hook nil
141 "Hook that is run after org.el has been loaded."
142 :group 'org
143 :type 'hook)
145 (defvar org-modules) ; defined below
146 (defvar org-modules-loaded nil
147 "Have the modules been loaded already?")
149 (defun org-load-modules-maybe (&optional force)
150 "Load all extensions listed in `org-modules'."
151 (when (or force (not org-modules-loaded))
152 (mapc (lambda (ext)
153 (condition-case nil (require ext)
154 (error (message "Problems while trying to load feature `%s'" ext))))
155 org-modules)
156 (setq org-modules-loaded t)))
158 (defun org-set-modules (var value)
159 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
160 (set var value)
161 (when (featurep 'org)
162 (org-load-modules-maybe 'force)))
164 (when (org-bound-and-true-p org-modules)
165 (let ((a (member 'org-infojs org-modules)))
166 (and a (setcar a 'org-jsinfo))))
168 (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)
169 "Modules that should always be loaded together with org.el.
170 If a description starts with <C>, the file is not part of Emacs
171 and loading it will require that you have downloaded and properly installed
172 the org-mode distribution.
174 You can also use this system to load external packages (i.e. neither Org
175 core modules, nor modules from the CONTRIB directory). Just add symbols
176 to the end of the list. If the package is called org-xyz.el, then you need
177 to add the symbol `xyz', and the package must have a call to
179 (provide 'org-xyz)"
180 :group 'org
181 :set 'org-set-modules
182 :type
183 '(set :greedy t
184 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
185 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
186 (const :tag " crypt: Encryption of subtrees" org-crypt)
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\n\t\t\t(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\n\t\t\t(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\n\t\t\t(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\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
218 (const :tag "C invoice Help manage client invoices in OrgMode" org-invoice)
220 (const :tag "C jira Add a jira:ticket protocol to Org" org-jira)
221 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
222 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
223 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
224 (const :tag "C mtags: Support for muse-like tags" org-mtags)
225 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
226 (const :tag "C R: Computation using the R language" org-R)
227 (const :tag "C registry: A registry for Org links" org-registry)
228 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
229 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
230 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
231 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
232 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
233 (const :tag "C track: Keep up with Org development" org-track)
234 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
236 (defcustom org-support-shift-select nil
237 "Non-nil means, make shift-cursor commands select text when possible.
239 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
240 selecting a region, or enlarge thusly regions started in this way.
241 In Org-mode, in special contexts, these same keys are used for other
242 purposes, important enough to compete with shift selection. Org tries
243 to balance these needs by supporting `shift-select-mode' outside these
244 special contexts, under control of this variable.
246 The default of this variable is nil, to avoid confusing behavior. Shifted
247 cursor keys will then execute Org commands in the following contexts:
248 - on a headline, changing TODO state (left/right) and priority (up/down)
249 - on a time stamp, changing the time
250 - in a plain list item, changing the bullet type
251 - in a property definition line, switching between allowed values
252 - in the BEGIN line of a clock table (changing the time block).
253 Outside these contexts, the commands will throw an error.
255 When this variable is t and the cursor is not in a special context,
256 Org-mode will support shift-selection for making and enlarging regions.
257 To make this more effective, the bullet cycling will no longer happen
258 anywhere in an item line, but only if the cursor is exactly on the bullet.
260 If you set this variable to the symbol `always', then the keys
261 will not be special in headlines, property lines, and item lines, to make
262 shift selection work there as well. If this is what you want, you can
263 use the following alternative commands: `C-c C-t' and `C-c ,' to
264 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
265 TODO sets, `C-c -' to cycle item bullet types, and properties can be
266 edited by hand or in column view.
268 However, when the cursor is on a timestamp, shift-cursor commands
269 will still edit the time stamp - this is just too good to give up.
271 XEmacs user should have this variable set to nil, because shift-select-mode
272 is Emacs 23 only."
273 :group 'org
274 :type '(choice
275 (const :tag "Never" nil)
276 (const :tag "When outside special context" t)
277 (const :tag "Everywhere except timestamps" always)))
279 (defgroup org-startup nil
280 "Options concerning startup of Org-mode."
281 :tag "Org Startup"
282 :group 'org)
284 (defcustom org-startup-folded t
285 "Non-nil means, entering Org-mode will switch to OVERVIEW.
286 This can also be configured on a per-file basis by adding one of
287 the following lines anywhere in the buffer:
289 #+STARTUP: fold (or `overview', this is equivalent)
290 #+STARTUP: nofold (or `showall', this is equivalent)
291 #+STARTUP: content
292 #+STARTUP: showeverything"
293 :group 'org-startup
294 :type '(choice
295 (const :tag "nofold: show all" nil)
296 (const :tag "fold: overview" t)
297 (const :tag "content: all headlines" content)
298 (const :tag "show everything, even drawers" showeverything)))
300 (defcustom org-startup-truncated t
301 "Non-nil means, entering Org-mode will set `truncate-lines'.
302 This is useful since some lines containing links can be very long and
303 uninteresting. Also tables look terrible when wrapped."
304 :group 'org-startup
305 :type 'boolean)
307 (defcustom org-startup-indented nil
308 "Non-nil means, turn on `org-indent-mode' on startup.
309 This can also be configured on a per-file basis by adding one of
310 the following lines anywhere in the buffer:
312 #+STARTUP: indent
313 #+STARTUP: noindent"
314 :group 'org-structure
315 :type '(choice
316 (const :tag "Not" nil)
317 (const :tag "Globally (slow on startup in large files)" t)))
319 (defcustom org-startup-align-all-tables nil
320 "Non-nil means, align all tables when visiting a file.
321 This is useful when the column width in tables is forced with <N> cookies
322 in table fields. Such tables will look correct only after the first re-align.
323 This can also be configured on a per-file basis by adding one of
324 the following lines anywhere in the buffer:
325 #+STARTUP: align
326 #+STARTUP: noalign"
327 :group 'org-startup
328 :type 'boolean)
330 (defcustom org-insert-mode-line-in-empty-file nil
331 "Non-nil means insert the first line setting Org-mode in empty files.
332 When the function `org-mode' is called interactively in an empty file, this
333 normally means that the file name does not automatically trigger Org-mode.
334 To ensure that the file will always be in Org-mode in the future, a
335 line enforcing Org-mode will be inserted into the buffer, if this option
336 has been set."
337 :group 'org-startup
338 :type 'boolean)
340 (defcustom org-replace-disputed-keys nil
341 "Non-nil means use alternative key bindings for some keys.
342 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
343 These keys are also used by other packages like shift-selection-mode'
344 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
345 If you want to use Org-mode together with one of these other modes,
346 or more generally if you would like to move some Org-mode commands to
347 other keys, set this variable and configure the keys with the variable
348 `org-disputed-keys'.
350 This option is only relevant at load-time of Org-mode, and must be set
351 *before* org.el is loaded. Changing it requires a restart of Emacs to
352 become effective."
353 :group 'org-startup
354 :type 'boolean)
356 (defcustom org-use-extra-keys nil
357 "Non-nil means use extra key sequence definitions for certain
358 commands. This happens automatically if you run XEmacs or if
359 window-system is nil. This variable lets you do the same
360 manually. You must set it before loading org.
362 Example: on Carbon Emacs 22 running graphically, with an external
363 keyboard on a Powerbook, the default way of setting M-left might
364 not work for either Alt or ESC. Setting this variable will make
365 it work for ESC."
366 :group 'org-startup
367 :type 'boolean)
369 (if (fboundp 'defvaralias)
370 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
372 (defcustom org-disputed-keys
373 '(([(shift up)] . [(meta p)])
374 ([(shift down)] . [(meta n)])
375 ([(shift left)] . [(meta -)])
376 ([(shift right)] . [(meta +)])
377 ([(control shift right)] . [(meta shift +)])
378 ([(control shift left)] . [(meta shift -)]))
379 "Keys for which Org-mode and other modes compete.
380 This is an alist, cars are the default keys, second element specifies
381 the alternative to use when `org-replace-disputed-keys' is t.
383 Keys can be specified in any syntax supported by `define-key'.
384 The value of this option takes effect only at Org-mode's startup,
385 therefore you'll have to restart Emacs to apply it after changing."
386 :group 'org-startup
387 :type 'alist)
389 (defun org-key (key)
390 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
391 Or return the original if not disputed."
392 (if org-replace-disputed-keys
393 (let* ((nkey (key-description key))
394 (x (org-find-if (lambda (x)
395 (equal (key-description (car x)) nkey))
396 org-disputed-keys)))
397 (if x (cdr x) key))
398 key))
400 (defun org-find-if (predicate seq)
401 (catch 'exit
402 (while seq
403 (if (funcall predicate (car seq))
404 (throw 'exit (car seq))
405 (pop seq)))))
407 (defun org-defkey (keymap key def)
408 "Define a key, possibly translated, as returned by `org-key'."
409 (define-key keymap (org-key key) def))
411 (defcustom org-ellipsis nil
412 "The ellipsis to use in the Org-mode outline.
413 When nil, just use the standard three dots. When a string, use that instead,
414 When a face, use the standard 3 dots, but with the specified face.
415 The change affects only Org-mode (which will then use its own display table).
416 Changing this requires executing `M-x org-mode' in a buffer to become
417 effective."
418 :group 'org-startup
419 :type '(choice (const :tag "Default" nil)
420 (face :tag "Face" :value org-warning)
421 (string :tag "String" :value "...#")))
423 (defvar org-display-table nil
424 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
426 (defgroup org-keywords nil
427 "Keywords in Org-mode."
428 :tag "Org Keywords"
429 :group 'org)
431 (defcustom org-deadline-string "DEADLINE:"
432 "String to mark deadline entries.
433 A deadline is this string, followed by a time stamp. Should be a word,
434 terminated by a colon. You can insert a schedule keyword and
435 a timestamp with \\[org-deadline].
436 Changes become only effective after restarting Emacs."
437 :group 'org-keywords
438 :type 'string)
440 (defcustom org-scheduled-string "SCHEDULED:"
441 "String to mark scheduled TODO entries.
442 A schedule is this string, followed by a time stamp. Should be a word,
443 terminated by a colon. You can insert a schedule keyword and
444 a timestamp with \\[org-schedule].
445 Changes become only effective after restarting Emacs."
446 :group 'org-keywords
447 :type 'string)
449 (defcustom org-closed-string "CLOSED:"
450 "String used as the prefix for timestamps logging closing a TODO entry."
451 :group 'org-keywords
452 :type 'string)
454 (defcustom org-clock-string "CLOCK:"
455 "String used as prefix for timestamps clocking work hours on an item."
456 :group 'org-keywords
457 :type 'string)
459 (defcustom org-comment-string "COMMENT"
460 "Entries starting with this keyword will never be exported.
461 An entry can be toggled between COMMENT and normal with
462 \\[org-toggle-comment].
463 Changes become only effective after restarting Emacs."
464 :group 'org-keywords
465 :type 'string)
467 (defcustom org-quote-string "QUOTE"
468 "Entries starting with this keyword will be exported in fixed-width font.
469 Quoting applies only to the text in the entry following the headline, and does
470 not extend beyond the next headline, even if that is lower level.
471 An entry can be toggled between QUOTE and normal with
472 \\[org-toggle-fixed-width-section]."
473 :group 'org-keywords
474 :type 'string)
476 (defconst org-repeat-re
477 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
478 "Regular expression for specifying repeated events.
479 After a match, group 1 contains the repeat expression.")
481 (defgroup org-structure nil
482 "Options concerning the general structure of Org-mode files."
483 :tag "Org Structure"
484 :group 'org)
486 (defgroup org-reveal-location nil
487 "Options about how to make context of a location visible."
488 :tag "Org Reveal Location"
489 :group 'org-structure)
491 (defconst org-context-choice
492 '(choice
493 (const :tag "Always" t)
494 (const :tag "Never" nil)
495 (repeat :greedy t :tag "Individual contexts"
496 (cons
497 (choice :tag "Context"
498 (const agenda)
499 (const org-goto)
500 (const occur-tree)
501 (const tags-tree)
502 (const link-search)
503 (const mark-goto)
504 (const bookmark-jump)
505 (const isearch)
506 (const default))
507 (boolean))))
508 "Contexts for the reveal options.")
510 (defcustom org-show-hierarchy-above '((default . t))
511 "Non-nil means, show full hierarchy when revealing a location.
512 Org-mode often shows locations in an org-mode file which might have
513 been invisible before. When this is set, the hierarchy of headings
514 above the exposed location is shown.
515 Turning this off for example for sparse trees makes them very compact.
516 Instead of t, this can also be an alist specifying this option for different
517 contexts. Valid contexts are
518 agenda when exposing an entry from the agenda
519 org-goto when using the command `org-goto' on key C-c C-j
520 occur-tree when using the command `org-occur' on key C-c /
521 tags-tree when constructing a sparse tree based on tags matches
522 link-search when exposing search matches associated with a link
523 mark-goto when exposing the jump goal of a mark
524 bookmark-jump when exposing a bookmark location
525 isearch when exiting from an incremental search
526 default default for all contexts not set explicitly"
527 :group 'org-reveal-location
528 :type org-context-choice)
530 (defcustom org-show-following-heading '((default . nil))
531 "Non-nil means, show following heading when revealing a location.
532 Org-mode often shows locations in an org-mode file which might have
533 been invisible before. When this is set, the heading following the
534 match is shown.
535 Turning this off for example for sparse trees makes them very compact,
536 but makes it harder to edit the location of the match. In such a case,
537 use the command \\[org-reveal] to show more context.
538 Instead of t, this can also be an alist specifying this option for different
539 contexts. See `org-show-hierarchy-above' for valid contexts."
540 :group 'org-reveal-location
541 :type org-context-choice)
543 (defcustom org-show-siblings '((default . nil) (isearch t))
544 "Non-nil means, show all sibling heading when revealing a location.
545 Org-mode often shows locations in an org-mode file which might have
546 been invisible before. When this is set, the sibling of the current entry
547 heading are all made visible. If `org-show-hierarchy-above' is t,
548 the same happens on each level of the hierarchy above the current entry.
550 By default this is on for the isearch context, off for all other contexts.
551 Turning this off for example for sparse trees makes them very compact,
552 but makes it harder to edit the location of the match. In such a case,
553 use the command \\[org-reveal] to show more context.
554 Instead of t, this can also be an alist specifying this option for different
555 contexts. See `org-show-hierarchy-above' for valid contexts."
556 :group 'org-reveal-location
557 :type org-context-choice)
559 (defcustom org-show-entry-below '((default . nil))
560 "Non-nil means, show the entry below a headline when revealing a location.
561 Org-mode often shows locations in an org-mode file which might have
562 been invisible before. When this is set, the text below the headline that is
563 exposed is also shown.
565 By default this is off for all contexts.
566 Instead of t, this can also be an alist specifying this option for different
567 contexts. See `org-show-hierarchy-above' for valid contexts."
568 :group 'org-reveal-location
569 :type org-context-choice)
571 (defcustom org-indirect-buffer-display 'other-window
572 "How should indirect tree buffers be displayed?
573 This applies to indirect buffers created with the commands
574 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
575 Valid values are:
576 current-window Display in the current window
577 other-window Just display in another window.
578 dedicated-frame Create one new frame, and re-use it each time.
579 new-frame Make a new frame each time. Note that in this case
580 previously-made indirect buffers are kept, and you need to
581 kill these buffers yourself."
582 :group 'org-structure
583 :group 'org-agenda-windows
584 :type '(choice
585 (const :tag "In current window" current-window)
586 (const :tag "In current frame, other window" other-window)
587 (const :tag "Each time a new frame" new-frame)
588 (const :tag "One dedicated frame" dedicated-frame)))
590 (defgroup org-cycle nil
591 "Options concerning visibility cycling in Org-mode."
592 :tag "Org Cycle"
593 :group 'org-structure)
595 (defcustom org-cycle-skip-children-state-if-no-children t
596 "Non-nil means, skip CHILDREN state in entries that don't have any."
597 :group 'org-cycle
598 :type 'boolean)
600 (defcustom org-cycle-max-level nil
601 "Maximum level which should still be subject to visibility cycling.
602 Levels higher than this will, for cycling, be treated as text, not a headline.
603 When `org-odd-levels-only' is set, a value of N in this variable actually
604 means 2N-1 stars as the limiting headline.
605 When nil, cycle all levels.
606 Note that the limiting level of cycling is also influenced by
607 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
608 `org-inlinetask-min-level' is, cycling will be limited to levels one less
609 than its value."
610 :group 'org-cycle
611 :type '(choice
612 (const :tag "No limit" nil)
613 (integer :tag "Maximum level")))
615 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
616 "Names of drawers. Drawers are not opened by cycling on the headline above.
617 Drawers only open with a TAB on the drawer line itself. A drawer looks like
618 this:
619 :DRAWERNAME:
620 .....
621 :END:
622 The drawer \"PROPERTIES\" is special for capturing properties through
623 the property API.
625 Drawers can be defined on the per-file basis with a line like:
627 #+DRAWERS: HIDDEN STATE PROPERTIES"
628 :group 'org-structure
629 :group 'org-cycle
630 :type '(repeat (string :tag "Drawer Name")))
632 (defcustom org-hide-block-startup nil
633 "Non-nil means, , entering Org-mode will fold all blocks.
634 This can also be set in on a per-file basis with
636 #+STARTUP: hideblocks
637 #+STARTUP: showblocks"
638 :group 'org-startup
639 :group 'org-cycle
640 :type 'boolean)
642 (defcustom org-cycle-global-at-bob nil
643 "Cycle globally if cursor is at beginning of buffer and not at a headline.
644 This makes it possible to do global cycling without having to use S-TAB or
645 C-u TAB. For this special case to work, the first line of the buffer
646 must not be a headline - it may be empty or some other text. When used in
647 this way, `org-cycle-hook' is disables temporarily, to make sure the
648 cursor stays at the beginning of the buffer.
649 When this option is nil, don't do anything special at the beginning
650 of the buffer."
651 :group 'org-cycle
652 :type 'boolean)
654 (defcustom org-cycle-emulate-tab t
655 "Where should `org-cycle' emulate TAB.
656 nil Never
657 white Only in completely white lines
658 whitestart Only at the beginning of lines, before the first non-white char
659 t Everywhere except in headlines
660 exc-hl-bol Everywhere except at the start of a headline
661 If TAB is used in a place where it does not emulate TAB, the current subtree
662 visibility is cycled."
663 :group 'org-cycle
664 :type '(choice (const :tag "Never" nil)
665 (const :tag "Only in completely white lines" white)
666 (const :tag "Before first char in a line" whitestart)
667 (const :tag "Everywhere except in headlines" t)
668 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
671 (defcustom org-cycle-separator-lines 2
672 "Number of empty lines needed to keep an empty line between collapsed trees.
673 If you leave an empty line between the end of a subtree and the following
674 headline, this empty line is hidden when the subtree is folded.
675 Org-mode will leave (exactly) one empty line visible if the number of
676 empty lines is equal or larger to the number given in this variable.
677 So the default 2 means, at least 2 empty lines after the end of a subtree
678 are needed to produce free space between a collapsed subtree and the
679 following headline.
681 If the number is negative, and the number of empty lines is at least -N,
682 all empty lines are shown.
684 Special case: when 0, never leave empty lines in collapsed view."
685 :group 'org-cycle
686 :type 'integer)
687 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
689 (defcustom org-pre-cycle-hook nil
690 "Hook that is run before visibility cycling is happening.
691 The function(s) in this hook must accept a single argument which indicates
692 the new state that will be set right after running this hook. The
693 argument is a symbol. Before a global state change, it can have the values
694 `overview', `content', or `all'. Before a local state change, it can have
695 the values `folded', `children', or `subtree'."
696 :group 'org-cycle
697 :type 'hook)
699 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
700 org-cycle-hide-drawers
701 org-cycle-show-empty-lines
702 org-optimize-window-after-visibility-change)
703 "Hook that is run after `org-cycle' has changed the buffer visibility.
704 The function(s) in this hook must accept a single argument which indicates
705 the new state that was set by the most recent `org-cycle' command. The
706 argument is a symbol. After a global state change, it can have the values
707 `overview', `content', or `all'. After a local state change, it can have
708 the values `folded', `children', or `subtree'."
709 :group 'org-cycle
710 :type 'hook)
712 (defgroup org-edit-structure nil
713 "Options concerning structure editing in Org-mode."
714 :tag "Org Edit Structure"
715 :group 'org-structure)
717 (defcustom org-odd-levels-only nil
718 "Non-nil means, skip even levels and only use odd levels for the outline.
719 This has the effect that two stars are being added/taken away in
720 promotion/demotion commands. It also influences how levels are
721 handled by the exporters.
722 Changing it requires restart of `font-lock-mode' to become effective
723 for fontification also in regions already fontified.
724 You may also set this on a per-file basis by adding one of the following
725 lines to the buffer:
727 #+STARTUP: odd
728 #+STARTUP: oddeven"
729 :group 'org-edit-structure
730 :group 'org-font-lock
731 :type 'boolean)
733 (defcustom org-adapt-indentation t
734 "Non-nil means, adapt indentation to outline node level.
736 When this variable is set, Org assumes that you write outlines by
737 indenting text in each node to align with the headline (after the stars).
738 The following issues are influenced by this variable:
740 - When this is set and the *entire* text in an entry is indented, the
741 indentation is increased by one space in a demotion command, and
742 decreased by one in a promotion command. If any line in the entry
743 body starts with text at column 0, indentation is not changed at all.
745 - Property drawers and planning information is inserted indented when
746 this variable s set. When nil, they will not be indented.
748 - TAB indents a line relative to context. The lines below a headline
749 will be indented when this variable is set.
751 Note that this is all about true indentation, by adding and removing
752 space characters. See also `org-indent.el' which does level-dependent
753 indentation in a virtual way, i.e. at display time in Emacs."
754 :group 'org-edit-structure
755 :type 'boolean)
757 (defcustom org-special-ctrl-a/e nil
758 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
760 When t, `C-a' will bring back the cursor to the beginning of the
761 headline text, i.e. after the stars and after a possible TODO keyword.
762 In an item, this will be the position after the bullet.
763 When the cursor is already at that position, another `C-a' will bring
764 it to the beginning of the line.
766 `C-e' will jump to the end of the headline, ignoring the presence of tags
767 in the headline. A second `C-e' will then jump to the true end of the
768 line, after any tags.
770 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
771 going to the true line boundary first. Only a directly following, identical
772 keypress will bring the cursor to the special positions.
774 This may also be a cons cell where the behavior for `C-a' and `C-e' is
775 set separately."
776 :group 'org-edit-structure
777 :type '(choice
778 (const :tag "off" nil)
779 (const :tag "after stars/bullet and before tags first" t)
780 (const :tag "true line boundary first" reversed)
781 (cons :tag "Set C-a and C-e separately"
782 (choice :tag "Special C-a"
783 (const :tag "off" nil)
784 (const :tag "after stars/bullet first" t)
785 (const :tag "before stars/bullet first" reversed))
786 (choice :tag "Special C-e"
787 (const :tag "off" nil)
788 (const :tag "before tags first" t)
789 (const :tag "after tags first" reversed)))))
790 (if (fboundp 'defvaralias)
791 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
793 (defcustom org-special-ctrl-k nil
794 "Non-nil means `C-k' will behave specially in headlines.
795 When nil, `C-k' will call the default `kill-line' command.
796 When t, the following will happen while the cursor is in the headline:
798 - When the cursor is at the beginning of a headline, kill the entire
799 line and possible the folded subtree below the line.
800 - When in the middle of the headline text, kill the headline up to the tags.
801 - When after the headline text, kill the tags."
802 :group 'org-edit-structure
803 :type 'boolean)
805 (defcustom org-yank-folded-subtrees t
806 "Non-nil means, when yanking subtrees, fold them.
807 If the kill is a single subtree, or a sequence of subtrees, i.e. if
808 it starts with a heading and all other headings in it are either children
809 or siblings, then fold all the subtrees. However, do this only if no
810 text after the yank would be swallowed into a folded tree by this action."
811 :group 'org-edit-structure
812 :type 'boolean)
814 (defcustom org-yank-adjusted-subtrees nil
815 "Non-nil means, when yanking subtrees, adjust the level.
816 With this setting, `org-paste-subtree' is used to insert the subtree, see
817 this function for details."
818 :group 'org-edit-structure
819 :type 'boolean)
821 (defcustom org-M-RET-may-split-line '((default . t))
822 "Non-nil means, M-RET will split the line at the cursor position.
823 When nil, it will go to the end of the line before making a
824 new line.
825 You may also set this option in a different way for different
826 contexts. Valid contexts are:
828 headline when creating a new headline
829 item when creating a new item
830 table in a table field
831 default the value to be used for all contexts not explicitly
832 customized"
833 :group 'org-structure
834 :group 'org-table
835 :type '(choice
836 (const :tag "Always" t)
837 (const :tag "Never" nil)
838 (repeat :greedy t :tag "Individual contexts"
839 (cons
840 (choice :tag "Context"
841 (const headline)
842 (const item)
843 (const table)
844 (const default))
845 (boolean)))))
848 (defcustom org-insert-heading-respect-content nil
849 "Non-nil means, insert new headings after the current subtree.
850 When nil, the new heading is created directly after the current line.
851 The commands \\[org-insert-heading-respect-content] and
852 \\[org-insert-todo-heading-respect-content] turn this variable on
853 for the duration of the command."
854 :group 'org-structure
855 :type 'boolean)
857 (defcustom org-blank-before-new-entry '((heading . auto)
858 (plain-list-item . auto))
859 "Should `org-insert-heading' leave a blank line before new heading/item?
860 The value is an alist, with `heading' and `plain-list-item' as car,
861 and a boolean flag as cdr. For plain lists, if the variable
862 `org-empty-line-terminates-plain-lists' is set, the setting here
863 is ignored and no empty line is inserted, to keep the list in tact."
864 :group 'org-edit-structure
865 :type '(list
866 (cons (const heading)
867 (choice (const :tag "Never" nil)
868 (const :tag "Always" t)
869 (const :tag "Auto" auto)))
870 (cons (const plain-list-item)
871 (choice (const :tag "Never" nil)
872 (const :tag "Always" t)
873 (const :tag "Auto" auto)))))
875 (defcustom org-insert-heading-hook nil
876 "Hook being run after inserting a new heading."
877 :group 'org-edit-structure
878 :type 'hook)
880 (defcustom org-enable-fixed-width-editor t
881 "Non-nil means, lines starting with \":\" are treated as fixed-width.
882 This currently only means, they are never auto-wrapped.
883 When nil, such lines will be treated like ordinary lines.
884 See also the QUOTE keyword."
885 :group 'org-edit-structure
886 :type 'boolean)
889 (defcustom org-goto-auto-isearch t
890 "Non-nil means, typing characters in org-goto starts incremental search."
891 :group 'org-edit-structure
892 :type 'boolean)
894 (defgroup org-sparse-trees nil
895 "Options concerning sparse trees in Org-mode."
896 :tag "Org Sparse Trees"
897 :group 'org-structure)
899 (defcustom org-highlight-sparse-tree-matches t
900 "Non-nil means, highlight all matches that define a sparse tree.
901 The highlights will automatically disappear the next time the buffer is
902 changed by an edit command."
903 :group 'org-sparse-trees
904 :type 'boolean)
906 (defcustom org-remove-highlights-with-change t
907 "Non-nil means, any change to the buffer will remove temporary highlights.
908 Such highlights are created by `org-occur' and `org-clock-display'.
909 When nil, `C-c C-c needs to be used to get rid of the highlights.
910 The highlights created by `org-preview-latex-fragment' always need
911 `C-c C-c' to be removed."
912 :group 'org-sparse-trees
913 :group 'org-time
914 :type 'boolean)
917 (defcustom org-occur-hook '(org-first-headline-recenter)
918 "Hook that is run after `org-occur' has constructed a sparse tree.
919 This can be used to recenter the window to show as much of the structure
920 as possible."
921 :group 'org-sparse-trees
922 :type 'hook)
924 (defgroup org-imenu-and-speedbar nil
925 "Options concerning imenu and speedbar in Org-mode."
926 :tag "Org Imenu and Speedbar"
927 :group 'org-structure)
929 (defcustom org-imenu-depth 2
930 "The maximum level for Imenu access to Org-mode headlines.
931 This also applied for speedbar access."
932 :group 'org-imenu-and-speedbar
933 :type 'integer)
935 (defgroup org-table nil
936 "Options concerning tables in Org-mode."
937 :tag "Org Table"
938 :group 'org)
940 (defcustom org-enable-table-editor 'optimized
941 "Non-nil means, lines starting with \"|\" are handled by the table editor.
942 When nil, such lines will be treated like ordinary lines.
944 When equal to the symbol `optimized', the table editor will be optimized to
945 do the following:
946 - Automatic overwrite mode in front of whitespace in table fields.
947 This makes the structure of the table stay in tact as long as the edited
948 field does not exceed the column width.
949 - Minimize the number of realigns. Normally, the table is aligned each time
950 TAB or RET are pressed to move to another field. With optimization this
951 happens only if changes to a field might have changed the column width.
952 Optimization requires replacing the functions `self-insert-command',
953 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
954 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
955 very good at guessing when a re-align will be necessary, but you can always
956 force one with \\[org-ctrl-c-ctrl-c].
958 If you would like to use the optimized version in Org-mode, but the
959 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
961 This variable can be used to turn on and off the table editor during a session,
962 but in order to toggle optimization, a restart is required.
964 See also the variable `org-table-auto-blank-field'."
965 :group 'org-table
966 :type '(choice
967 (const :tag "off" nil)
968 (const :tag "on" t)
969 (const :tag "on, optimized" optimized)))
971 (defcustom org-self-insert-cluster-for-undo t
972 "Non-nil means cluster self-insert commands for undo when possible.
973 If this is set, then, like in the Emacs command loop, 20 consequtive
974 characters will be undone together.
975 This is configurable, because there is some impact on typing performance."
976 :group 'org-table
977 :type 'boolean)
979 (defcustom org-table-tab-recognizes-table.el t
980 "Non-nil means, TAB will automatically notice a table.el table.
981 When it sees such a table, it moves point into it and - if necessary -
982 calls `table-recognize-table'."
983 :group 'org-table-editing
984 :type 'boolean)
986 (defgroup org-link nil
987 "Options concerning links in Org-mode."
988 :tag "Org Link"
989 :group 'org)
991 (defvar org-link-abbrev-alist-local nil
992 "Buffer-local version of `org-link-abbrev-alist', which see.
993 The value of this is taken from the #+LINK lines.")
994 (make-variable-buffer-local 'org-link-abbrev-alist-local)
996 (defcustom org-link-abbrev-alist nil
997 "Alist of link abbreviations.
998 The car of each element is a string, to be replaced at the start of a link.
999 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1000 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1002 [[linkkey:tag][description]]
1004 The 'linkkey' must be a word word, starting with a letter, followed
1005 by letters, numbers, '-' or '_'.
1007 If REPLACE is a string, the tag will simply be appended to create the link.
1008 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1009 the placeholder \"%h\" will cause a url-encoded version of the tag to
1010 be inserted at that point (see the function `url-hexify-string').
1012 REPLACE may also be a function that will be called with the tag as the
1013 only argument to create the link, which should be returned as a string.
1015 See the manual for examples."
1016 :group 'org-link
1017 :type '(repeat
1018 (cons
1019 (string :tag "Protocol")
1020 (choice
1021 (string :tag "Format")
1022 (function)))))
1024 (defcustom org-descriptive-links t
1025 "Non-nil means, hide link part and only show description of bracket links.
1026 Bracket links are like [[link][description]]. This variable sets the initial
1027 state in new org-mode buffers. The setting can then be toggled on a
1028 per-buffer basis from the Org->Hyperlinks menu."
1029 :group 'org-link
1030 :type 'boolean)
1032 (defcustom org-link-file-path-type 'adaptive
1033 "How the path name in file links should be stored.
1034 Valid values are:
1036 relative Relative to the current directory, i.e. the directory of the file
1037 into which the link is being inserted.
1038 absolute Absolute path, if possible with ~ for home directory.
1039 noabbrev Absolute path, no abbreviation of home directory.
1040 adaptive Use relative path for files in the current directory and sub-
1041 directories of it. For other files, use an absolute path."
1042 :group 'org-link
1043 :type '(choice
1044 (const relative)
1045 (const absolute)
1046 (const noabbrev)
1047 (const adaptive)))
1049 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1050 "Types of links that should be activated in Org-mode files.
1051 This is a list of symbols, each leading to the activation of a certain link
1052 type. In principle, it does not hurt to turn on most link types - there may
1053 be a small gain when turning off unused link types. The types are:
1055 bracket The recommended [[link][description]] or [[link]] links with hiding.
1056 angular Links in angular brackets that may contain whitespace like
1057 <bbdb:Carsten Dominik>.
1058 plain Plain links in normal text, no whitespace, like http://google.com.
1059 radio Text that is matched by a radio target, see manual for details.
1060 tag Tag settings in a headline (link to tag search).
1061 date Time stamps (link to calendar).
1062 footnote Footnote labels.
1064 Changing this variable requires a restart of Emacs to become effective."
1065 :group 'org-link
1066 :type '(set :greedy t
1067 (const :tag "Double bracket links (new style)" bracket)
1068 (const :tag "Angular bracket links (old style)" angular)
1069 (const :tag "Plain text links" plain)
1070 (const :tag "Radio target matches" radio)
1071 (const :tag "Tags" tag)
1072 (const :tag "Timestamps" date)
1073 (const :tag "Footnotes" footnote)))
1075 (defcustom org-make-link-description-function nil
1076 "Function to use to generate link descriptions from links. If
1077 nil the link location will be used. This function must take two
1078 parameters; the first is the link and the second the description
1079 org-insert-link has generated, and should return the description
1080 to use."
1081 :group 'org-link
1082 :type 'function)
1084 (defgroup org-link-store nil
1085 "Options concerning storing links in Org-mode."
1086 :tag "Org Store Link"
1087 :group 'org-link)
1089 (defcustom org-email-link-description-format "Email %c: %.30s"
1090 "Format of the description part of a link to an email or usenet message.
1091 The following %-escapes will be replaced by corresponding information:
1093 %F full \"From\" field
1094 %f name, taken from \"From\" field, address if no name
1095 %T full \"To\" field
1096 %t first name in \"To\" field, address if no name
1097 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1098 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1099 %s subject
1100 %m message-id.
1102 You may use normal field width specification between the % and the letter.
1103 This is for example useful to limit the length of the subject.
1105 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1106 :group 'org-link-store
1107 :type 'string)
1109 (defcustom org-from-is-user-regexp
1110 (let (r1 r2)
1111 (when (and user-mail-address (not (string= user-mail-address "")))
1112 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1113 (when (and user-full-name (not (string= user-full-name "")))
1114 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1115 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1116 "Regexp matched against the \"From:\" header of an email or usenet message.
1117 It should match if the message is from the user him/herself."
1118 :group 'org-link-store
1119 :type 'regexp)
1121 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1122 "Non-nil means, storing a link to an Org file will use entry IDs.
1124 Note that before this variable is even considered, org-id must be loaded,
1125 so please customize `org-modules' and turn it on.
1127 The variable can have the following values:
1129 t Create an ID if needed to make a link to the current entry.
1131 create-if-interactive
1132 If `org-store-link' is called directly (interactively, as a user
1133 command), do create an ID to support the link. But when doing the
1134 job for remember, only use the ID if it already exists. The
1135 purpose of this setting is to avoid proliferation of unwanted
1136 IDs, just because you happen to be in an Org file when you
1137 call `org-remember' that automatically and preemptively
1138 creates a link. If you do want to get an ID link in a remember
1139 template to an entry not having an ID, create it first by
1140 explicitly creating a link to it, using `C-c C-l' first.
1142 create-if-interactive-and-no-custom-id
1143 Like create-if-interactive, but do not create an ID if there is
1144 a CUSTOM_ID property defined in the entry. This is the default.
1146 use-existing
1147 Use existing ID, do not create one.
1149 nil Never use an ID to make a link, instead link using a text search for
1150 the headline text."
1151 :group 'org-link-store
1152 :type '(choice
1153 (const :tag "Create ID to make link" t)
1154 (const :tag "Create if storing link interactively"
1155 create-if-interactive)
1156 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1157 create-if-interactive-and-no-custom-id)
1158 (const :tag "Only use existing" use-existing)
1159 (const :tag "Do not use ID to create link" nil)))
1161 (defcustom org-context-in-file-links t
1162 "Non-nil means, file links from `org-store-link' contain context.
1163 A search string will be added to the file name with :: as separator and
1164 used to find the context when the link is activated by the command
1165 `org-open-at-point'.
1166 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1167 negates this setting for the duration of the command."
1168 :group 'org-link-store
1169 :type 'boolean)
1171 (defcustom org-keep-stored-link-after-insertion nil
1172 "Non-nil means, keep link in list for entire session.
1174 The command `org-store-link' adds a link pointing to the current
1175 location to an internal list. These links accumulate during a session.
1176 The command `org-insert-link' can be used to insert links into any
1177 Org-mode file (offering completion for all stored links). When this
1178 option is nil, every link which has been inserted once using \\[org-insert-link]
1179 will be removed from the list, to make completing the unused links
1180 more efficient."
1181 :group 'org-link-store
1182 :type 'boolean)
1184 (defgroup org-link-follow nil
1185 "Options concerning following links in Org-mode."
1186 :tag "Org Follow Link"
1187 :group 'org-link)
1189 (defcustom org-link-translation-function nil
1190 "Function to translate links with different syntax to Org syntax.
1191 This can be used to translate links created for example by the Planner
1192 or emacs-wiki packages to Org syntax.
1193 The function must accept two parameters, a TYPE containing the link
1194 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1195 which is everything after the link protocol. It should return a cons
1196 with possibly modified values of type and path.
1197 Org contains a function for this, so if you set this variable to
1198 `org-translate-link-from-planner', you should be able follow many
1199 links created by planner."
1200 :group 'org-link-follow
1201 :type 'function)
1203 (defcustom org-follow-link-hook nil
1204 "Hook that is run after a link has been followed."
1205 :group 'org-link-follow
1206 :type 'hook)
1208 (defcustom org-tab-follows-link nil
1209 "Non-nil means, on links TAB will follow the link.
1210 Needs to be set before org.el is loaded.
1211 This really should not be used, it does not make sense, and the
1212 implementation is bad."
1213 :group 'org-link-follow
1214 :type 'boolean)
1216 (defcustom org-return-follows-link nil
1217 "Non-nil means, on links RET will follow the link.
1218 Needs to be set before org.el is loaded."
1219 :group 'org-link-follow
1220 :type 'boolean)
1222 (defcustom org-mouse-1-follows-link
1223 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1224 "Non-nil means, mouse-1 on a link will follow the link.
1225 A longer mouse click will still set point. Does not work on XEmacs.
1226 Needs to be set before org.el is loaded."
1227 :group 'org-link-follow
1228 :type 'boolean)
1230 (defcustom org-mark-ring-length 4
1231 "Number of different positions to be recorded in the ring
1232 Changing this requires a restart of Emacs to work correctly."
1233 :group 'org-link-follow
1234 :type 'integer)
1236 (defcustom org-link-frame-setup
1237 '((vm . vm-visit-folder-other-frame)
1238 (gnus . gnus-other-frame)
1239 (file . find-file-other-window))
1240 "Setup the frame configuration for following links.
1241 When following a link with Emacs, it may often be useful to display
1242 this link in another window or frame. This variable can be used to
1243 set this up for the different types of links.
1244 For VM, use any of
1245 `vm-visit-folder'
1246 `vm-visit-folder-other-frame'
1247 For Gnus, use any of
1248 `gnus'
1249 `gnus-other-frame'
1250 `org-gnus-no-new-news'
1251 For FILE, use any of
1252 `find-file'
1253 `find-file-other-window'
1254 `find-file-other-frame'
1255 For the calendar, use the variable `calendar-setup'.
1256 For BBDB, it is currently only possible to display the matches in
1257 another window."
1258 :group 'org-link-follow
1259 :type '(list
1260 (cons (const vm)
1261 (choice
1262 (const vm-visit-folder)
1263 (const vm-visit-folder-other-window)
1264 (const vm-visit-folder-other-frame)))
1265 (cons (const gnus)
1266 (choice
1267 (const gnus)
1268 (const gnus-other-frame)
1269 (const org-gnus-no-new-news)))
1270 (cons (const file)
1271 (choice
1272 (const find-file)
1273 (const find-file-other-window)
1274 (const find-file-other-frame)))))
1276 (defcustom org-display-internal-link-with-indirect-buffer nil
1277 "Non-nil means, use indirect buffer to display infile links.
1278 Activating internal links (from one location in a file to another location
1279 in the same file) normally just jumps to the location. When the link is
1280 activated with a C-u prefix (or with mouse-3), the link is displayed in
1281 another window. When this option is set, the other window actually displays
1282 an indirect buffer clone of the current buffer, to avoid any visibility
1283 changes to the current buffer."
1284 :group 'org-link-follow
1285 :type 'boolean)
1287 (defcustom org-open-non-existing-files nil
1288 "Non-nil means, `org-open-file' will open non-existing files.
1289 When nil, an error will be generated.
1290 This variable applies only to external applications because they
1291 might choke on non-existing files. If the link is to a file that
1292 will be openend in Emacs, the variable is ignored."
1293 :group 'org-link-follow
1294 :type 'boolean)
1296 (defcustom org-open-directory-means-index-dot-org nil
1297 "Non-nil means, a link to a directory really means to index.org.
1298 When nil, following a directory link will run dired or open a finder/explorer
1299 window on that directory."
1300 :group 'org-link-follow
1301 :type 'boolean)
1303 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1304 "Function and arguments to call for following mailto links.
1305 This is a list with the first element being a lisp function, and the
1306 remaining elements being arguments to the function. In string arguments,
1307 %a will be replaced by the address, and %s will be replaced by the subject
1308 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1309 :group 'org-link-follow
1310 :type '(choice
1311 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1312 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1313 (const :tag "message-mail" (message-mail "%a" "%s"))
1314 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1316 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1317 "Non-nil means, ask for confirmation before executing shell links.
1318 Shell links can be dangerous: just think about a link
1320 [[shell:rm -rf ~/*][Google Search]]
1322 This link would show up in your Org-mode document as \"Google Search\",
1323 but really it would remove your entire home directory.
1324 Therefore we advise against setting this variable to nil.
1325 Just change it to `y-or-n-p' if you want to confirm with a
1326 single keystroke rather than having to type \"yes\"."
1327 :group 'org-link-follow
1328 :type '(choice
1329 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1330 (const :tag "with y-or-n (faster)" y-or-n-p)
1331 (const :tag "no confirmation (dangerous)" nil)))
1333 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1334 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1335 Elisp links can be dangerous: just think about a link
1337 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1339 This link would show up in your Org-mode document as \"Google Search\",
1340 but really it would remove your entire home directory.
1341 Therefore we advise against setting this variable to nil.
1342 Just change it to `y-or-n-p' if you want to confirm with a
1343 single keystroke rather than having to type \"yes\"."
1344 :group 'org-link-follow
1345 :type '(choice
1346 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1347 (const :tag "with y-or-n (faster)" y-or-n-p)
1348 (const :tag "no confirmation (dangerous)" nil)))
1350 (defconst org-file-apps-defaults-gnu
1351 '((remote . emacs)
1352 (system . mailcap)
1353 (t . mailcap))
1354 "Default file applications on a UNIX or GNU/Linux system.
1355 See `org-file-apps'.")
1357 (defconst org-file-apps-defaults-macosx
1358 '((remote . emacs)
1359 (t . "open %s")
1360 (system . "open %s")
1361 ("ps.gz" . "gv %s")
1362 ("eps.gz" . "gv %s")
1363 ("dvi" . "xdvi %s")
1364 ("fig" . "xfig %s"))
1365 "Default file applications on a MacOS X system.
1366 The system \"open\" is known as a default, but we use X11 applications
1367 for some files for which the OS does not have a good default.
1368 See `org-file-apps'.")
1370 (defconst org-file-apps-defaults-windowsnt
1371 (list
1372 '(remote . emacs)
1373 (cons t
1374 (list (if (featurep 'xemacs)
1375 'mswindows-shell-execute
1376 'w32-shell-execute)
1377 "open" 'file))
1378 (cons 'system
1379 (list (if (featurep 'xemacs)
1380 'mswindows-shell-execute
1381 'w32-shell-execute)
1382 "open" 'file)))
1383 "Default file applications on a Windows NT system.
1384 The system \"open\" is used for most files.
1385 See `org-file-apps'.")
1387 (defcustom org-file-apps
1389 (auto-mode . emacs)
1390 ("\\.x?html?\\'" . default)
1391 ("\\.pdf\\'" . default)
1393 "External applications for opening `file:path' items in a document.
1394 Org-mode uses system defaults for different file types, but
1395 you can use this variable to set the application for a given file
1396 extension. The entries in this list are cons cells where the car identifies
1397 files and the cdr the corresponding command. Possible values for the
1398 file identifier are
1399 \"regex\" Regular expression matched against the file name. For backward
1400 compatibility, this can also be a string with only alphanumeric
1401 characters, which is then interpreted as an extension.
1402 `directory' Matches a directory
1403 `remote' Matches a remote file, accessible through tramp or efs.
1404 Remote files most likely should be visited through Emacs
1405 because external applications cannot handle such paths.
1406 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1407 so all files Emacs knows how to handle. Using this with
1408 command `emacs' will open most files in Emacs. Beware that this
1409 will also open html files inside Emacs, unless you add
1410 (\"html\" . default) to the list as well.
1411 t Default for files not matched by any of the other options.
1412 `system' The system command to open files, like `open' on Windows
1413 and Mac OS X, and mailcap under GNU/Linux. This is the command
1414 that will be selected if you call `C-c C-o' with a double
1415 `C-u C-u' prefix.
1417 Possible values for the command are:
1418 `emacs' The file will be visited by the current Emacs process.
1419 `default' Use the default application for this file type, which is the
1420 association for t in the list, most likely in the system-specific
1421 part.
1422 This can be used to overrule an unwanted setting in the
1423 system-specific variable.
1424 `system' Use the system command for opening files, like \"open\".
1425 This command is specified by the entry whose car is `system'.
1426 Most likely, the system-specific version of this variable
1427 does define this command, but you can overrule/replace it
1428 here.
1429 string A command to be executed by a shell; %s will be replaced
1430 by the path to the file.
1431 sexp A Lisp form which will be evaluated. The file path will
1432 be available in the Lisp variable `file'.
1433 For more examples, see the system specific constants
1434 `org-file-apps-defaults-macosx'
1435 `org-file-apps-defaults-windowsnt'
1436 `org-file-apps-defaults-gnu'."
1437 :group 'org-link-follow
1438 :type '(repeat
1439 (cons (choice :value ""
1440 (string :tag "Extension")
1441 (const :tag "System command to open files" system)
1442 (const :tag "Default for unrecognized files" t)
1443 (const :tag "Remote file" remote)
1444 (const :tag "Links to a directory" directory)
1445 (const :tag "Any files that have Emacs modes"
1446 auto-mode))
1447 (choice :value ""
1448 (const :tag "Visit with Emacs" emacs)
1449 (const :tag "Use default" default)
1450 (const :tag "Use the system command" system)
1451 (string :tag "Command")
1452 (sexp :tag "Lisp form")))))
1454 (defgroup org-refile nil
1455 "Options concerning refiling entries in Org-mode."
1456 :tag "Org Refile"
1457 :group 'org)
1459 (defcustom org-directory "~/org"
1460 "Directory with org files.
1461 This is just a default location to look for Org files. There is no need
1462 at all to put your files into this directory. It is only used in the
1463 following situations:
1465 1. When a remember template specifies a target file that is not an
1466 absolute path. The path will then be interpreted relative to
1467 `org-directory'
1468 2. When a remember note is filed away in an interactive way (when exiting the
1469 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1470 with `org-directory' as the default path."
1471 :group 'org-refile
1472 :group 'org-remember
1473 :type 'directory)
1475 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1476 "Default target for storing notes.
1477 Used by the hooks for remember.el. This can be a string, or nil to mean
1478 the value of `remember-data-file'.
1479 You can set this on a per-template basis with the variable
1480 `org-remember-templates'."
1481 :group 'org-refile
1482 :group 'org-remember
1483 :type '(choice
1484 (const :tag "Default from remember-data-file" nil)
1485 file))
1487 (defcustom org-goto-interface 'outline
1488 "The default interface to be used for `org-goto'.
1489 Allowed values are:
1490 outline The interface shows an outline of the relevant file
1491 and the correct heading is found by moving through
1492 the outline or by searching with incremental search.
1493 outline-path-completion Headlines in the current buffer are offered via
1494 completion. This is the interface also used by
1495 the refile command."
1496 :group 'org-refile
1497 :type '(choice
1498 (const :tag "Outline" outline)
1499 (const :tag "Outline-path-completion" outline-path-completion)))
1501 (defcustom org-goto-max-level 5
1502 "Maximum level to be considered when running org-goto with refile interface."
1503 :group 'org-refile
1504 :type 'integer)
1506 (defcustom org-reverse-note-order nil
1507 "Non-nil means, store new notes at the beginning of a file or entry.
1508 When nil, new notes will be filed to the end of a file or entry.
1509 This can also be a list with cons cells of regular expressions that
1510 are matched against file names, and values."
1511 :group 'org-remember
1512 :group 'org-refile
1513 :type '(choice
1514 (const :tag "Reverse always" t)
1515 (const :tag "Reverse never" nil)
1516 (repeat :tag "By file name regexp"
1517 (cons regexp boolean))))
1519 (defcustom org-refile-targets nil
1520 "Targets for refiling entries with \\[org-refile].
1521 This is list of cons cells. Each cell contains:
1522 - a specification of the files to be considered, either a list of files,
1523 or a symbol whose function or variable value will be used to retrieve
1524 a file name or a list of file names. If you use `org-agenda-files' for
1525 that, all agenda files will be scanned for targets. Nil means, consider
1526 headings in the current buffer.
1527 - A specification of how to find candidate refile targets. This may be
1528 any of:
1529 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1530 This tag has to be present in all target headlines, inheritance will
1531 not be considered.
1532 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1533 todo keyword.
1534 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1535 headlines that are refiling targets.
1536 - a cons cell (:level . N). Any headline of level N is considered a target.
1537 Note that, when `org-odd-levels-only' is set, level corresponds to
1538 order in hierarchy, not to the number of stars.
1539 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1540 Note that, when `org-odd-levels-only' is set, level corresponds to
1541 order in hierarchy, not to the number of stars.
1543 You can set the variable `org-refile-target-verify-function' to a function
1544 to verify each headline found by the simple critery above.
1546 When this variable is nil, all top-level headlines in the current buffer
1547 are used, equivalent to the value `((nil . (:level . 1))'."
1548 :group 'org-refile
1549 :type '(repeat
1550 (cons
1551 (choice :value org-agenda-files
1552 (const :tag "All agenda files" org-agenda-files)
1553 (const :tag "Current buffer" nil)
1554 (function) (variable) (file))
1555 (choice :tag "Identify target headline by"
1556 (cons :tag "Specific tag" (const :value :tag) (string))
1557 (cons :tag "TODO keyword" (const :value :todo) (string))
1558 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1559 (cons :tag "Level number" (const :value :level) (integer))
1560 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1562 (defcustom org-refile-target-verify-function nil
1563 "Function to verify if the headline at point should be a refile target.
1564 The function will be called without arguments, with point at the
1565 beginning of the headline. It should return t and leave point
1566 where it is if the headline is a valid target for refiling.
1568 If the target should not be selected, the function must return nil.
1569 In addition to this, it may move point to a place from where the search
1570 should be continued. For example, the function may decide that the entire
1571 subtree of the current entry should be excluded and move point to the end
1572 of the subtree."
1573 :group 'org-refile
1574 :type 'function)
1576 (defcustom org-refile-use-outline-path nil
1577 "Non-nil means, provide refile targets as paths.
1578 So a level 3 headline will be available as level1/level2/level3.
1580 When the value is `file', also include the file name (without directory)
1581 into the path. In this case, you can also stop the completion after
1582 the file name, to get entries inserted as top level in the file.
1584 When `full-file-path', include the full file path."
1585 :group 'org-refile
1586 :type '(choice
1587 (const :tag "Not" nil)
1588 (const :tag "Yes" t)
1589 (const :tag "Start with file name" file)
1590 (const :tag "Start with full file path" full-file-path)))
1592 (defcustom org-outline-path-complete-in-steps t
1593 "Non-nil means, complete the outline path in hierarchical steps.
1594 When Org-mode uses the refile interface to select an outline path
1595 \(see variable `org-refile-use-outline-path'), the completion of
1596 the path can be done is a single go, or if can be done in steps down
1597 the headline hierarchy. Going in steps is probably the best if you
1598 do not use a special completion package like `ido' or `icicles'.
1599 However, when using these packages, going in one step can be very
1600 fast, while still showing the whole path to the entry."
1601 :group 'org-refile
1602 :type 'boolean)
1604 (defcustom org-refile-allow-creating-parent-nodes nil
1605 "Non-nil means, allow to create new nodes as refile targets.
1606 New nodes are then created by adding \"/new node name\" to the completion
1607 of an existing node. When the value of this variable is `confirm',
1608 new node creation must be confirmed by the user (recommended)
1609 When nil, the completion must match an existing entry.
1611 Note that, if the new heading is not seen by the criteria
1612 listed in `org-refile-targets', multiple instances of the same
1613 heading would be created by trying again to file under the new
1614 heading."
1615 :group 'org-refile
1616 :type '(choice
1617 (const :tag "Never" nil)
1618 (const :tag "Always" t)
1619 (const :tag "Prompt for confirmation" confirm)))
1621 (defgroup org-todo nil
1622 "Options concerning TODO items in Org-mode."
1623 :tag "Org TODO"
1624 :group 'org)
1626 (defgroup org-progress nil
1627 "Options concerning Progress logging in Org-mode."
1628 :tag "Org Progress"
1629 :group 'org-time)
1631 (defvar org-todo-interpretation-widgets
1633 (:tag "Sequence (cycling hits every state)" sequence)
1634 (:tag "Type (cycling directly to DONE)" type))
1635 "The available interpretation symbols for customizing
1636 `org-todo-keywords'.
1637 Interested libraries should add to this list.")
1639 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1640 "List of TODO entry keyword sequences and their interpretation.
1641 \\<org-mode-map>This is a list of sequences.
1643 Each sequence starts with a symbol, either `sequence' or `type',
1644 indicating if the keywords should be interpreted as a sequence of
1645 action steps, or as different types of TODO items. The first
1646 keywords are states requiring action - these states will select a headline
1647 for inclusion into the global TODO list Org-mode produces. If one of
1648 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1649 signify that no further action is necessary. If \"|\" is not found,
1650 the last keyword is treated as the only DONE state of the sequence.
1652 The command \\[org-todo] cycles an entry through these states, and one
1653 additional state where no keyword is present. For details about this
1654 cycling, see the manual.
1656 TODO keywords and interpretation can also be set on a per-file basis with
1657 the special #+SEQ_TODO and #+TYP_TODO lines.
1659 Each keyword can optionally specify a character for fast state selection
1660 \(in combination with the variable `org-use-fast-todo-selection')
1661 and specifiers for state change logging, using the same syntax
1662 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1663 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1664 indicates to record a time stamp each time this state is selected.
1666 Each keyword may also specify if a timestamp or a note should be
1667 recorded when entering or leaving the state, by adding additional
1668 characters in the parenthesis after the keyword. This looks like this:
1669 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1670 record only the time of the state change. With X and Y being either
1671 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1672 Y when leaving the state if and only if the *target* state does not
1673 define X. You may omit any of the fast-selection key or X or /Y,
1674 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1676 For backward compatibility, this variable may also be just a list
1677 of keywords - in this case the interpretation (sequence or type) will be
1678 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1679 :group 'org-todo
1680 :group 'org-keywords
1681 :type '(choice
1682 (repeat :tag "Old syntax, just keywords"
1683 (string :tag "Keyword"))
1684 (repeat :tag "New syntax"
1685 (cons
1686 (choice
1687 :tag "Interpretation"
1688 ;;Quick and dirty way to see
1689 ;;`org-todo-interpretations'. This takes the
1690 ;;place of item arguments
1691 :convert-widget
1692 (lambda (widget)
1693 (widget-put widget
1694 :args (mapcar
1695 #'(lambda (x)
1696 (widget-convert
1697 (cons 'const x)))
1698 org-todo-interpretation-widgets))
1699 widget))
1700 (repeat
1701 (string :tag "Keyword"))))))
1703 (defvar org-todo-keywords-1 nil
1704 "All TODO and DONE keywords active in a buffer.")
1705 (make-variable-buffer-local 'org-todo-keywords-1)
1706 (defvar org-todo-keywords-for-agenda nil)
1707 (defvar org-done-keywords-for-agenda nil)
1708 (defvar org-todo-keyword-alist-for-agenda nil)
1709 (defvar org-tag-alist-for-agenda nil)
1710 (defvar org-agenda-contributing-files nil)
1711 (defvar org-not-done-keywords nil)
1712 (make-variable-buffer-local 'org-not-done-keywords)
1713 (defvar org-done-keywords nil)
1714 (make-variable-buffer-local 'org-done-keywords)
1715 (defvar org-todo-heads nil)
1716 (make-variable-buffer-local 'org-todo-heads)
1717 (defvar org-todo-sets nil)
1718 (make-variable-buffer-local 'org-todo-sets)
1719 (defvar org-todo-log-states nil)
1720 (make-variable-buffer-local 'org-todo-log-states)
1721 (defvar org-todo-kwd-alist nil)
1722 (make-variable-buffer-local 'org-todo-kwd-alist)
1723 (defvar org-todo-key-alist nil)
1724 (make-variable-buffer-local 'org-todo-key-alist)
1725 (defvar org-todo-key-trigger nil)
1726 (make-variable-buffer-local 'org-todo-key-trigger)
1728 (defcustom org-todo-interpretation 'sequence
1729 "Controls how TODO keywords are interpreted.
1730 This variable is in principle obsolete and is only used for
1731 backward compatibility, if the interpretation of todo keywords is
1732 not given already in `org-todo-keywords'. See that variable for
1733 more information."
1734 :group 'org-todo
1735 :group 'org-keywords
1736 :type '(choice (const sequence)
1737 (const type)))
1739 (defcustom org-use-fast-todo-selection t
1740 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1741 This variable describes if and under what circumstances the cycling
1742 mechanism for TODO keywords will be replaced by a single-key, direct
1743 selection scheme.
1745 When nil, fast selection is never used.
1747 When the symbol `prefix', it will be used when `org-todo' is called with
1748 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1749 in an agenda buffer.
1751 When t, fast selection is used by default. In this case, the prefix
1752 argument forces cycling instead.
1754 In all cases, the special interface is only used if access keys have actually
1755 been assigned by the user, i.e. if keywords in the configuration are followed
1756 by a letter in parenthesis, like TODO(t)."
1757 :group 'org-todo
1758 :type '(choice
1759 (const :tag "Never" nil)
1760 (const :tag "By default" t)
1761 (const :tag "Only with C-u C-c C-t" prefix)))
1763 (defcustom org-provide-todo-statistics t
1764 "Non-nil means, update todo statistics after insert and toggle.
1765 ALL-HEADLINES means update todo statistics by including headlines
1766 with no TODO keyword as well, counting them as not done.
1767 A list of TODO keywords means the same, but skip keywords that are
1768 not in this list.
1770 When this is set, todo statistics is updated in the parent of the
1771 current entry each time a todo state is changed."
1772 :group 'org-todo
1773 :type '(choice
1774 (const :tag "Yes, only for TODO entries" t)
1775 (const :tag "Yes, including all entries" 'all-headlines)
1776 (repeat :tag "Yes, for TODOs in this list"
1777 (string :tag "TODO keyword"))
1778 (other :tag "No TODO statistics" nil)))
1780 (defcustom org-hierarchical-todo-statistics t
1781 "Non-nil means, TODO statistics covers just direct children.
1782 When nil, all entries in the subtree are considered.
1783 This has only an effect if `org-provide-todo-statistics' is set.
1784 To set this to nil for only a single subtree, use a COOKIE_DATA
1785 property and include the word \"recursive\" into the value."
1786 :group 'org-todo
1787 :type 'boolean)
1789 (defcustom org-after-todo-state-change-hook nil
1790 "Hook which is run after the state of a TODO item was changed.
1791 The new state (a string with a TODO keyword, or nil) is available in the
1792 Lisp variable `state'."
1793 :group 'org-todo
1794 :type 'hook)
1796 (defvar org-blocker-hook nil
1797 "Hook for functions that are allowed to block a state change.
1799 Each function gets as its single argument a property list, see
1800 `org-trigger-hook' for more information about this list.
1802 If any of the functions in this hook returns nil, the state change
1803 is blocked.")
1805 (defvar org-trigger-hook nil
1806 "Hook for functions that are triggered by a state change.
1808 Each function gets as its single argument a property list with at least
1809 the following elements:
1811 (:type type-of-change :position pos-at-entry-start
1812 :from old-state :to new-state)
1814 Depending on the type, more properties may be present.
1816 This mechanism is currently implemented for:
1818 TODO state changes
1819 ------------------
1820 :type todo-state-change
1821 :from previous state (keyword as a string), or nil, or a symbol
1822 'todo' or 'done', to indicate the general type of state.
1823 :to new state, like in :from")
1825 (defcustom org-enforce-todo-dependencies nil
1826 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1827 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1828 be blocked if any prior sibling is not yet done.
1829 Finally, if the parent is blocked because of ordered siblings of its own,
1830 the child will also be blocked.
1831 This variable needs to be set before org.el is loaded, and you need to
1832 restart Emacs after a change to make the change effective. The only way
1833 to change is while Emacs is running is through the customize interface."
1834 :set (lambda (var val)
1835 (set var val)
1836 (if val
1837 (add-hook 'org-blocker-hook
1838 'org-block-todo-from-children-or-siblings-or-parent)
1839 (remove-hook 'org-blocker-hook
1840 'org-block-todo-from-children-or-siblings-or-parent)))
1841 :group 'org-todo
1842 :type 'boolean)
1844 (defcustom org-enforce-todo-checkbox-dependencies nil
1845 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1846 When this is nil, checkboxes have no influence on switching TODO states.
1847 When non-nil, you first need to check off all check boxes before the TODO
1848 entry can be switched to DONE.
1849 This variable needs to be set before org.el is loaded, and you need to
1850 restart Emacs after a change to make the change effective. The only way
1851 to change is while Emacs is running is through the customize interface."
1852 :set (lambda (var val)
1853 (set var val)
1854 (if val
1855 (add-hook 'org-blocker-hook
1856 'org-block-todo-from-checkboxes)
1857 (remove-hook 'org-blocker-hook
1858 'org-block-todo-from-checkboxes)))
1859 :group 'org-todo
1860 :type 'boolean)
1862 (defcustom org-treat-insert-todo-heading-as-state-change nil
1863 "Non-nil means, inserting a TODO heading is treated as state change.
1864 So when the command \\[org-insert-todo-heading] is used, state change
1865 logging will apply if appropriate. When nil, the new TODO item will
1866 be inserted directly, and no logging will take place."
1867 :group 'org-todo
1868 :type 'boolean)
1870 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1871 "Non-nil means, switching TODO states with S-cursor counts as state change.
1872 This is the default behavior. However, setting this to nil allows a
1873 convenient way to select a TODO state and bypass any logging associated
1874 with that."
1875 :group 'org-todo
1876 :type 'boolean)
1878 (defcustom org-todo-state-tags-triggers nil
1879 "Tag changes that should be triggered by TODO state changes.
1880 This is a list. Each entry is
1882 (state-change (tag . flag) .......)
1884 State-change can be a string with a state, and empty string to indicate the
1885 state that has no TODO keyword, or it can be one of the symbols `todo'
1886 or `done', meaning any not-done or done state, respectively."
1887 :group 'org-todo
1888 :group 'org-tags
1889 :type '(repeat
1890 (cons (choice :tag "When changing to"
1891 (const :tag "Not-done state" todo)
1892 (const :tag "Done state" done)
1893 (string :tag "State"))
1894 (repeat
1895 (cons :tag "Tag action"
1896 (string :tag "Tag")
1897 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1899 (defcustom org-log-done nil
1900 "Information to record when a task moves to the DONE state.
1902 Possible values are:
1904 nil Don't add anything, just change the keyword
1905 time Add a time stamp to the task
1906 note Prompt a closing note and add it with template `org-log-note-headings'
1908 This option can also be set with on a per-file-basis with
1910 #+STARTUP: nologdone
1911 #+STARTUP: logdone
1912 #+STARTUP: lognotedone
1914 You can have local logging settings for a subtree by setting the LOGGING
1915 property to one or more of these keywords."
1916 :group 'org-todo
1917 :group 'org-progress
1918 :type '(choice
1919 (const :tag "No logging" nil)
1920 (const :tag "Record CLOSED timestamp" time)
1921 (const :tag "Record CLOSED timestamp with closing note." note)))
1923 ;; Normalize old uses of org-log-done.
1924 (cond
1925 ((eq org-log-done t) (setq org-log-done 'time))
1926 ((and (listp org-log-done) (memq 'done org-log-done))
1927 (setq org-log-done 'note)))
1929 (defcustom org-log-note-clock-out nil
1930 "Non-nil means, record a note when clocking out of an item.
1931 This can also be configured on a per-file basis by adding one of
1932 the following lines anywhere in the buffer:
1934 #+STARTUP: lognoteclock-out
1935 #+STARTUP: nolognoteclock-out"
1936 :group 'org-todo
1937 :group 'org-progress
1938 :type 'boolean)
1940 (defcustom org-log-done-with-time t
1941 "Non-nil means, the CLOSED time stamp will contain date and time.
1942 When nil, only the date will be recorded."
1943 :group 'org-progress
1944 :type 'boolean)
1946 (defcustom org-log-note-headings
1947 '((done . "CLOSING NOTE %t")
1948 (state . "State %-12s from %-12S %t")
1949 (note . "Note taken on %t")
1950 (clock-out . ""))
1951 "Headings for notes added to entries.
1952 The value is an alist, with the car being a symbol indicating the note
1953 context, and the cdr is the heading to be used. The heading may also be the
1954 empty string.
1955 %t in the heading will be replaced by a time stamp.
1956 %s will be replaced by the new TODO state, in double quotes.
1957 %S will be replaced by the old TODO state, in double quotes.
1958 %u will be replaced by the user name.
1959 %U will be replaced by the full user name."
1960 :group 'org-todo
1961 :group 'org-progress
1962 :type '(list :greedy t
1963 (cons (const :tag "Heading when closing an item" done) string)
1964 (cons (const :tag
1965 "Heading when changing todo state (todo sequence only)"
1966 state) string)
1967 (cons (const :tag "Heading when just taking a note" note) string)
1968 (cons (const :tag "Heading when clocking out" clock-out) string)))
1970 (unless (assq 'note org-log-note-headings)
1971 (push '(note . "%t") org-log-note-headings))
1973 (defcustom org-log-into-drawer nil
1974 "Non-nil means, insert state change notes and time stamps into a drawer.
1975 When nil, state changes notes will be inserted after the headline and
1976 any scheduling and clock lines, but not inside a drawer.
1978 The value of this variable should be the name of the drawer to use.
1979 LOGBOOK is proposed at the default drawer for this purpose, you can
1980 also set this to a string to define the drawer of your choice.
1982 A value of t is also allowed, representing \"LOGBOOK\".
1984 If this variable is set, `org-log-state-notes-insert-after-drawers'
1985 will be ignored.
1987 You can set the property LOG_INTO_DRAWER to overrule this setting for
1988 a subtree."
1989 :group 'org-todo
1990 :group 'org-progress
1991 :type '(choice
1992 (const :tag "Not into a drawer" nil)
1993 (const :tag "LOGBOOK" t)
1994 (string :tag "Other")))
1996 (if (fboundp 'defvaralias)
1997 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1999 (defun org-log-into-drawer ()
2000 "Return the value of `org-log-into-drawer', but let properties overrule.
2001 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2002 used instead of the default value."
2003 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2004 (cond
2005 ((or (not p) (equal p "nil")) org-log-into-drawer)
2006 ((equal p "t") "LOGBOOK")
2007 (t p))))
2009 (defcustom org-log-state-notes-insert-after-drawers nil
2010 "Non-nil means, insert state change notes after any drawers in entry.
2011 Only the drawers that *immediately* follow the headline and the
2012 deadline/scheduled line are skipped.
2013 When nil, insert notes right after the heading and perhaps the line
2014 with deadline/scheduling if present.
2016 This variable will have no effect if `org-log-into-drawer' is
2017 set."
2018 :group 'org-todo
2019 :group 'org-progress
2020 :type 'boolean)
2022 (defcustom org-log-states-order-reversed t
2023 "Non-nil means, the latest state change note will be directly after heading.
2024 When nil, the notes will be orderer according to time."
2025 :group 'org-todo
2026 :group 'org-progress
2027 :type 'boolean)
2029 (defcustom org-log-repeat 'time
2030 "Non-nil means, record moving through the DONE state when triggering repeat.
2031 An auto-repeating task is immediately switched back to TODO when
2032 marked DONE. If you are not logging state changes (by adding \"@\"
2033 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2034 record a closing note, there will be no record of the task moving
2035 through DONE. This variable forces taking a note anyway.
2037 nil Don't force a record
2038 time Record a time stamp
2039 note Record a note
2041 This option can also be set with on a per-file-basis with
2043 #+STARTUP: logrepeat
2044 #+STARTUP: lognoterepeat
2045 #+STARTUP: nologrepeat
2047 You can have local logging settings for a subtree by setting the LOGGING
2048 property to one or more of these keywords."
2049 :group 'org-todo
2050 :group 'org-progress
2051 :type '(choice
2052 (const :tag "Don't force a record" nil)
2053 (const :tag "Force recording the DONE state" time)
2054 (const :tag "Force recording a note with the DONE state" note)))
2057 (defgroup org-priorities nil
2058 "Priorities in Org-mode."
2059 :tag "Org Priorities"
2060 :group 'org-todo)
2062 (defcustom org-enable-priority-commands t
2063 "Non-nil means, priority commands are active.
2064 When nil, these commands will be disabled, so that you never accidentally
2065 set a priority."
2066 :group 'org-priorities
2067 :type 'boolean)
2069 (defcustom org-highest-priority ?A
2070 "The highest priority of TODO items. A character like ?A, ?B etc.
2071 Must have a smaller ASCII number than `org-lowest-priority'."
2072 :group 'org-priorities
2073 :type 'character)
2075 (defcustom org-lowest-priority ?C
2076 "The lowest priority of TODO items. A character like ?A, ?B etc.
2077 Must have a larger ASCII number than `org-highest-priority'."
2078 :group 'org-priorities
2079 :type 'character)
2081 (defcustom org-default-priority ?B
2082 "The default priority of TODO items.
2083 This is the priority an item get if no explicit priority is given."
2084 :group 'org-priorities
2085 :type 'character)
2087 (defcustom org-priority-start-cycle-with-default t
2088 "Non-nil means, start with default priority when starting to cycle.
2089 When this is nil, the first step in the cycle will be (depending on the
2090 command used) one higher or lower that the default priority."
2091 :group 'org-priorities
2092 :type 'boolean)
2094 (defgroup org-time nil
2095 "Options concerning time stamps and deadlines in Org-mode."
2096 :tag "Org Time"
2097 :group 'org)
2099 (defcustom org-insert-labeled-timestamps-at-point nil
2100 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2101 When nil, these labeled time stamps are forces into the second line of an
2102 entry, just after the headline. When scheduling from the global TODO list,
2103 the time stamp will always be forced into the second line."
2104 :group 'org-time
2105 :type 'boolean)
2107 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2108 "Formats for `format-time-string' which are used for time stamps.
2109 It is not recommended to change this constant.")
2111 (defcustom org-time-stamp-rounding-minutes '(0 5)
2112 "Number of minutes to round time stamps to.
2113 These are two values, the first applies when first creating a time stamp.
2114 The second applies when changing it with the commands `S-up' and `S-down'.
2115 When changing the time stamp, this means that it will change in steps
2116 of N minutes, as given by the second value.
2118 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2119 numbers should be factors of 60, so for example 5, 10, 15.
2121 When this is larger than 1, you can still force an exact time-stamp by using
2122 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2123 and by using a prefix arg to `S-up/down' to specify the exact number
2124 of minutes to shift."
2125 :group 'org-time
2126 :get '(lambda (var) ; Make sure all entries have 5 elements
2127 (if (integerp (default-value var))
2128 (list (default-value var) 5)
2129 (default-value var)))
2130 :type '(list
2131 (integer :tag "when inserting times")
2132 (integer :tag "when modifying times")))
2134 ;; Normalize old customizations of this variable.
2135 (when (integerp org-time-stamp-rounding-minutes)
2136 (setq org-time-stamp-rounding-minutes
2137 (list org-time-stamp-rounding-minutes
2138 org-time-stamp-rounding-minutes)))
2140 (defcustom org-display-custom-times nil
2141 "Non-nil means, overlay custom formats over all time stamps.
2142 The formats are defined through the variable `org-time-stamp-custom-formats'.
2143 To turn this on on a per-file basis, insert anywhere in the file:
2144 #+STARTUP: customtime"
2145 :group 'org-time
2146 :set 'set-default
2147 :type 'sexp)
2148 (make-variable-buffer-local 'org-display-custom-times)
2150 (defcustom org-time-stamp-custom-formats
2151 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2152 "Custom formats for time stamps. See `format-time-string' for the syntax.
2153 These are overlayed over the default ISO format if the variable
2154 `org-display-custom-times' is set. Time like %H:%M should be at the
2155 end of the second format. The custom formats are also honored by export
2156 commands, if custom time display is turned on at the time of export."
2157 :group 'org-time
2158 :type 'sexp)
2160 (defun org-time-stamp-format (&optional long inactive)
2161 "Get the right format for a time string."
2162 (let ((f (if long (cdr org-time-stamp-formats)
2163 (car org-time-stamp-formats))))
2164 (if inactive
2165 (concat "[" (substring f 1 -1) "]")
2166 f)))
2168 (defcustom org-time-clocksum-format "%d:%02d"
2169 "The format string used when creating CLOCKSUM lines, or when
2170 org-mode generates a time duration."
2171 :group 'org-time
2172 :type 'string)
2174 (defcustom org-deadline-warning-days 14
2175 "No. of days before expiration during which a deadline becomes active.
2176 This variable governs the display in sparse trees and in the agenda.
2177 When 0 or negative, it means use this number (the absolute value of it)
2178 even if a deadline has a different individual lead time specified.
2180 Custom commands can set this variable in the options section."
2181 :group 'org-time
2182 :group 'org-agenda-daily/weekly
2183 :type 'integer)
2185 (defcustom org-read-date-prefer-future t
2186 "Non-nil means, assume future for incomplete date input from user.
2187 This affects the following situations:
2188 1. The user gives a day, but no month.
2189 For example, if today is the 15th, and you enter \"3\", Org-mode will
2190 read this as the third of *next* month. However, if you enter \"17\",
2191 it will be considered as *this* month.
2192 2. The user gives a month but not a year.
2193 For example, if it is april and you enter \"feb 2\", this will be read
2194 as feb 2, *next* year. \"May 5\", however, will be this year.
2196 Currently this does not work for ISO week specifications.
2198 When this option is nil, the current month and year will always be used
2199 as defaults."
2200 :group 'org-time
2201 :type 'boolean)
2203 (defcustom org-read-date-display-live t
2204 "Non-nil means, display current interpretation of date prompt live.
2205 This display will be in an overlay, in the minibuffer."
2206 :group 'org-time
2207 :type 'boolean)
2209 (defcustom org-read-date-popup-calendar t
2210 "Non-nil means, pop up a calendar when prompting for a date.
2211 In the calendar, the date can be selected with mouse-1. However, the
2212 minibuffer will also be active, and you can simply enter the date as well.
2213 When nil, only the minibuffer will be available."
2214 :group 'org-time
2215 :type 'boolean)
2216 (if (fboundp 'defvaralias)
2217 (defvaralias 'org-popup-calendar-for-date-prompt
2218 'org-read-date-popup-calendar))
2220 (defcustom org-read-date-minibuffer-setup-hook nil
2221 "Hook to be used to set up keys for the date/time interface.
2222 Add key definitions to `minibuffer-local-map', which will be a temporary
2223 copy."
2224 :group 'org-time
2225 :type 'hook)
2227 (defcustom org-extend-today-until 0
2228 "The hour when your day really ends. Must be an integer.
2229 This has influence for the following applications:
2230 - When switching the agenda to \"today\". It it is still earlier than
2231 the time given here, the day recognized as TODAY is actually yesterday.
2232 - When a date is read from the user and it is still before the time given
2233 here, the current date and time will be assumed to be yesterday, 23:59.
2234 Also, timestamps inserted in remember templates follow this rule.
2236 IMPORTANT: This is a feature whose implementation is and likely will
2237 remain incomplete. Really, it is only here because past midnight seems to
2238 be the favorite working time of John Wiegley :-)"
2239 :group 'org-time
2240 :type 'integer)
2242 (defcustom org-edit-timestamp-down-means-later nil
2243 "Non-nil means, S-down will increase the time in a time stamp.
2244 When nil, S-up will increase."
2245 :group 'org-time
2246 :type 'boolean)
2248 (defcustom org-calendar-follow-timestamp-change t
2249 "Non-nil means, make the calendar window follow timestamp changes.
2250 When a timestamp is modified and the calendar window is visible, it will be
2251 moved to the new date."
2252 :group 'org-time
2253 :type 'boolean)
2255 (defgroup org-tags nil
2256 "Options concerning tags in Org-mode."
2257 :tag "Org Tags"
2258 :group 'org)
2260 (defcustom org-tag-alist nil
2261 "List of tags allowed in Org-mode files.
2262 When this list is nil, Org-mode will base TAG input on what is already in the
2263 buffer.
2264 The value of this variable is an alist, the car of each entry must be a
2265 keyword as a string, the cdr may be a character that is used to select
2266 that tag through the fast-tag-selection interface.
2267 See the manual for details."
2268 :group 'org-tags
2269 :type '(repeat
2270 (choice
2271 (cons (string :tag "Tag name")
2272 (character :tag "Access char"))
2273 (const :tag "Start radio group" (:startgroup))
2274 (const :tag "End radio group" (:endgroup))
2275 (const :tag "New line" (:newline)))))
2277 (defcustom org-tag-persistent-alist nil
2278 "List of tags that will always appear in all Org-mode files.
2279 This is in addition to any in buffer settings or customizations
2280 of `org-tag-alist'.
2281 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2282 The value of this variable is an alist, the car of each entry must be a
2283 keyword as a string, the cdr may be a character that is used to select
2284 that tag through the fast-tag-selection interface.
2285 See the manual for details.
2286 To disable these tags on a per-file basis, insert anywhere in the file:
2287 #+STARTUP: noptag"
2288 :group 'org-tags
2289 :type '(repeat
2290 (choice
2291 (cons (string :tag "Tag name")
2292 (character :tag "Access char"))
2293 (const :tag "Start radio group" (:startgroup))
2294 (const :tag "End radio group" (:endgroup))
2295 (const :tag "New line" (:newline)))))
2297 (defvar org-file-tags nil
2298 "List of tags that can be inherited by all entries in the file.
2299 The tags will be inherited if the variable `org-use-tag-inheritance'
2300 says they should be.
2301 This variable is populated from #+TAG lines.")
2303 (defcustom org-use-fast-tag-selection 'auto
2304 "Non-nil means, use fast tag selection scheme.
2305 This is a special interface to select and deselect tags with single keys.
2306 When nil, fast selection is never used.
2307 When the symbol `auto', fast selection is used if and only if selection
2308 characters for tags have been configured, either through the variable
2309 `org-tag-alist' or through a #+TAGS line in the buffer.
2310 When t, fast selection is always used and selection keys are assigned
2311 automatically if necessary."
2312 :group 'org-tags
2313 :type '(choice
2314 (const :tag "Always" t)
2315 (const :tag "Never" nil)
2316 (const :tag "When selection characters are configured" 'auto)))
2318 (defcustom org-fast-tag-selection-single-key nil
2319 "Non-nil means, fast tag selection exits after first change.
2320 When nil, you have to press RET to exit it.
2321 During fast tag selection, you can toggle this flag with `C-c'.
2322 This variable can also have the value `expert'. In this case, the window
2323 displaying the tags menu is not even shown, until you press C-c again."
2324 :group 'org-tags
2325 :type '(choice
2326 (const :tag "No" nil)
2327 (const :tag "Yes" t)
2328 (const :tag "Expert" expert)))
2330 (defvar org-fast-tag-selection-include-todo nil
2331 "Non-nil means, fast tags selection interface will also offer TODO states.
2332 This is an undocumented feature, you should not rely on it.")
2334 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2335 "The column to which tags should be indented in a headline.
2336 If this number is positive, it specifies the column. If it is negative,
2337 it means that the tags should be flushright to that column. For example,
2338 -80 works well for a normal 80 character screen."
2339 :group 'org-tags
2340 :type 'integer)
2342 (defcustom org-auto-align-tags t
2343 "Non-nil means, realign tags after pro/demotion of TODO state change.
2344 These operations change the length of a headline and therefore shift
2345 the tags around. With this options turned on, after each such operation
2346 the tags are again aligned to `org-tags-column'."
2347 :group 'org-tags
2348 :type 'boolean)
2350 (defcustom org-use-tag-inheritance t
2351 "Non-nil means, tags in levels apply also for sublevels.
2352 When nil, only the tags directly given in a specific line apply there.
2353 This may also be a list of tags that should be inherited, or a regexp that
2354 matches tags that should be inherited. Additional control is possible
2355 with the variable `org-tags-exclude-from-inheritance' which gives an
2356 explicit list of tags to be excluded from inheritance., even if the value of
2357 `org-use-tag-inheritance' would select it for inheritance.
2359 If this option is t, a match early-on in a tree can lead to a large
2360 number of matches in the subtree when constructing the agenda or creating
2361 a sparse tree. If you only want to see the first match in a tree during
2362 a search, check out the variable `org-tags-match-list-sublevels'."
2363 :group 'org-tags
2364 :type '(choice
2365 (const :tag "Not" nil)
2366 (const :tag "Always" t)
2367 (repeat :tag "Specific tags" (string :tag "Tag"))
2368 (regexp :tag "Tags matched by regexp")))
2370 (defcustom org-tags-exclude-from-inheritance nil
2371 "List of tags that should never be inherited.
2372 This is a way to exclude a few tags from inheritance. For way to do
2373 the opposite, to actively allow inheritance for selected tags,
2374 see the variable `org-use-tag-inheritance'."
2375 :group 'org-tags
2376 :type '(repeat (string :tag "Tag")))
2378 (defun org-tag-inherit-p (tag)
2379 "Check if TAG is one that should be inherited."
2380 (cond
2381 ((member tag org-tags-exclude-from-inheritance) nil)
2382 ((eq org-use-tag-inheritance t) t)
2383 ((not org-use-tag-inheritance) nil)
2384 ((stringp org-use-tag-inheritance)
2385 (string-match org-use-tag-inheritance tag))
2386 ((listp org-use-tag-inheritance)
2387 (member tag org-use-tag-inheritance))
2388 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2390 (defcustom org-tags-match-list-sublevels t
2391 "Non-nil means list also sublevels of headlines matching a search.
2392 This variable applies to tags/property searches, and also to stuck
2393 projects because this search is based on a tags match as well.
2395 When set to the symbol `indented', sublevels are indented with
2396 leading dots.
2398 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2399 the sublevels of a headline matching a tag search often also match
2400 the same search. Listing all of them can create very long lists.
2401 Setting this variable to nil causes subtrees of a match to be skipped.
2403 This variable is semi-obsolete and probably should always be true. It
2404 is better to limit inheritance to certain tags using the variables
2405 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2406 :group 'org-tags
2407 :type '(choice
2408 (const :tag "No, don't list them" nil)
2409 (const :tag "Yes, do list them" t)
2410 (const :tag "List them, indented with leading dots" indented)))
2412 (defcustom org-tags-sort-function nil
2413 "When set, tags are sorted using this function as a comparator"
2414 :group 'org-tags
2415 :type '(choice
2416 (const :tag "No sorting" nil)
2417 (const :tag "Alphabetical" string<)
2418 (const :tag "Reverse alphabetical" string>)
2419 (function :tag "Custom function" nil)))
2421 (defvar org-tags-history nil
2422 "History of minibuffer reads for tags.")
2423 (defvar org-last-tags-completion-table nil
2424 "The last used completion table for tags.")
2425 (defvar org-after-tags-change-hook nil
2426 "Hook that is run after the tags in a line have changed.")
2428 (defgroup org-properties nil
2429 "Options concerning properties in Org-mode."
2430 :tag "Org Properties"
2431 :group 'org)
2433 (defcustom org-property-format "%-10s %s"
2434 "How property key/value pairs should be formatted by `indent-line'.
2435 When `indent-line' hits a property definition, it will format the line
2436 according to this format, mainly to make sure that the values are
2437 lined-up with respect to each other."
2438 :group 'org-properties
2439 :type 'string)
2441 (defcustom org-use-property-inheritance nil
2442 "Non-nil means, properties apply also for sublevels.
2444 This setting is chiefly used during property searches. Turning it on can
2445 cause significant overhead when doing a search, which is why it is not
2446 on by default.
2448 When nil, only the properties directly given in the current entry count.
2449 When t, every property is inherited. The value may also be a list of
2450 properties that should have inheritance, or a regular expression matching
2451 properties that should be inherited.
2453 However, note that some special properties use inheritance under special
2454 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2455 and the properties ending in \"_ALL\" when they are used as descriptor
2456 for valid values of a property.
2458 Note for programmers:
2459 When querying an entry with `org-entry-get', you can control if inheritance
2460 should be used. By default, `org-entry-get' looks only at the local
2461 properties. You can request inheritance by setting the inherit argument
2462 to t (to force inheritance) or to `selective' (to respect the setting
2463 in this variable)."
2464 :group 'org-properties
2465 :type '(choice
2466 (const :tag "Not" nil)
2467 (const :tag "Always" t)
2468 (repeat :tag "Specific properties" (string :tag "Property"))
2469 (regexp :tag "Properties matched by regexp")))
2471 (defun org-property-inherit-p (property)
2472 "Check if PROPERTY is one that should be inherited."
2473 (cond
2474 ((eq org-use-property-inheritance t) t)
2475 ((not org-use-property-inheritance) nil)
2476 ((stringp org-use-property-inheritance)
2477 (string-match org-use-property-inheritance property))
2478 ((listp org-use-property-inheritance)
2479 (member property org-use-property-inheritance))
2480 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2482 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2483 "The default column format, if no other format has been defined.
2484 This variable can be set on the per-file basis by inserting a line
2486 #+COLUMNS: %25ITEM ....."
2487 :group 'org-properties
2488 :type 'string)
2490 (defcustom org-columns-ellipses ".."
2491 "The ellipses to be used when a field in column view is truncated.
2492 When this is the empty string, as many characters as possible are shown,
2493 but then there will be no visual indication that the field has been truncated.
2494 When this is a string of length N, the last N characters of a truncated
2495 field are replaced by this string. If the column is narrower than the
2496 ellipses string, only part of the ellipses string will be shown."
2497 :group 'org-properties
2498 :type 'string)
2500 (defcustom org-columns-modify-value-for-display-function nil
2501 "Function that modifies values for display in column view.
2502 For example, it can be used to cut out a certain part from a time stamp.
2503 The function must take 2 arguments:
2505 column-title The title of the column (*not* the property name)
2506 value The value that should be modified.
2508 The function should return the value that should be displayed,
2509 or nil if the normal value should be used."
2510 :group 'org-properties
2511 :type 'function)
2513 (defcustom org-effort-property "Effort"
2514 "The property that is being used to keep track of effort estimates.
2515 Effort estimates given in this property need to have the format H:MM."
2516 :group 'org-properties
2517 :group 'org-progress
2518 :type '(string :tag "Property"))
2520 (defconst org-global-properties-fixed
2521 '(("VISIBILITY_ALL" . "folded children content all")
2522 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2523 "List of property/value pairs that can be inherited by any entry.
2525 These are fixed values, for the preset properties. The user variable
2526 that can be used to add to this list is `org-global-properties'.
2528 The entries in this list are cons cells where the car is a property
2529 name and cdr is a string with the value. If the value represents
2530 multiple items like an \"_ALL\" property, separate the items by
2531 spaces.")
2533 (defcustom org-global-properties nil
2534 "List of property/value pairs that can be inherited by any entry.
2536 This list will be combined with the constant `org-global-properties-fixed'.
2538 The entries in this list are cons cells where the car is a property
2539 name and cdr is a string with the value.
2541 You can set buffer-local values for the same purpose in the variable
2542 `org-file-properties' this by adding lines like
2544 #+PROPERTY: NAME VALUE"
2545 :group 'org-properties
2546 :type '(repeat
2547 (cons (string :tag "Property")
2548 (string :tag "Value"))))
2550 (defvar org-file-properties nil
2551 "List of property/value pairs that can be inherited by any entry.
2552 Valid for the current buffer.
2553 This variable is populated from #+PROPERTY lines.")
2554 (make-variable-buffer-local 'org-file-properties)
2556 (defgroup org-agenda nil
2557 "Options concerning agenda views in Org-mode."
2558 :tag "Org Agenda"
2559 :group 'org)
2561 (defvar org-category nil
2562 "Variable used by org files to set a category for agenda display.
2563 Such files should use a file variable to set it, for example
2565 # -*- mode: org; org-category: \"ELisp\"
2567 or contain a special line
2569 #+CATEGORY: ELisp
2571 If the file does not specify a category, then file's base name
2572 is used instead.")
2573 (make-variable-buffer-local 'org-category)
2574 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2576 (defcustom org-agenda-files nil
2577 "The files to be used for agenda display.
2578 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2579 \\[org-remove-file]. You can also use customize to edit the list.
2581 If an entry is a directory, all files in that directory that are matched by
2582 `org-agenda-file-regexp' will be part of the file list.
2584 If the value of the variable is not a list but a single file name, then
2585 the list of agenda files is actually stored and maintained in that file, one
2586 agenda file per line."
2587 :group 'org-agenda
2588 :type '(choice
2589 (repeat :tag "List of files and directories" file)
2590 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2592 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2593 "Regular expression to match files for `org-agenda-files'.
2594 If any element in the list in that variable contains a directory instead
2595 of a normal file, all files in that directory that are matched by this
2596 regular expression will be included."
2597 :group 'org-agenda
2598 :type 'regexp)
2600 (defcustom org-agenda-text-search-extra-files nil
2601 "List of extra files to be searched by text search commands.
2602 These files will be search in addition to the agenda files by the
2603 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2604 Note that these files will only be searched for text search commands,
2605 not for the other agenda views like todo lists, tag searches or the weekly
2606 agenda. This variable is intended to list notes and possibly archive files
2607 that should also be searched by these two commands.
2608 In fact, if the first element in the list is the symbol `agenda-archives',
2609 than all archive files of all agenda files will be added to the search
2610 scope."
2611 :group 'org-agenda
2612 :type '(set :greedy t
2613 (const :tag "Agenda Archives" agenda-archives)
2614 (repeat :inline t (file))))
2616 (if (fboundp 'defvaralias)
2617 (defvaralias 'org-agenda-multi-occur-extra-files
2618 'org-agenda-text-search-extra-files))
2620 (defcustom org-agenda-skip-unavailable-files nil
2621 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2622 A nil value means to remove them, after a query, from the list."
2623 :group 'org-agenda
2624 :type 'boolean)
2626 (defcustom org-calendar-to-agenda-key [?c]
2627 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2628 The command `org-calendar-goto-agenda' will be bound to this key. The
2629 default is the character `c' because then `c' can be used to switch back and
2630 forth between agenda and calendar."
2631 :group 'org-agenda
2632 :type 'sexp)
2634 (defcustom org-calendar-agenda-action-key [?k]
2635 "The key to be installed in `calendar-mode-map' for agenda-action.
2636 The command `org-agenda-action' will be bound to this key. The
2637 default is the character `k' because we use the same key in the agenda."
2638 :group 'org-agenda
2639 :type 'sexp)
2641 (eval-after-load "calendar"
2642 '(progn
2643 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2644 'org-calendar-goto-agenda)
2645 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2646 'org-agenda-action)))
2648 (defgroup org-latex nil
2649 "Options for embedding LaTeX code into Org-mode."
2650 :tag "Org LaTeX"
2651 :group 'org)
2653 (defcustom org-format-latex-options
2654 '(:foreground default :background default :scale 1.0
2655 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2656 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2657 "Options for creating images from LaTeX fragments.
2658 This is a property list with the following properties:
2659 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2660 `default' means use the foreground of the default face.
2661 :background the background color, or \"Transparent\".
2662 `default' means use the background of the default face.
2663 :scale a scaling factor for the size of the images.
2664 :html-foreground, :html-background, :html-scale
2665 the same numbers for HTML export.
2666 :matchers a list indicating which matchers should be used to
2667 find LaTeX fragments. Valid members of this list are:
2668 \"begin\" find environments
2669 \"$1\" find single characters surrounded by $.$
2670 \"$\" find math expressions surrounded by $...$
2671 \"$$\" find math expressions surrounded by $$....$$
2672 \"\\(\" find math expressions surrounded by \\(...\\)
2673 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2674 :group 'org-latex
2675 :type 'plist)
2677 (defcustom org-format-latex-header "\\documentclass{article}
2678 \\usepackage{fullpage} % do not remove
2679 \\usepackage{amssymb}
2680 \\usepackage[usenames]{color}
2681 \\usepackage{amsmath}
2682 \\usepackage{latexsym}
2683 \\usepackage[mathscr]{eucal}
2684 \\pagestyle{empty} % do not remove"
2685 "The document header used for processing LaTeX fragments."
2686 :group 'org-latex
2687 :type 'string)
2690 (defgroup org-font-lock nil
2691 "Font-lock settings for highlighting in Org-mode."
2692 :tag "Org Font Lock"
2693 :group 'org)
2695 (defcustom org-level-color-stars-only nil
2696 "Non-nil means fontify only the stars in each headline.
2697 When nil, the entire headline is fontified.
2698 Changing it requires restart of `font-lock-mode' to become effective
2699 also in regions already fontified."
2700 :group 'org-font-lock
2701 :type 'boolean)
2703 (defcustom org-hide-leading-stars nil
2704 "Non-nil means, hide the first N-1 stars in a headline.
2705 This works by using the face `org-hide' for these stars. This
2706 face is white for a light background, and black for a dark
2707 background. You may have to customize the face `org-hide' to
2708 make this work.
2709 Changing it requires restart of `font-lock-mode' to become effective
2710 also in regions already fontified.
2711 You may also set this on a per-file basis by adding one of the following
2712 lines to the buffer:
2714 #+STARTUP: hidestars
2715 #+STARTUP: showstars"
2716 :group 'org-font-lock
2717 :type 'boolean)
2719 (defcustom org-fontify-done-headline nil
2720 "Non-nil means, change the face of a headline if it is marked DONE.
2721 Normally, only the TODO/DONE keyword indicates the state of a headline.
2722 When this is non-nil, the headline after the keyword is set to the
2723 `org-headline-done' as an additional indication."
2724 :group 'org-font-lock
2725 :type 'boolean)
2727 (defcustom org-fontify-emphasized-text t
2728 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2729 Changing this variable requires a restart of Emacs to take effect."
2730 :group 'org-font-lock
2731 :type 'boolean)
2733 (defcustom org-fontify-whole-heading-line nil
2734 "Non-nil means fontify the whole line for headings.
2735 This is useful when setting a background color for the
2736 org-leve-* faces."
2737 :group 'org-font-lock
2738 :type 'boolean)
2740 (defcustom org-highlight-latex-fragments-and-specials nil
2741 "Non-nil means, fontify what is treated specially by the exporters."
2742 :group 'org-font-lock
2743 :type 'boolean)
2745 (defcustom org-hide-emphasis-markers nil
2746 "Non-nil mean font-lock should hide the emphasis marker characters."
2747 :group 'org-font-lock
2748 :type 'boolean)
2750 (defvar org-emph-re nil
2751 "Regular expression for matching emphasis.")
2752 (defvar org-verbatim-re nil
2753 "Regular expression for matching verbatim text.")
2754 (defvar org-emphasis-regexp-components) ; defined just below
2755 (defvar org-emphasis-alist) ; defined just below
2756 (defun org-set-emph-re (var val)
2757 "Set variable and compute the emphasis regular expression."
2758 (set var val)
2759 (when (and (boundp 'org-emphasis-alist)
2760 (boundp 'org-emphasis-regexp-components)
2761 org-emphasis-alist org-emphasis-regexp-components)
2762 (let* ((e org-emphasis-regexp-components)
2763 (pre (car e))
2764 (post (nth 1 e))
2765 (border (nth 2 e))
2766 (body (nth 3 e))
2767 (nl (nth 4 e))
2768 (body1 (concat body "*?"))
2769 (markers (mapconcat 'car org-emphasis-alist ""))
2770 (vmarkers (mapconcat
2771 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2772 org-emphasis-alist "")))
2773 ;; make sure special characters appear at the right position in the class
2774 (if (string-match "\\^" markers)
2775 (setq markers (concat (replace-match "" t t markers) "^")))
2776 (if (string-match "-" markers)
2777 (setq markers (concat (replace-match "" t t markers) "-")))
2778 (if (string-match "\\^" vmarkers)
2779 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2780 (if (string-match "-" vmarkers)
2781 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2782 (if (> nl 0)
2783 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2784 (int-to-string nl) "\\}")))
2785 ;; Make the regexp
2786 (setq org-emph-re
2787 (concat "\\([" pre "]\\|^\\)"
2788 "\\("
2789 "\\([" markers "]\\)"
2790 "\\("
2791 "[^" border "]\\|"
2792 "[^" border "]"
2793 body1
2794 "[^" border "]"
2795 "\\)"
2796 "\\3\\)"
2797 "\\([" post "]\\|$\\)"))
2798 (setq org-verbatim-re
2799 (concat "\\([" pre "]\\|^\\)"
2800 "\\("
2801 "\\([" vmarkers "]\\)"
2802 "\\("
2803 "[^" border "]\\|"
2804 "[^" border "]"
2805 body1
2806 "[^" border "]"
2807 "\\)"
2808 "\\3\\)"
2809 "\\([" post "]\\|$\\)")))))
2811 (defcustom org-emphasis-regexp-components
2812 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2813 "Components used to build the regular expression for emphasis.
2814 This is a list with 6 entries. Terminology: In an emphasis string
2815 like \" *strong word* \", we call the initial space PREMATCH, the final
2816 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2817 and \"trong wor\" is the body. The different components in this variable
2818 specify what is allowed/forbidden in each part:
2820 pre Chars allowed as prematch. Beginning of line will be allowed too.
2821 post Chars allowed as postmatch. End of line will be allowed too.
2822 border The chars *forbidden* as border characters.
2823 body-regexp A regexp like \".\" to match a body character. Don't use
2824 non-shy groups here, and don't allow newline here.
2825 newline The maximum number of newlines allowed in an emphasis exp.
2827 Use customize to modify this, or restart Emacs after changing it."
2828 :group 'org-font-lock
2829 :set 'org-set-emph-re
2830 :type '(list
2831 (sexp :tag "Allowed chars in pre ")
2832 (sexp :tag "Allowed chars in post ")
2833 (sexp :tag "Forbidden chars in border ")
2834 (sexp :tag "Regexp for body ")
2835 (integer :tag "number of newlines allowed")
2836 (option (boolean :tag "Please ignore this button"))))
2838 (defcustom org-emphasis-alist
2839 `(("*" bold "<b>" "</b>")
2840 ("/" italic "<i>" "</i>")
2841 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2842 ("=" org-code "<code>" "</code>" verbatim)
2843 ("~" org-verbatim "<code>" "</code>" verbatim)
2844 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2845 "<del>" "</del>")
2847 "Special syntax for emphasized text.
2848 Text starting and ending with a special character will be emphasized, for
2849 example *bold*, _underlined_ and /italic/. This variable sets the marker
2850 characters, the face to be used by font-lock for highlighting in Org-mode
2851 Emacs buffers, and the HTML tags to be used for this.
2852 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2853 Use customize to modify this, or restart Emacs after changing it."
2854 :group 'org-font-lock
2855 :set 'org-set-emph-re
2856 :type '(repeat
2857 (list
2858 (string :tag "Marker character")
2859 (choice
2860 (face :tag "Font-lock-face")
2861 (plist :tag "Face property list"))
2862 (string :tag "HTML start tag")
2863 (string :tag "HTML end tag")
2864 (option (const verbatim)))))
2866 (defvar org-protecting-blocks
2867 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2868 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2869 This is needed for font-lock setup.")
2871 ;;; Miscellaneous options
2873 (defgroup org-completion nil
2874 "Completion in Org-mode."
2875 :tag "Org Completion"
2876 :group 'org)
2878 (defcustom org-completion-use-ido nil
2879 "Non-nil means, use ido completion wherever possible.
2880 Note that `ido-mode' must be active for this variable to be relevant.
2881 If you decide to turn this variable on, you might well want to turn off
2882 `org-outline-path-complete-in-steps'.
2883 See also `org-completion-use-iswitchb'."
2884 :group 'org-completion
2885 :type 'boolean)
2887 (defcustom org-completion-use-iswitchb nil
2888 "Non-nil means, use iswitchb completion wherever possible.
2889 Note that `iswitchb-mode' must be active for this variable to be relevant.
2890 If you decide to turn this variable on, you might well want to turn off
2891 `org-outline-path-complete-in-steps'.
2892 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
2893 :group 'org-completion
2894 :type 'boolean)
2896 (defcustom org-completion-fallback-command 'hippie-expand
2897 "The expansion command called by \\[org-complete] in normal context.
2898 Normal means, no org-mode-specific context."
2899 :group 'org-completion
2900 :type 'function)
2902 ;;; Functions and variables from ther packages
2903 ;; Declared here to avoid compiler warnings
2905 ;; XEmacs only
2906 (defvar outline-mode-menu-heading)
2907 (defvar outline-mode-menu-show)
2908 (defvar outline-mode-menu-hide)
2909 (defvar zmacs-regions) ; XEmacs regions
2911 ;; Emacs only
2912 (defvar mark-active)
2914 ;; Various packages
2915 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2916 (declare-function calendar-forward-day "cal-move" (arg))
2917 (declare-function calendar-goto-date "cal-move" (date))
2918 (declare-function calendar-goto-today "cal-move" ())
2919 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2920 (defvar calc-embedded-close-formula)
2921 (defvar calc-embedded-open-formula)
2922 (declare-function cdlatex-tab "ext:cdlatex" ())
2923 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2924 (defvar font-lock-unfontify-region-function)
2925 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2926 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2927 (defvar iswitchb-temp-buflist)
2928 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2929 (defvar org-agenda-tags-todo-honor-ignore-options)
2930 (declare-function org-agenda-skip "org-agenda" ())
2931 (declare-function org-format-agenda-item "org-agenda"
2932 (extra txt &optional category tags dotime noprefix remove-re))
2933 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2934 (declare-function org-agenda-change-all-lines "org-agenda"
2935 (newhead hdmarker &optional fixface just-this))
2936 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2937 (declare-function org-agenda-maybe-redo "org-agenda" ())
2938 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2939 (beg end))
2940 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2941 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2942 "org-agenda" (&optional end))
2943 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
2944 (declare-function org-indent-mode "org-indent" (arg))
2945 (declare-function parse-time-string "parse-time" (string))
2946 (declare-function remember "remember" (&optional initial))
2947 (declare-function remember-buffer-desc "remember" ())
2948 (declare-function remember-finalize "remember" ())
2949 (defvar remember-save-after-remembering)
2950 (defvar remember-data-file)
2951 (defvar remember-register)
2952 (defvar remember-buffer)
2953 (defvar remember-handler-functions)
2954 (defvar remember-annotation-functions)
2955 (defvar texmathp-why)
2956 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2957 (declare-function table--at-cell-p "table" (position &optional object at-column))
2959 (defvar w3m-current-url)
2960 (defvar w3m-current-title)
2962 (defvar org-latex-regexps)
2964 ;;; Autoload and prepare some org modules
2966 ;; Some table stuff that needs to be defined here, because it is used
2967 ;; by the functions setting up org-mode or checking for table context.
2969 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2970 "Detects an org-type or table-type table.")
2971 (defconst org-table-line-regexp "^[ \t]*|"
2972 "Detects an org-type table line.")
2973 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2974 "Detects an org-type table line.")
2975 (defconst org-table-hline-regexp "^[ \t]*|-"
2976 "Detects an org-type table hline.")
2977 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2978 "Detects a table-type table hline.")
2979 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2980 "Searching from within a table (any type) this finds the first line
2981 outside the table.")
2983 ;; Autoload the functions in org-table.el that are needed by functions here.
2985 (eval-and-compile
2986 (org-autoload "org-table"
2987 '(org-table-align org-table-begin org-table-blank-field
2988 org-table-convert org-table-convert-region org-table-copy-down
2989 org-table-copy-region org-table-create
2990 org-table-create-or-convert-from-region
2991 org-table-create-with-table.el org-table-current-dline
2992 org-table-cut-region org-table-delete-column org-table-edit-field
2993 org-table-edit-formulas org-table-end org-table-eval-formula
2994 org-table-export org-table-field-info
2995 org-table-get-stored-formulas org-table-goto-column
2996 org-table-hline-and-move org-table-import org-table-insert-column
2997 org-table-insert-hline org-table-insert-row org-table-iterate
2998 org-table-justify-field-maybe org-table-kill-row
2999 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3000 org-table-move-column org-table-move-column-left
3001 org-table-move-column-right org-table-move-row
3002 org-table-move-row-down org-table-move-row-up
3003 org-table-next-field org-table-next-row org-table-paste-rectangle
3004 org-table-previous-field org-table-recalculate
3005 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3006 org-table-toggle-coordinate-overlays
3007 org-table-toggle-formula-debugger org-table-wrap-region
3008 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3010 (defun org-at-table-p (&optional table-type)
3011 "Return t if the cursor is inside an org-type table.
3012 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3013 (if org-enable-table-editor
3014 (save-excursion
3015 (beginning-of-line 1)
3016 (looking-at (if table-type org-table-any-line-regexp
3017 org-table-line-regexp)))
3018 nil))
3019 (defsubst org-table-p () (org-at-table-p))
3021 (defun org-at-table.el-p ()
3022 "Return t if and only if we are at a table.el table."
3023 (and (org-at-table-p 'any)
3024 (save-excursion
3025 (goto-char (org-table-begin 'any))
3026 (looking-at org-table1-hline-regexp))))
3027 (defun org-table-recognize-table.el ()
3028 "If there is a table.el table nearby, recognize it and move into it."
3029 (if org-table-tab-recognizes-table.el
3030 (if (org-at-table.el-p)
3031 (progn
3032 (beginning-of-line 1)
3033 (if (looking-at org-table-dataline-regexp)
3035 (if (looking-at org-table1-hline-regexp)
3036 (progn
3037 (beginning-of-line 2)
3038 (if (looking-at org-table-any-border-regexp)
3039 (beginning-of-line -1)))))
3040 (if (re-search-forward "|" (org-table-end t) t)
3041 (progn
3042 (require 'table)
3043 (if (table--at-cell-p (point))
3045 (message "recognizing table.el table...")
3046 (table-recognize-table)
3047 (message "recognizing table.el table...done")))
3048 (error "This should not happen..."))
3050 nil)
3051 nil))
3053 (defun org-at-table-hline-p ()
3054 "Return t if the cursor is inside a hline in a table."
3055 (if org-enable-table-editor
3056 (save-excursion
3057 (beginning-of-line 1)
3058 (looking-at org-table-hline-regexp))
3059 nil))
3061 (defvar org-table-clean-did-remove-column nil)
3063 (defun org-table-map-tables (function)
3064 "Apply FUNCTION to the start of all tables in the buffer."
3065 (save-excursion
3066 (save-restriction
3067 (widen)
3068 (goto-char (point-min))
3069 (while (re-search-forward org-table-any-line-regexp nil t)
3070 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3071 (beginning-of-line 1)
3072 (when (looking-at org-table-line-regexp)
3073 (save-excursion (funcall function))
3074 (or (looking-at org-table-line-regexp)
3075 (forward-char 1)))
3076 (re-search-forward org-table-any-border-regexp nil 1))))
3077 (message "Mapping tables: done"))
3079 ;; Declare and autoload functions from org-exp.el & Co
3081 (declare-function org-default-export-plist "org-exp")
3082 (declare-function org-infile-export-plist "org-exp")
3083 (declare-function org-get-current-options "org-exp")
3084 (eval-and-compile
3085 (org-autoload "org-exp"
3086 '(org-export org-export-visible
3087 org-insert-export-options-template
3088 org-table-clean-before-export))
3089 (org-autoload "org-ascii"
3090 '(org-export-as-ascii org-export-ascii-preprocess
3091 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3092 org-export-region-as-ascii))
3093 (org-autoload "org-html"
3094 '(org-export-as-html-and-open
3095 org-export-as-html-batch org-export-as-html-to-buffer
3096 org-replace-region-by-html org-export-region-as-html
3097 org-export-as-html))
3098 (org-autoload "org-icalendar"
3099 '(org-export-icalendar-this-file
3100 org-export-icalendar-all-agenda-files
3101 org-export-icalendar-combine-agenda-files))
3102 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3104 ;; Declare and autoload functions from org-agenda.el
3106 (eval-and-compile
3107 (org-autoload "org-agenda"
3108 '(org-agenda org-agenda-list org-search-view
3109 org-todo-list org-tags-view org-agenda-list-stuck-projects
3110 org-diary org-agenda-to-appt
3111 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3113 ;; Autoload org-remember
3115 (eval-and-compile
3116 (org-autoload "org-remember"
3117 '(org-remember-insinuate org-remember-annotation
3118 org-remember-apply-template org-remember org-remember-handler)))
3120 ;; Autoload org-clock.el
3123 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3124 (beg end))
3125 (declare-function org-clock-update-mode-line "org-clock" ())
3126 (defvar org-clock-start-time)
3127 (defvar org-clock-marker (make-marker)
3128 "Marker recording the last clock-in.")
3129 (defvar org-clock-hd-marker (make-marker)
3130 "Marker recording the last clock-in, but the headline position.")
3131 (defun org-clock-is-active ()
3132 "Return non-nil if clock is currently running.
3133 The return value is actually the clock marker."
3134 (marker-buffer org-clock-marker))
3136 (eval-and-compile
3137 (org-autoload
3138 "org-clock"
3139 '(org-clock-in org-clock-out org-clock-cancel
3140 org-clock-goto org-clock-sum org-clock-display
3141 org-clock-remove-overlays org-clock-report
3142 org-clocktable-shift org-dblock-write:clocktable
3143 org-get-clocktable)))
3145 (defun org-clock-update-time-maybe ()
3146 "If this is a CLOCK line, update it and return t.
3147 Otherwise, return nil."
3148 (interactive)
3149 (save-excursion
3150 (beginning-of-line 1)
3151 (skip-chars-forward " \t")
3152 (when (looking-at org-clock-string)
3153 (let ((re (concat "[ \t]*" org-clock-string
3154 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3155 "\\([ \t]*=>.*\\)?\\)?"))
3156 ts te h m s neg)
3157 (cond
3158 ((not (looking-at re))
3159 nil)
3160 ((not (match-end 2))
3161 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3162 (> org-clock-marker (point))
3163 (<= org-clock-marker (point-at-eol)))
3164 ;; The clock is running here
3165 (setq org-clock-start-time
3166 (apply 'encode-time
3167 (org-parse-time-string (match-string 1))))
3168 (org-clock-update-mode-line)))
3170 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3171 (end-of-line 1)
3172 (setq ts (match-string 1)
3173 te (match-string 3))
3174 (setq s (- (org-float-time
3175 (apply 'encode-time (org-parse-time-string te)))
3176 (org-float-time
3177 (apply 'encode-time (org-parse-time-string ts))))
3178 neg (< s 0)
3179 s (abs s)
3180 h (floor (/ s 3600))
3181 s (- s (* 3600 h))
3182 m (floor (/ s 60))
3183 s (- s (* 60 s)))
3184 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3185 t))))))
3187 (defun org-check-running-clock ()
3188 "Check if the current buffer contains the running clock.
3189 If yes, offer to stop it and to save the buffer with the changes."
3190 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3191 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3192 (buffer-name))))
3193 (org-clock-out)
3194 (when (y-or-n-p "Save changed buffer?")
3195 (save-buffer))))
3197 (defun org-clocktable-try-shift (dir n)
3198 "Check if this line starts a clock table, if yes, shift the time block."
3199 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3200 (org-clocktable-shift dir n)))
3202 ;; Autoload org-timer.el
3204 (eval-and-compile
3205 (org-autoload
3206 "org-timer"
3207 '(org-timer-start org-timer org-timer-item
3208 org-timer-change-times-in-region
3209 org-timer-set-timer
3210 org-timer-reset-timers
3211 org-timer-show-remaining-time)))
3213 ;; Autoload org-feed.el
3215 (eval-and-compile
3216 (org-autoload
3217 "org-feed"
3218 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3221 ;; Autoload org-indent.el
3223 (eval-and-compile
3224 (org-autoload
3225 "org-indent"
3226 '(org-indent-mode)))
3228 ;; Autoload org-mobile.el
3230 (eval-and-compile
3231 (org-autoload
3232 "org-mobile"
3233 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3235 ;; Autoload archiving code
3236 ;; The stuff that is needed for cycling and tags has to be defined here.
3238 (defgroup org-archive nil
3239 "Options concerning archiving in Org-mode."
3240 :tag "Org Archive"
3241 :group 'org-structure)
3243 (defcustom org-archive-location "%s_archive::"
3244 "The location where subtrees should be archived.
3246 The value of this variable is a string, consisting of two parts,
3247 separated by a double-colon. The first part is a filename and
3248 the second part is a headline.
3250 When the filename is omitted, archiving happens in the same file.
3251 %s in the filename will be replaced by the current file
3252 name (without the directory part). Archiving to a different file
3253 is useful to keep archived entries from contributing to the
3254 Org-mode Agenda.
3256 The archived entries will be filed as subtrees of the specified
3257 headline. When the headline is omitted, the subtrees are simply
3258 filed away at the end of the file, as top-level entries. Also in
3259 the heading you can use %s to represent the file name, this can be
3260 useful when using the same archive for a number of different files.
3262 Here are a few examples:
3263 \"%s_archive::\"
3264 If the current file is Projects.org, archive in file
3265 Projects.org_archive, as top-level trees. This is the default.
3267 \"::* Archived Tasks\"
3268 Archive in the current file, under the top-level headline
3269 \"* Archived Tasks\".
3271 \"~/org/archive.org::\"
3272 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3274 \"~/org/archive.org::From %s\"
3275 Archive in file ~/org/archive.org (absolute path), und headlines
3276 \"From FILENAME\" where file name is the current file name.
3278 \"basement::** Finished Tasks\"
3279 Archive in file ./basement (relative path), as level 3 trees
3280 below the level 2 heading \"** Finished Tasks\".
3282 You may set this option on a per-file basis by adding to the buffer a
3283 line like
3285 #+ARCHIVE: basement::** Finished Tasks
3287 You may also define it locally for a subtree by setting an ARCHIVE property
3288 in the entry. If such a property is found in an entry, or anywhere up
3289 the hierarchy, it will be used."
3290 :group 'org-archive
3291 :type 'string)
3293 (defcustom org-archive-tag "ARCHIVE"
3294 "The tag that marks a subtree as archived.
3295 An archived subtree does not open during visibility cycling, and does
3296 not contribute to the agenda listings.
3297 After changing this, font-lock must be restarted in the relevant buffers to
3298 get the proper fontification."
3299 :group 'org-archive
3300 :group 'org-keywords
3301 :type 'string)
3303 (defcustom org-agenda-skip-archived-trees t
3304 "Non-nil means, the agenda will skip any items located in archived trees.
3305 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3306 variable is no longer recommended, you should leave it at the value t.
3307 Instead, use the key `v' to cycle the archives-mode in the agenda."
3308 :group 'org-archive
3309 :group 'org-agenda-skip
3310 :type 'boolean)
3312 (defcustom org-columns-skip-arrchived-trees t
3313 "Non-nil means, irgnore archived trees when creating column view."
3314 :group 'org-archive
3315 :group 'org-properties
3316 :type 'boolean)
3318 (defcustom org-cycle-open-archived-trees nil
3319 "Non-nil means, `org-cycle' will open archived trees.
3320 An archived tree is a tree marked with the tag ARCHIVE.
3321 When nil, archived trees will stay folded. You can still open them with
3322 normal outline commands like `show-all', but not with the cycling commands."
3323 :group 'org-archive
3324 :group 'org-cycle
3325 :type 'boolean)
3327 (defcustom org-sparse-tree-open-archived-trees nil
3328 "Non-nil means sparse tree construction shows matches in archived trees.
3329 When nil, matches in these trees are highlighted, but the trees are kept in
3330 collapsed state."
3331 :group 'org-archive
3332 :group 'org-sparse-trees
3333 :type 'boolean)
3335 (defun org-cycle-hide-archived-subtrees (state)
3336 "Re-hide all archived subtrees after a visibility state change."
3337 (when (and (not org-cycle-open-archived-trees)
3338 (not (memq state '(overview folded))))
3339 (save-excursion
3340 (let* ((globalp (memq state '(contents all)))
3341 (beg (if globalp (point-min) (point)))
3342 (end (if globalp (point-max) (org-end-of-subtree t))))
3343 (org-hide-archived-subtrees beg end)
3344 (goto-char beg)
3345 (if (looking-at (concat ".*:" org-archive-tag ":"))
3346 (message "%s" (substitute-command-keys
3347 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3349 (defun org-force-cycle-archived ()
3350 "Cycle subtree even if it is archived."
3351 (interactive)
3352 (setq this-command 'org-cycle)
3353 (let ((org-cycle-open-archived-trees t))
3354 (call-interactively 'org-cycle)))
3356 (defun org-hide-archived-subtrees (beg end)
3357 "Re-hide all archived subtrees after a visibility state change."
3358 (save-excursion
3359 (let* ((re (concat ":" org-archive-tag ":")))
3360 (goto-char beg)
3361 (while (re-search-forward re end t)
3362 (and (org-on-heading-p) (hide-subtree))
3363 (org-end-of-subtree t)))))
3365 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3367 (eval-and-compile
3368 (org-autoload "org-archive"
3369 '(org-add-archive-files org-archive-subtree
3370 org-archive-to-archive-sibling org-toggle-archive-tag)))
3372 ;; Autoload Column View Code
3374 (declare-function org-columns-number-to-string "org-colview")
3375 (declare-function org-columns-get-format-and-top-level "org-colview")
3376 (declare-function org-columns-compute "org-colview")
3378 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3379 '(org-columns-number-to-string org-columns-get-format-and-top-level
3380 org-columns-compute org-agenda-columns org-columns-remove-overlays
3381 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3383 ;; Autoload ID code
3385 (declare-function org-id-store-link "org-id")
3386 (declare-function org-id-locations-load "org-id")
3387 (declare-function org-id-locations-save "org-id")
3388 (defvar org-id-track-globally)
3389 (org-autoload "org-id"
3390 '(org-id-get-create org-id-new org-id-copy org-id-get
3391 org-id-get-with-outline-path-completion
3392 org-id-get-with-outline-drilling
3393 org-id-goto org-id-find org-id-store-link))
3395 ;; Autoload Plotting Code
3397 (org-autoload "org-plot"
3398 '(org-plot/gnuplot))
3400 ;;; Variables for pre-computed regular expressions, all buffer local
3402 (defvar org-drawer-regexp nil
3403 "Matches first line of a hidden block.")
3404 (make-variable-buffer-local 'org-drawer-regexp)
3405 (defvar org-todo-regexp nil
3406 "Matches any of the TODO state keywords.")
3407 (make-variable-buffer-local 'org-todo-regexp)
3408 (defvar org-not-done-regexp nil
3409 "Matches any of the TODO state keywords except the last one.")
3410 (make-variable-buffer-local 'org-not-done-regexp)
3411 (defvar org-not-done-heading-regexp nil
3412 "Matches a TODO headline that is not done.")
3413 (make-variable-buffer-local 'org-not-done-regexp)
3414 (defvar org-todo-line-regexp nil
3415 "Matches a headline and puts TODO state into group 2 if present.")
3416 (make-variable-buffer-local 'org-todo-line-regexp)
3417 (defvar org-complex-heading-regexp nil
3418 "Matches a headline and puts everything into groups:
3419 group 1: the stars
3420 group 2: The todo keyword, maybe
3421 group 3: Priority cookie
3422 group 4: True headline
3423 group 5: Tags")
3424 (make-variable-buffer-local 'org-complex-heading-regexp)
3425 (defvar org-todo-line-tags-regexp nil
3426 "Matches a headline and puts TODO state into group 2 if present.
3427 Also put tags into group 4 if tags are present.")
3428 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3429 (defvar org-nl-done-regexp nil
3430 "Matches newline followed by a headline with the DONE keyword.")
3431 (make-variable-buffer-local 'org-nl-done-regexp)
3432 (defvar org-looking-at-done-regexp nil
3433 "Matches the DONE keyword a point.")
3434 (make-variable-buffer-local 'org-looking-at-done-regexp)
3435 (defvar org-ds-keyword-length 12
3436 "Maximum length of the Deadline and SCHEDULED keywords.")
3437 (make-variable-buffer-local 'org-ds-keyword-length)
3438 (defvar org-deadline-regexp nil
3439 "Matches the DEADLINE keyword.")
3440 (make-variable-buffer-local 'org-deadline-regexp)
3441 (defvar org-deadline-time-regexp nil
3442 "Matches the DEADLINE keyword together with a time stamp.")
3443 (make-variable-buffer-local 'org-deadline-time-regexp)
3444 (defvar org-deadline-line-regexp nil
3445 "Matches the DEADLINE keyword and the rest of the line.")
3446 (make-variable-buffer-local 'org-deadline-line-regexp)
3447 (defvar org-scheduled-regexp nil
3448 "Matches the SCHEDULED keyword.")
3449 (make-variable-buffer-local 'org-scheduled-regexp)
3450 (defvar org-scheduled-time-regexp nil
3451 "Matches the SCHEDULED keyword together with a time stamp.")
3452 (make-variable-buffer-local 'org-scheduled-time-regexp)
3453 (defvar org-closed-time-regexp nil
3454 "Matches the CLOSED keyword together with a time stamp.")
3455 (make-variable-buffer-local 'org-closed-time-regexp)
3457 (defvar org-keyword-time-regexp nil
3458 "Matches any of the 4 keywords, together with the time stamp.")
3459 (make-variable-buffer-local 'org-keyword-time-regexp)
3460 (defvar org-keyword-time-not-clock-regexp nil
3461 "Matches any of the 3 keywords, together with the time stamp.")
3462 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3463 (defvar org-maybe-keyword-time-regexp nil
3464 "Matches a timestamp, possibly preceeded by a keyword.")
3465 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3466 (defvar org-planning-or-clock-line-re nil
3467 "Matches a line with planning or clock info.")
3468 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3470 (defconst org-plain-time-of-day-regexp
3471 (concat
3472 "\\(\\<[012]?[0-9]"
3473 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3474 "\\(--?"
3475 "\\(\\<[012]?[0-9]"
3476 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3477 "\\)?")
3478 "Regular expression to match a plain time or time range.
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 1 the first time, range or not
3483 8 the second time, if it is a range.")
3485 (defconst org-plain-time-extension-regexp
3486 (concat
3487 "\\(\\<[012]?[0-9]"
3488 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3489 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3490 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3491 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3492 groups carry important information:
3493 0 the full match
3494 7 hours of duration
3495 9 minutes of duration")
3497 (defconst org-stamp-time-of-day-regexp
3498 (concat
3499 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3500 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3501 "\\(--?"
3502 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3503 "Regular expression to match a timestamp time or time range.
3504 After a match, the following groups carry important information:
3505 0 the full match
3506 1 date plus weekday, for backreferencing to make sure both times on same day
3507 2 the first time, range or not
3508 4 the second time, if it is a range.")
3510 (defconst org-startup-options
3511 '(("fold" org-startup-folded t)
3512 ("overview" org-startup-folded t)
3513 ("nofold" org-startup-folded nil)
3514 ("showall" org-startup-folded nil)
3515 ("showeverything" org-startup-folded showeverything)
3516 ("content" org-startup-folded content)
3517 ("indent" org-startup-indented t)
3518 ("noindent" org-startup-indented nil)
3519 ("hidestars" org-hide-leading-stars t)
3520 ("showstars" org-hide-leading-stars nil)
3521 ("odd" org-odd-levels-only t)
3522 ("oddeven" org-odd-levels-only nil)
3523 ("align" org-startup-align-all-tables t)
3524 ("noalign" org-startup-align-all-tables nil)
3525 ("customtime" org-display-custom-times t)
3526 ("logdone" org-log-done time)
3527 ("lognotedone" org-log-done note)
3528 ("nologdone" org-log-done nil)
3529 ("lognoteclock-out" org-log-note-clock-out t)
3530 ("nolognoteclock-out" org-log-note-clock-out nil)
3531 ("logrepeat" org-log-repeat state)
3532 ("lognoterepeat" org-log-repeat note)
3533 ("nologrepeat" org-log-repeat nil)
3534 ("fninline" org-footnote-define-inline t)
3535 ("nofninline" org-footnote-define-inline nil)
3536 ("fnlocal" org-footnote-section nil)
3537 ("fnauto" org-footnote-auto-label t)
3538 ("fnprompt" org-footnote-auto-label nil)
3539 ("fnconfirm" org-footnote-auto-label confirm)
3540 ("fnplain" org-footnote-auto-label plain)
3541 ("fnadjust" org-footnote-auto-adjust t)
3542 ("nofnadjust" org-footnote-auto-adjust nil)
3543 ("constcgs" constants-unit-system cgs)
3544 ("constSI" constants-unit-system SI)
3545 ("noptag" org-tag-persistent-alist nil)
3546 ("hideblocks" org-hide-block-startup t)
3547 ("nohideblocks" org-hide-block-startup nil))
3548 "Variable associated with STARTUP options for org-mode.
3549 Each element is a list of three items: The startup options as written
3550 in the #+STARTUP line, the corresponding variable, and the value to
3551 set this variable to if the option is found. An optional forth element PUSH
3552 means to push this value onto the list in the variable.")
3554 (defun org-set-regexps-and-options ()
3555 "Precompute regular expressions for current buffer."
3556 (when (org-mode-p)
3557 (org-set-local 'org-todo-kwd-alist nil)
3558 (org-set-local 'org-todo-key-alist nil)
3559 (org-set-local 'org-todo-key-trigger nil)
3560 (org-set-local 'org-todo-keywords-1 nil)
3561 (org-set-local 'org-done-keywords nil)
3562 (org-set-local 'org-todo-heads nil)
3563 (org-set-local 'org-todo-sets nil)
3564 (org-set-local 'org-todo-log-states nil)
3565 (org-set-local 'org-file-properties nil)
3566 (org-set-local 'org-file-tags nil)
3567 (let ((re (org-make-options-regexp
3568 '("CATEGORY" "TODO" "COLUMNS"
3569 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3570 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3571 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3572 (splitre "[ \t]+")
3573 kwds kws0 kwsa key log value cat arch tags const links hw dws
3574 tail sep kws1 prio props ftags drawers
3575 ext-setup-or-nil setup-contents (start 0))
3576 (save-excursion
3577 (save-restriction
3578 (widen)
3579 (goto-char (point-min))
3580 (while (or (and ext-setup-or-nil
3581 (string-match re ext-setup-or-nil start)
3582 (setq start (match-end 0)))
3583 (and (setq ext-setup-or-nil nil start 0)
3584 (re-search-forward re nil t)))
3585 (setq key (upcase (match-string 1 ext-setup-or-nil))
3586 value (org-match-string-no-properties 2 ext-setup-or-nil))
3587 (cond
3588 ((equal key "CATEGORY")
3589 (if (string-match "[ \t]+$" value)
3590 (setq value (replace-match "" t t value)))
3591 (setq cat value))
3592 ((member key '("SEQ_TODO" "TODO"))
3593 (push (cons 'sequence (org-split-string value splitre)) kwds))
3594 ((equal key "TYP_TODO")
3595 (push (cons 'type (org-split-string value splitre)) kwds))
3596 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3597 ;; general TODO-like setup
3598 (push (cons (intern (downcase (match-string 1 key)))
3599 (org-split-string value splitre)) kwds))
3600 ((equal key "TAGS")
3601 (setq tags (append tags (if tags '("\\n") nil)
3602 (org-split-string value splitre))))
3603 ((equal key "COLUMNS")
3604 (org-set-local 'org-columns-default-format value))
3605 ((equal key "LINK")
3606 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3607 (push (cons (match-string 1 value)
3608 (org-trim (match-string 2 value)))
3609 links)))
3610 ((equal key "PRIORITIES")
3611 (setq prio (org-split-string value " +")))
3612 ((equal key "PROPERTY")
3613 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3614 (push (cons (match-string 1 value) (match-string 2 value))
3615 props)))
3616 ((equal key "FILETAGS")
3617 (when (string-match "\\S-" value)
3618 (setq ftags
3619 (append
3620 ftags
3621 (apply 'append
3622 (mapcar (lambda (x) (org-split-string x ":"))
3623 (org-split-string value)))))))
3624 ((equal key "DRAWERS")
3625 (setq drawers (org-split-string value splitre)))
3626 ((equal key "CONSTANTS")
3627 (setq const (append const (org-split-string value splitre))))
3628 ((equal key "STARTUP")
3629 (let ((opts (org-split-string value splitre))
3630 l var val)
3631 (while (setq l (pop opts))
3632 (when (setq l (assoc l org-startup-options))
3633 (setq var (nth 1 l) val (nth 2 l))
3634 (if (not (nth 3 l))
3635 (set (make-local-variable var) val)
3636 (if (not (listp (symbol-value var)))
3637 (set (make-local-variable var) nil))
3638 (set (make-local-variable var) (symbol-value var))
3639 (add-to-list var val))))))
3640 ((equal key "ARCHIVE")
3641 (string-match " *$" value)
3642 (setq arch (replace-match "" t t value))
3643 (remove-text-properties 0 (length arch)
3644 '(face t fontified t) arch))
3645 ((equal key "SETUPFILE")
3646 (setq setup-contents (org-file-contents
3647 (expand-file-name
3648 (org-remove-double-quotes value))
3649 'noerror))
3650 (if (not ext-setup-or-nil)
3651 (setq ext-setup-or-nil setup-contents start 0)
3652 (setq ext-setup-or-nil
3653 (concat (substring ext-setup-or-nil 0 start)
3654 "\n" setup-contents "\n"
3655 (substring ext-setup-or-nil start)))))
3656 ))))
3657 (when cat
3658 (org-set-local 'org-category (intern cat))
3659 (push (cons "CATEGORY" cat) props))
3660 (when prio
3661 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3662 (setq prio (mapcar 'string-to-char prio))
3663 (org-set-local 'org-highest-priority (nth 0 prio))
3664 (org-set-local 'org-lowest-priority (nth 1 prio))
3665 (org-set-local 'org-default-priority (nth 2 prio)))
3666 (and props (org-set-local 'org-file-properties (nreverse props)))
3667 (and ftags (org-set-local 'org-file-tags
3668 (mapcar 'org-add-prop-inherited ftags)))
3669 (and drawers (org-set-local 'org-drawers drawers))
3670 (and arch (org-set-local 'org-archive-location arch))
3671 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3672 ;; Process the TODO keywords
3673 (unless kwds
3674 ;; Use the global values as if they had been given locally.
3675 (setq kwds (default-value 'org-todo-keywords))
3676 (if (stringp (car kwds))
3677 (setq kwds (list (cons org-todo-interpretation
3678 (default-value 'org-todo-keywords)))))
3679 (setq kwds (reverse kwds)))
3680 (setq kwds (nreverse kwds))
3681 (let (inter kws kw)
3682 (while (setq kws (pop kwds))
3683 (let ((kws (or
3684 (run-hook-with-args-until-success
3685 'org-todo-setup-filter-hook kws)
3686 kws)))
3687 (setq inter (pop kws) sep (member "|" kws)
3688 kws0 (delete "|" (copy-sequence kws))
3689 kwsa nil
3690 kws1 (mapcar
3691 (lambda (x)
3692 ;; 1 2
3693 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3694 (progn
3695 (setq kw (match-string 1 x)
3696 key (and (match-end 2) (match-string 2 x))
3697 log (org-extract-log-state-settings x))
3698 (push (cons kw (and key (string-to-char key))) kwsa)
3699 (and log (push log org-todo-log-states))
3701 (error "Invalid TODO keyword %s" x)))
3702 kws0)
3703 kwsa (if kwsa (append '((:startgroup))
3704 (nreverse kwsa)
3705 '((:endgroup))))
3706 hw (car kws1)
3707 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3708 tail (list inter hw (car dws) (org-last dws))))
3709 (add-to-list 'org-todo-heads hw 'append)
3710 (push kws1 org-todo-sets)
3711 (setq org-done-keywords (append org-done-keywords dws nil))
3712 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3713 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3714 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3715 (setq org-todo-sets (nreverse org-todo-sets)
3716 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3717 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3718 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3719 ;; Process the constants
3720 (when const
3721 (let (e cst)
3722 (while (setq e (pop const))
3723 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3724 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3725 (setq org-table-formula-constants-local cst)))
3727 ;; Process the tags.
3728 (when tags
3729 (let (e tgs)
3730 (while (setq e (pop tags))
3731 (cond
3732 ((equal e "{") (push '(:startgroup) tgs))
3733 ((equal e "}") (push '(:endgroup) tgs))
3734 ((equal e "\\n") (push '(:newline) tgs))
3735 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3736 (push (cons (match-string 1 e)
3737 (string-to-char (match-string 2 e)))
3738 tgs))
3739 (t (push (list e) tgs))))
3740 (org-set-local 'org-tag-alist nil)
3741 (while (setq e (pop tgs))
3742 (or (and (stringp (car e))
3743 (assoc (car e) org-tag-alist))
3744 (push e org-tag-alist)))))
3746 ;; Compute the regular expressions and other local variables
3747 (if (not org-done-keywords)
3748 (setq org-done-keywords (and org-todo-keywords-1
3749 (list (org-last org-todo-keywords-1)))))
3750 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3751 (length org-scheduled-string)
3752 (length org-clock-string)
3753 (length org-closed-string)))
3754 org-drawer-regexp
3755 (concat "^[ \t]*:\\("
3756 (mapconcat 'regexp-quote org-drawers "\\|")
3757 "\\):[ \t]*$")
3758 org-not-done-keywords
3759 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3760 org-todo-regexp
3761 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3762 "\\|") "\\)\\>")
3763 org-not-done-regexp
3764 (concat "\\<\\("
3765 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3766 "\\)\\>")
3767 org-not-done-heading-regexp
3768 (concat "^\\(\\*+\\)[ \t]+\\("
3769 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3770 "\\)\\>")
3771 org-todo-line-regexp
3772 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3773 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3774 "\\)\\>\\)?[ \t]*\\(.*\\)")
3775 org-complex-heading-regexp
3776 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3777 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3778 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3779 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3780 org-nl-done-regexp
3781 (concat "\n\\*+[ \t]+"
3782 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3783 "\\)" "\\>")
3784 org-todo-line-tags-regexp
3785 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3786 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3787 (org-re
3788 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3789 org-looking-at-done-regexp
3790 (concat "^" "\\(?:"
3791 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3792 "\\>")
3793 org-deadline-regexp (concat "\\<" org-deadline-string)
3794 org-deadline-time-regexp
3795 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3796 org-deadline-line-regexp
3797 (concat "\\<\\(" org-deadline-string "\\).*")
3798 org-scheduled-regexp
3799 (concat "\\<" org-scheduled-string)
3800 org-scheduled-time-regexp
3801 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3802 org-closed-time-regexp
3803 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3804 org-keyword-time-regexp
3805 (concat "\\<\\(" org-scheduled-string
3806 "\\|" org-deadline-string
3807 "\\|" org-closed-string
3808 "\\|" org-clock-string "\\)"
3809 " *[[<]\\([^]>]+\\)[]>]")
3810 org-keyword-time-not-clock-regexp
3811 (concat "\\<\\(" org-scheduled-string
3812 "\\|" org-deadline-string
3813 "\\|" org-closed-string
3814 "\\)"
3815 " *[[<]\\([^]>]+\\)[]>]")
3816 org-maybe-keyword-time-regexp
3817 (concat "\\(\\<\\(" org-scheduled-string
3818 "\\|" org-deadline-string
3819 "\\|" org-closed-string
3820 "\\|" org-clock-string "\\)\\)?"
3821 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3822 org-planning-or-clock-line-re
3823 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3824 "\\|" org-deadline-string
3825 "\\|" org-closed-string "\\|" org-clock-string
3826 "\\)\\>\\)")
3828 (org-compute-latex-and-specials-regexp)
3829 (org-set-font-lock-defaults))))
3831 (defun org-file-contents (file &optional noerror)
3832 "Return the contents of FILE, as a string."
3833 (if (or (not file)
3834 (not (file-readable-p file)))
3835 (if noerror
3836 (progn
3837 (message "Cannot read file %s" file)
3838 (ding) (sit-for 2)
3840 (error "Cannot read file %s" file))
3841 (with-temp-buffer
3842 (insert-file-contents file)
3843 (buffer-string))))
3845 (defun org-extract-log-state-settings (x)
3846 "Extract the log state setting from a TODO keyword string.
3847 This will extract info from a string like \"WAIT(w@/!)\"."
3848 (let (kw key log1 log2)
3849 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3850 (setq kw (match-string 1 x)
3851 key (and (match-end 2) (match-string 2 x))
3852 log1 (and (match-end 3) (match-string 3 x))
3853 log2 (and (match-end 4) (match-string 4 x)))
3854 (and (or log1 log2)
3855 (list kw
3856 (and log1 (if (equal log1 "!") 'time 'note))
3857 (and log2 (if (equal log2 "!") 'time 'note)))))))
3859 (defun org-remove-keyword-keys (list)
3860 "Remove a pair of parenthesis at the end of each string in LIST."
3861 (mapcar (lambda (x)
3862 (if (string-match "(.*)$" x)
3863 (substring x 0 (match-beginning 0))
3865 list))
3867 ;; FIXME: this could be done much better, using second characters etc.
3868 (defun org-assign-fast-keys (alist)
3869 "Assign fast keys to a keyword-key alist.
3870 Respect keys that are already there."
3871 (let (new e k c c1 c2 (char ?a))
3872 (while (setq e (pop alist))
3873 (cond
3874 ((equal e '(:startgroup)) (push e new))
3875 ((equal e '(:endgroup)) (push e new))
3876 ((equal e '(:newline)) (push e new))
3878 (setq k (car e) c2 nil)
3879 (if (cdr e)
3880 (setq c (cdr e))
3881 ;; automatically assign a character.
3882 (setq c1 (string-to-char
3883 (downcase (substring
3884 k (if (= (string-to-char k) ?@) 1 0)))))
3885 (if (or (rassoc c1 new) (rassoc c1 alist))
3886 (while (or (rassoc char new) (rassoc char alist))
3887 (setq char (1+ char)))
3888 (setq c2 c1))
3889 (setq c (or c2 char)))
3890 (push (cons k c) new))))
3891 (nreverse new)))
3893 ;;; Some variables used in various places
3895 (defvar org-window-configuration nil
3896 "Used in various places to store a window configuration.")
3897 (defvar org-selected-window nil
3898 "Used in various places to store a window configuration.")
3899 (defvar org-finish-function nil
3900 "Function to be called when `C-c C-c' is used.
3901 This is for getting out of special buffers like remember.")
3904 ;; FIXME: Occasionally check by commenting these, to make sure
3905 ;; no other functions uses these, forgetting to let-bind them.
3906 (defvar entry)
3907 (defvar last-state)
3908 (defvar date)
3910 ;; Defined somewhere in this file, but used before definition.
3911 (defvar org-html-entities)
3912 (defvar org-struct-menu)
3913 (defvar org-org-menu)
3914 (defvar org-tbl-menu)
3915 (defvar org-agenda-keymap)
3917 ;;;; Define the Org-mode
3919 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3920 (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."))
3923 ;; We use a before-change function to check if a table might need
3924 ;; an update.
3925 (defvar org-table-may-need-update t
3926 "Indicates that a table might need an update.
3927 This variable is set by `org-before-change-function'.
3928 `org-table-align' sets it back to nil.")
3929 (defun org-before-change-function (beg end)
3930 "Every change indicates that a table might need an update."
3931 (setq org-table-may-need-update t))
3932 (defvar org-mode-map)
3933 (defvar org-mode-hook nil
3934 "Mode hook for Org-mode, run after the mode was turned on.")
3935 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3936 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3937 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3938 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3939 (defvar org-table-buffer-is-an nil)
3940 (defconst org-outline-regexp "\\*+ ")
3942 ;;;###autoload
3943 (define-derived-mode org-mode outline-mode "Org"
3944 "Outline-based notes management and organizer, alias
3945 \"Carsten's outline-mode for keeping track of everything.\"
3947 Org-mode develops organizational tasks around a NOTES file which
3948 contains information about projects as plain text. Org-mode is
3949 implemented on top of outline-mode, which is ideal to keep the content
3950 of large files well structured. It supports ToDo items, deadlines and
3951 time stamps, which magically appear in the diary listing of the Emacs
3952 calendar. Tables are easily created with a built-in table editor.
3953 Plain text URL-like links connect to websites, emails (VM), Usenet
3954 messages (Gnus), BBDB entries, and any files related to the project.
3955 For printing and sharing of notes, an Org-mode file (or a part of it)
3956 can be exported as a structured ASCII or HTML file.
3958 The following commands are available:
3960 \\{org-mode-map}"
3962 ;; Get rid of Outline menus, they are not needed
3963 ;; Need to do this here because define-derived-mode sets up
3964 ;; the keymap so late. Still, it is a waste to call this each time
3965 ;; we switch another buffer into org-mode.
3966 (if (featurep 'xemacs)
3967 (when (boundp 'outline-mode-menu-heading)
3968 ;; Assume this is Greg's port, it used easymenu
3969 (easy-menu-remove outline-mode-menu-heading)
3970 (easy-menu-remove outline-mode-menu-show)
3971 (easy-menu-remove outline-mode-menu-hide))
3972 (define-key org-mode-map [menu-bar headings] 'undefined)
3973 (define-key org-mode-map [menu-bar hide] 'undefined)
3974 (define-key org-mode-map [menu-bar show] 'undefined))
3976 (org-load-modules-maybe)
3977 (easy-menu-add org-org-menu)
3978 (easy-menu-add org-tbl-menu)
3979 (org-install-agenda-files-menu)
3980 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3981 (org-add-to-invisibility-spec '(org-cwidth))
3982 (org-add-to-invisibility-spec '(org-hide-block . t))
3983 (when (featurep 'xemacs)
3984 (org-set-local 'line-move-ignore-invisible t))
3985 (org-set-local 'outline-regexp org-outline-regexp)
3986 (org-set-local 'outline-level 'org-outline-level)
3987 (when (and org-ellipsis
3988 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3989 (fboundp 'make-glyph-code))
3990 (unless org-display-table
3991 (setq org-display-table (make-display-table)))
3992 (set-display-table-slot
3993 org-display-table 4
3994 (vconcat (mapcar
3995 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3996 org-ellipsis)))
3997 (if (stringp org-ellipsis) org-ellipsis "..."))))
3998 (setq buffer-display-table org-display-table))
3999 (org-set-regexps-and-options)
4000 (when (and org-tag-faces (not org-tags-special-faces-re))
4001 ;; tag faces set outside customize.... force initialization.
4002 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4003 ;; Calc embedded
4004 (org-set-local 'calc-embedded-open-mode "# ")
4005 (modify-syntax-entry ?# "<")
4006 (modify-syntax-entry ?@ "w")
4007 (if org-startup-truncated (setq truncate-lines t))
4008 (org-set-local 'font-lock-unfontify-region-function
4009 'org-unfontify-region)
4010 ;; Activate before-change-function
4011 (org-set-local 'org-table-may-need-update t)
4012 (org-add-hook 'before-change-functions 'org-before-change-function nil
4013 'local)
4014 ;; Check for running clock before killing a buffer
4015 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4016 ;; Paragraphs and auto-filling
4017 (org-set-autofill-regexps)
4018 (setq indent-line-function 'org-indent-line-function)
4019 (org-update-radio-target-regexp)
4020 ;; Make sure dependence stuff works reliably, even for users who set it
4021 ;; too late :-(
4022 (if org-enforce-todo-dependencies
4023 (add-hook 'org-blocker-hook
4024 'org-block-todo-from-children-or-siblings-or-parent)
4025 (remove-hook 'org-blocker-hook
4026 'org-block-todo-from-children-or-siblings-or-parent))
4027 (if org-enforce-todo-checkbox-dependencies
4028 (add-hook 'org-blocker-hook
4029 'org-block-todo-from-checkboxes)
4030 (remove-hook 'org-blocker-hook
4031 'org-block-todo-from-checkboxes))
4033 ;; Comment characters
4034 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4035 (org-set-local 'comment-padding " ")
4037 ;; Align options lines
4038 (org-set-local
4039 'align-mode-rules-list
4040 '((org-in-buffer-settings
4041 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4042 (modes . '(org-mode)))))
4044 ;; Imenu
4045 (org-set-local 'imenu-create-index-function
4046 'org-imenu-get-tree)
4048 ;; Make isearch reveal context
4049 (if (or (featurep 'xemacs)
4050 (not (boundp 'outline-isearch-open-invisible-function)))
4051 ;; Emacs 21 and XEmacs make use of the hook
4052 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4053 ;; Emacs 22 deals with this through a special variable
4054 (org-set-local 'outline-isearch-open-invisible-function
4055 (lambda (&rest ignore) (org-show-context 'isearch))))
4057 ;; If empty file that did not turn on org-mode automatically, make it to.
4058 (if (and org-insert-mode-line-in-empty-file
4059 (interactive-p)
4060 (= (point-min) (point-max)))
4061 (insert "# -*- mode: org -*-\n\n"))
4063 (unless org-inhibit-startup
4064 (when org-startup-align-all-tables
4065 (let ((bmp (buffer-modified-p)))
4066 (org-table-map-tables 'org-table-align)
4067 (set-buffer-modified-p bmp)))
4068 (when org-startup-indented
4069 (require 'org-indent)
4070 (org-indent-mode 1))
4071 (org-set-startup-visibility)))
4073 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4075 (defun org-current-time ()
4076 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4077 (if (> (car org-time-stamp-rounding-minutes) 1)
4078 (let ((r (car org-time-stamp-rounding-minutes))
4079 (time (decode-time)))
4080 (apply 'encode-time
4081 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4082 (nthcdr 2 time))))
4083 (current-time)))
4085 ;;;; Font-Lock stuff, including the activators
4087 (defvar org-mouse-map (make-sparse-keymap))
4088 (org-defkey org-mouse-map
4089 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4090 (org-defkey org-mouse-map
4091 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4092 (when org-mouse-1-follows-link
4093 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4094 (when org-tab-follows-link
4095 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4096 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4098 (require 'font-lock)
4100 (defconst org-non-link-chars "]\t\n\r<>")
4101 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4102 "shell" "elisp"))
4103 (defvar org-link-types-re nil
4104 "Matches a link that has a url-like prefix like \"http:\"")
4105 (defvar org-link-re-with-space nil
4106 "Matches a link with spaces, optional angular brackets around it.")
4107 (defvar org-link-re-with-space2 nil
4108 "Matches a link with spaces, optional angular brackets around it.")
4109 (defvar org-link-re-with-space3 nil
4110 "Matches a link with spaces, only for internal part in bracket links.")
4111 (defvar org-angle-link-re nil
4112 "Matches link with angular brackets, spaces are allowed.")
4113 (defvar org-plain-link-re nil
4114 "Matches plain link, without spaces.")
4115 (defvar org-bracket-link-regexp nil
4116 "Matches a link in double brackets.")
4117 (defvar org-bracket-link-analytic-regexp nil
4118 "Regular expression used to analyze links.
4119 Here is what the match groups contain after a match:
4120 1: http:
4121 2: http
4122 3: path
4123 4: [desc]
4124 5: desc")
4125 (defvar org-bracket-link-analytic-regexp++ nil
4126 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4127 (defvar org-any-link-re nil
4128 "Regular expression matching any link.")
4130 (defun org-make-link-regexps ()
4131 "Update the link regular expressions.
4132 This should be called after the variable `org-link-types' has changed."
4133 (setq org-link-types-re
4134 (concat
4135 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4136 org-link-re-with-space
4137 (concat
4138 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4139 "\\([^" org-non-link-chars " ]"
4140 "[^" org-non-link-chars "]*"
4141 "[^" org-non-link-chars " ]\\)>?")
4142 org-link-re-with-space2
4143 (concat
4144 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4145 "\\([^" org-non-link-chars " ]"
4146 "[^\t\n\r]*"
4147 "[^" org-non-link-chars " ]\\)>?")
4148 org-link-re-with-space3
4149 (concat
4150 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4151 "\\([^" org-non-link-chars " ]"
4152 "[^\t\n\r]*\\)")
4153 org-angle-link-re
4154 (concat
4155 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4156 "\\([^" org-non-link-chars " ]"
4157 "[^" org-non-link-chars "]*"
4158 "\\)>")
4159 org-plain-link-re
4160 (concat
4161 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4162 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4163 org-bracket-link-regexp
4164 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4165 org-bracket-link-analytic-regexp
4166 (concat
4167 "\\[\\["
4168 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4169 "\\([^]]+\\)"
4170 "\\]"
4171 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4172 "\\]")
4173 org-bracket-link-analytic-regexp++
4174 (concat
4175 "\\[\\["
4176 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4177 "\\([^]]+\\)"
4178 "\\]"
4179 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4180 "\\]")
4181 org-any-link-re
4182 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4183 org-angle-link-re "\\)\\|\\("
4184 org-plain-link-re "\\)")))
4186 (org-make-link-regexps)
4188 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4189 "Regular expression for fast time stamp matching.")
4190 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4191 "Regular expression for fast time stamp matching.")
4192 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4193 "Regular expression matching time strings for analysis.
4194 This one does not require the space after the date, so it can be used
4195 on a string that terminates immediately after the date.")
4196 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4197 "Regular expression matching time strings for analysis.")
4198 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4199 "Regular expression matching time stamps, with groups.")
4200 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4201 "Regular expression matching time stamps (also [..]), with groups.")
4202 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4203 "Regular expression matching a time stamp range.")
4204 (defconst org-tr-regexp-both
4205 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4206 "Regular expression matching a time stamp range.")
4207 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4208 org-ts-regexp "\\)?")
4209 "Regular expression matching a time stamp or time stamp range.")
4210 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4211 org-ts-regexp-both "\\)?")
4212 "Regular expression matching a time stamp or time stamp range.
4213 The time stamps may be either active or inactive.")
4215 (defvar org-emph-face nil)
4217 (defun org-do-emphasis-faces (limit)
4218 "Run through the buffer and add overlays to links."
4219 (let (rtn a)
4220 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4221 (if (not (= (char-after (match-beginning 3))
4222 (char-after (match-beginning 4))))
4223 (progn
4224 (setq rtn t)
4225 (setq a (assoc (match-string 3) org-emphasis-alist))
4226 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4227 'face
4228 (nth 1 a))
4229 (and (nth 4 a)
4230 (org-remove-flyspell-overlays-in
4231 (match-beginning 0) (match-end 0)))
4232 (add-text-properties (match-beginning 2) (match-end 2)
4233 '(font-lock-multiline t))
4234 (when org-hide-emphasis-markers
4235 (add-text-properties (match-end 4) (match-beginning 5)
4236 '(invisible org-link))
4237 (add-text-properties (match-beginning 3) (match-end 3)
4238 '(invisible org-link)))))
4239 (backward-char 1))
4240 rtn))
4242 (defun org-emphasize (&optional char)
4243 "Insert or change an emphasis, i.e. a font like bold or italic.
4244 If there is an active region, change that region to a new emphasis.
4245 If there is no region, just insert the marker characters and position
4246 the cursor between them.
4247 CHAR should be either the marker character, or the first character of the
4248 HTML tag associated with that emphasis. If CHAR is a space, the means
4249 to remove the emphasis of the selected region.
4250 If char is not given (for example in an interactive call) it
4251 will be prompted for."
4252 (interactive)
4253 (let ((eal org-emphasis-alist) e det
4254 (erc org-emphasis-regexp-components)
4255 (prompt "")
4256 (string "") beg end move tag c s)
4257 (if (org-region-active-p)
4258 (setq beg (region-beginning) end (region-end)
4259 string (buffer-substring beg end))
4260 (setq move t))
4262 (while (setq e (pop eal))
4263 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4264 c (aref tag 0))
4265 (push (cons c (string-to-char (car e))) det)
4266 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4267 (substring tag 1)))))
4268 (setq det (nreverse det))
4269 (unless char
4270 (message "%s" (concat "Emphasis marker or tag:" prompt))
4271 (setq char (read-char-exclusive)))
4272 (setq char (or (cdr (assoc char det)) char))
4273 (if (equal char ?\ )
4274 (setq s "" move nil)
4275 (unless (assoc (char-to-string char) org-emphasis-alist)
4276 (error "No such emphasis marker: \"%c\"" char))
4277 (setq s (char-to-string char)))
4278 (while (and (> (length string) 1)
4279 (equal (substring string 0 1) (substring string -1))
4280 (assoc (substring string 0 1) org-emphasis-alist))
4281 (setq string (substring string 1 -1)))
4282 (setq string (concat s string s))
4283 (if beg (delete-region beg end))
4284 (unless (or (bolp)
4285 (string-match (concat "[" (nth 0 erc) "\n]")
4286 (char-to-string (char-before (point)))))
4287 (insert " "))
4288 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4289 (char-to-string (char-after (point))))
4290 (insert " ") (backward-char 1))
4291 (insert string)
4292 (and move (backward-char 1))))
4294 (defconst org-nonsticky-props
4295 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4297 (defsubst org-rear-nonsticky-at (pos)
4298 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4300 (defun org-activate-plain-links (limit)
4301 "Run through the buffer and add overlays to links."
4302 (catch 'exit
4303 (let (f)
4304 (if (re-search-forward org-plain-link-re limit t)
4305 (progn
4306 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4307 (setq f (get-text-property (match-beginning 0) 'face))
4308 (if (or (eq f 'org-tag)
4309 (and (listp f) (memq 'org-tag f)))
4311 (add-text-properties (match-beginning 0) (match-end 0)
4312 (list 'mouse-face 'highlight
4313 'keymap org-mouse-map))
4314 (org-rear-nonsticky-at (match-end 0)))
4315 t)))))
4317 (defun org-activate-code (limit)
4318 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4319 (progn
4320 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4321 (remove-text-properties (match-beginning 0) (match-end 0)
4322 '(display t invisible t intangible t))
4323 t)))
4325 (defun org-fontify-meta-lines-and-blocks (limit)
4326 "Fontify #+ lines and blocks, in the correct ways."
4327 (let ((case-fold-search t))
4328 (if (re-search-forward
4329 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4330 limit t)
4331 (let ((beg (match-beginning 0))
4332 (beg1 (line-beginning-position 2))
4333 (dc1 (downcase (match-string 2)))
4334 (dc3 (downcase (match-string 3)))
4335 end end1 quoting)
4336 (cond
4337 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4338 ;; a single line of backend-specific content
4339 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4340 (remove-text-properties (match-beginning 0) (match-end 0)
4341 '(display t invisible t intangible t))
4342 (add-text-properties (match-beginning 1) (match-end 3)
4343 '(font-lock-fontified t face org-meta-line))
4344 (add-text-properties (match-beginning 6) (match-end 6)
4345 '(font-lock-fontified t face org-block))
4347 ((and (match-end 4) (equal dc3 "begin"))
4348 ;; Truely a block
4349 (setq quoting (member (downcase (match-string 5))
4350 org-protecting-blocks))
4351 (when (re-search-forward
4352 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4353 nil t) ;; on purpose, we look further than LIMIT
4354 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4355 (when quoting
4356 (remove-text-properties beg end
4357 '(display t invisible t intangible t)))
4358 (add-text-properties
4359 beg end
4360 '(font-lock-fontified t font-lock-multiline t))
4361 (add-text-properties beg beg1 '(face org-meta-line))
4362 (add-text-properties end1 end '(face org-meta-line))
4363 (when quoting
4364 (add-text-properties beg1 end1 '(face org-block)))
4366 ((not (member (char-after beg) '(?\ ?\t)))
4367 ;; just any other in-buffer setting, but not indented
4368 (add-text-properties
4369 beg (match-end 0)
4370 '(font-lock-fontified t face org-meta-line))
4372 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4373 "orgtbl:" "tblfm:" "tblname:"))
4374 (and (match-end 4) (equal dc3 "attr")))
4375 (add-text-properties
4376 beg (match-end 0)
4377 '(font-lock-fontified t face org-meta-line))
4379 (t nil))))))
4381 (defun org-activate-angle-links (limit)
4382 "Run through the buffer and add overlays to links."
4383 (if (re-search-forward org-angle-link-re limit t)
4384 (progn
4385 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4386 (add-text-properties (match-beginning 0) (match-end 0)
4387 (list 'mouse-face 'highlight
4388 'keymap org-mouse-map))
4389 (org-rear-nonsticky-at (match-end 0))
4390 t)))
4392 (defun org-activate-footnote-links (limit)
4393 "Run through the buffer and add overlays to links."
4394 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4395 limit t)
4396 (progn
4397 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4398 (add-text-properties (match-beginning 2) (match-end 2)
4399 (list 'mouse-face 'highlight
4400 'keymap org-mouse-map
4401 'help-echo
4402 (if (= (point-at-bol) (match-beginning 2))
4403 "Footnote definition"
4404 "Footnote reference")
4406 (org-rear-nonsticky-at (match-end 2))
4407 t)))
4409 (defun org-activate-bracket-links (limit)
4410 "Run through the buffer and add overlays to bracketed links."
4411 (if (re-search-forward org-bracket-link-regexp limit t)
4412 (let* ((help (concat "LINK: "
4413 (org-match-string-no-properties 1)))
4414 ;; FIXME: above we should remove the escapes.
4415 ;; but that requires another match, protecting match data,
4416 ;; a lot of overhead for font-lock.
4417 (ip (org-maybe-intangible
4418 (list 'invisible 'org-link
4419 'keymap org-mouse-map 'mouse-face 'highlight
4420 'font-lock-multiline t 'help-echo help)))
4421 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4422 'font-lock-multiline t 'help-echo help)))
4423 ;; We need to remove the invisible property here. Table narrowing
4424 ;; may have made some of this invisible.
4425 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4426 (remove-text-properties (match-beginning 0) (match-end 0)
4427 '(invisible nil))
4428 (if (match-end 3)
4429 (progn
4430 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4431 (org-rear-nonsticky-at (match-beginning 3))
4432 (add-text-properties (match-beginning 3) (match-end 3) vp)
4433 (org-rear-nonsticky-at (match-end 3))
4434 (add-text-properties (match-end 3) (match-end 0) ip)
4435 (org-rear-nonsticky-at (match-end 0)))
4436 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4437 (org-rear-nonsticky-at (match-beginning 1))
4438 (add-text-properties (match-beginning 1) (match-end 1) vp)
4439 (org-rear-nonsticky-at (match-end 1))
4440 (add-text-properties (match-end 1) (match-end 0) ip)
4441 (org-rear-nonsticky-at (match-end 0)))
4442 t)))
4444 (defun org-activate-dates (limit)
4445 "Run through the buffer and add overlays to dates."
4446 (if (re-search-forward org-tsr-regexp-both limit t)
4447 (progn
4448 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4449 (add-text-properties (match-beginning 0) (match-end 0)
4450 (list 'mouse-face 'highlight
4451 'keymap org-mouse-map))
4452 (org-rear-nonsticky-at (match-end 0))
4453 (when org-display-custom-times
4454 (if (match-end 3)
4455 (org-display-custom-time (match-beginning 3) (match-end 3)))
4456 (org-display-custom-time (match-beginning 1) (match-end 1)))
4457 t)))
4459 (defvar org-target-link-regexp nil
4460 "Regular expression matching radio targets in plain text.")
4461 (make-variable-buffer-local 'org-target-link-regexp)
4462 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4463 "Regular expression matching a link target.")
4464 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4465 "Regular expression matching a radio target.")
4466 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4467 "Regular expression matching any target.")
4469 (defun org-activate-target-links (limit)
4470 "Run through the buffer and add overlays to target matches."
4471 (when org-target-link-regexp
4472 (let ((case-fold-search t))
4473 (if (re-search-forward org-target-link-regexp limit t)
4474 (progn
4475 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4476 (add-text-properties (match-beginning 0) (match-end 0)
4477 (list 'mouse-face 'highlight
4478 'keymap org-mouse-map
4479 'help-echo "Radio target link"
4480 'org-linked-text t))
4481 (org-rear-nonsticky-at (match-end 0))
4482 t)))))
4484 (defun org-update-radio-target-regexp ()
4485 "Find all radio targets in this file and update the regular expression."
4486 (interactive)
4487 (when (memq 'radio org-activate-links)
4488 (setq org-target-link-regexp
4489 (org-make-target-link-regexp (org-all-targets 'radio)))
4490 (org-restart-font-lock)))
4492 (defun org-hide-wide-columns (limit)
4493 (let (s e)
4494 (setq s (text-property-any (point) (or limit (point-max))
4495 'org-cwidth t))
4496 (when s
4497 (setq e (next-single-property-change s 'org-cwidth))
4498 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4499 (goto-char e)
4500 t)))
4502 (defvar org-latex-and-specials-regexp nil
4503 "Regular expression for highlighting export special stuff.")
4504 (defvar org-match-substring-regexp)
4505 (defvar org-match-substring-with-braces-regexp)
4507 ;; This should be with the exporter code, but we also use if for font-locking
4508 (defconst org-export-html-special-string-regexps
4509 '(("\\\\-" . "&shy;")
4510 ("---\\([^-]\\)" . "&mdash;\\1")
4511 ("--\\([^-]\\)" . "&ndash;\\1")
4512 ("\\.\\.\\." . "&hellip;"))
4513 "Regular expressions for special string conversion.")
4516 (defun org-compute-latex-and-specials-regexp ()
4517 "Compute regular expression for stuff treated specially by exporters."
4518 (if (not org-highlight-latex-fragments-and-specials)
4519 (org-set-local 'org-latex-and-specials-regexp nil)
4520 (require 'org-exp)
4521 (let*
4522 ((matchers (plist-get org-format-latex-options :matchers))
4523 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4524 org-latex-regexps)))
4525 (options (org-combine-plists (org-default-export-plist)
4526 (org-infile-export-plist)))
4527 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4528 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4529 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4530 (org-export-html-expand (plist-get options :expand-quoted-html))
4531 (org-export-with-special-strings (plist-get options :special-strings))
4532 (re-sub
4533 (cond
4534 ((equal org-export-with-sub-superscripts '{})
4535 (list org-match-substring-with-braces-regexp))
4536 (org-export-with-sub-superscripts
4537 (list org-match-substring-regexp))
4538 (t nil)))
4539 (re-latex
4540 (if org-export-with-LaTeX-fragments
4541 (mapcar (lambda (x) (nth 1 x)) latexs)))
4542 (re-macros
4543 (if org-export-with-TeX-macros
4544 (list (concat "\\\\"
4545 (regexp-opt
4546 (append (mapcar 'car org-html-entities)
4547 (if (boundp 'org-latex-entities)
4548 (mapcar (lambda (x)
4549 (or (car-safe x) x))
4550 org-latex-entities)
4551 nil))
4552 'words))) ; FIXME
4554 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4555 (re-special (if org-export-with-special-strings
4556 (mapcar (lambda (x) (car x))
4557 org-export-html-special-string-regexps)))
4558 (re-rest
4559 (delq nil
4560 (list
4561 (if org-export-html-expand "@<[^>\n]+>")
4562 ))))
4563 (org-set-local
4564 'org-latex-and-specials-regexp
4565 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4566 re-rest) "\\|")))))
4568 (defun org-do-latex-and-special-faces (limit)
4569 "Run through the buffer and add overlays to links."
4570 (when org-latex-and-specials-regexp
4571 (let (rtn d)
4572 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4573 limit t))
4574 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4575 'face))
4576 '(org-code org-verbatim underline)))
4577 (progn
4578 (setq rtn t
4579 d (cond ((member (char-after (1+ (match-beginning 0)))
4580 '(?_ ?^)) 1)
4581 (t 0)))
4582 (font-lock-prepend-text-property
4583 (+ d (match-beginning 0)) (match-end 0)
4584 'face 'org-latex-and-export-specials)
4585 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4586 '(font-lock-multiline t)))))
4587 rtn)))
4589 (defun org-restart-font-lock ()
4590 "Restart font-lock-mode, to force refontification."
4591 (when (and (boundp 'font-lock-mode) font-lock-mode)
4592 (font-lock-mode -1)
4593 (font-lock-mode 1)))
4595 (defun org-all-targets (&optional radio)
4596 "Return a list of all targets in this file.
4597 With optional argument RADIO, only find radio targets."
4598 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4599 rtn)
4600 (save-excursion
4601 (goto-char (point-min))
4602 (while (re-search-forward re nil t)
4603 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4604 rtn)))
4606 (defun org-make-target-link-regexp (targets)
4607 "Make regular expression matching all strings in TARGETS.
4608 The regular expression finds the targets also if there is a line break
4609 between words."
4610 (and targets
4611 (concat
4612 "\\<\\("
4613 (mapconcat
4614 (lambda (x)
4615 (while (string-match " +" x)
4616 (setq x (replace-match "\\s-+" t t x)))
4618 targets
4619 "\\|")
4620 "\\)\\>")))
4622 (defun org-activate-tags (limit)
4623 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4624 (progn
4625 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4626 (add-text-properties (match-beginning 1) (match-end 1)
4627 (list 'mouse-face 'highlight
4628 'keymap org-mouse-map))
4629 (org-rear-nonsticky-at (match-end 1))
4630 t)))
4632 (defun org-outline-level ()
4633 (save-excursion
4634 (looking-at outline-regexp)
4635 (if (match-beginning 1)
4636 (+ (org-get-string-indentation (match-string 1)) 1000)
4637 (1- (- (match-end 0) (match-beginning 0))))))
4639 (defvar org-font-lock-keywords nil)
4641 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4642 "Regular expression matching a property line.")
4644 (defvar org-font-lock-hook nil
4645 "Functions to be called for special font lock stuff.")
4647 (defun org-font-lock-hook (limit)
4648 (run-hook-with-args 'org-font-lock-hook limit))
4650 (defun org-set-font-lock-defaults ()
4651 (let* ((em org-fontify-emphasized-text)
4652 (lk org-activate-links)
4653 (org-font-lock-extra-keywords
4654 (list
4655 ;; Call the hook
4656 '(org-font-lock-hook)
4657 ;; Headlines
4658 `(,(if org-fontify-whole-heading-line
4659 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4660 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4661 (1 (org-get-level-face 1))
4662 (2 (org-get-level-face 2))
4663 (3 (org-get-level-face 3)))
4664 ;; Table lines
4665 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4666 (1 'org-table t))
4667 ;; Table internals
4668 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4669 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4670 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4671 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4672 ;; Drawers
4673 (list org-drawer-regexp '(0 'org-special-keyword t))
4674 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4675 ;; Properties
4676 (list org-property-re
4677 '(1 'org-special-keyword t)
4678 '(3 'org-property-value t))
4679 ;; Links
4680 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4681 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4682 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4683 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4684 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4685 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4686 (if (memq 'footnote lk) '(org-activate-footnote-links
4687 (2 'org-footnote t)))
4688 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4689 '(org-hide-wide-columns (0 nil append))
4690 ;; TODO lines
4691 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4692 '(1 (org-get-todo-face 1) t))
4693 ;; DONE
4694 (if org-fontify-done-headline
4695 (list (concat "^[*]+ +\\<\\("
4696 (mapconcat 'regexp-quote org-done-keywords "\\|")
4697 "\\)\\(.*\\)")
4698 '(2 'org-headline-done t))
4699 nil)
4700 ;; Priorities
4701 '(org-font-lock-add-priority-faces)
4702 ;; Tags
4703 '(org-font-lock-add-tag-faces)
4704 ;; Special keywords
4705 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4706 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4707 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4708 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4709 ;; Emphasis
4710 (if em
4711 (if (featurep 'xemacs)
4712 '(org-do-emphasis-faces (0 nil append))
4713 '(org-do-emphasis-faces)))
4714 ;; Checkboxes
4715 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4716 2 'org-checkbox prepend)
4717 (if org-provide-checkbox-statistics
4718 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4719 (0 (org-get-checkbox-statistics-face) t)))
4720 ;; Description list items
4721 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4722 2 'bold prepend)
4723 ;; ARCHIVEd headings
4724 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4725 '(1 'org-archived prepend))
4726 ;; Specials
4727 '(org-do-latex-and-special-faces)
4728 ;; Code
4729 '(org-activate-code (1 'org-code t))
4730 ;; COMMENT
4731 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4732 "\\|" org-quote-string "\\)\\>")
4733 '(1 'org-special-keyword t))
4734 '("^#.*" (0 'font-lock-comment-face t))
4735 ;; Blocks and meta lines
4736 '(org-fontify-meta-lines-and-blocks)
4738 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4739 ;; Now set the full font-lock-keywords
4740 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4741 (org-set-local 'font-lock-defaults
4742 '(org-font-lock-keywords t nil nil backward-paragraph))
4743 (kill-local-variable 'font-lock-keywords) nil))
4745 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4746 "Fontify string S like in Org-mode"
4747 (with-temp-buffer
4748 (insert s)
4749 (let ((org-odd-levels-only odd-levels))
4750 (org-mode)
4751 (font-lock-fontify-buffer)
4752 (buffer-string))))
4754 (defvar org-m nil)
4755 (defvar org-l nil)
4756 (defvar org-f nil)
4757 (defun org-get-level-face (n)
4758 "Get the right face for match N in font-lock matching of headlines."
4759 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4760 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4761 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4762 (cond
4763 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4764 ((eq n 2) org-f)
4765 (t (if org-level-color-stars-only nil org-f))))
4767 (defun org-get-todo-face (kwd)
4768 "Get the right face for a TODO keyword KWD.
4769 If KWD is a number, get the corresponding match group."
4770 (if (numberp kwd) (setq kwd (match-string kwd)))
4771 (or (cdr (assoc kwd org-todo-keyword-faces))
4772 (and (member kwd org-done-keywords) 'org-done)
4773 'org-todo))
4775 (defun org-font-lock-add-tag-faces (limit)
4776 "Add the special tag faces."
4777 (when (and org-tag-faces org-tags-special-faces-re)
4778 (while (re-search-forward org-tags-special-faces-re limit t)
4779 (add-text-properties (match-beginning 1) (match-end 1)
4780 (list 'face (org-get-tag-face 1)
4781 'font-lock-fontified t))
4782 (backward-char 1))))
4784 (defun org-font-lock-add-priority-faces (limit)
4785 "Add the special priority faces."
4786 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4787 (add-text-properties
4788 (match-beginning 0) (match-end 0)
4789 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4790 org-priority-faces))
4791 'org-special-keyword)
4792 'font-lock-fontified t))))
4794 (defun org-get-tag-face (kwd)
4795 "Get the right face for a TODO keyword KWD.
4796 If KWD is a number, get the corresponding match group."
4797 (if (numberp kwd) (setq kwd (match-string kwd)))
4798 (or (cdr (assoc kwd org-tag-faces))
4799 'org-tag))
4801 (defun org-unfontify-region (beg end &optional maybe_loudly)
4802 "Remove fontification and activation overlays from links."
4803 (font-lock-default-unfontify-region beg end)
4804 (let* ((buffer-undo-list t)
4805 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4806 (inhibit-modification-hooks t)
4807 deactivate-mark buffer-file-name buffer-file-truename)
4808 (remove-text-properties beg end
4809 '(mouse-face t keymap t org-linked-text t
4810 invisible t intangible t
4811 line-prefix t wrap-prefix t
4812 org-no-flyspell t))))
4814 ;;;; Visibility cycling, including org-goto and indirect buffer
4816 ;;; Cycling
4818 (defvar org-cycle-global-status nil)
4819 (make-variable-buffer-local 'org-cycle-global-status)
4820 (defvar org-cycle-subtree-status nil)
4821 (make-variable-buffer-local 'org-cycle-subtree-status)
4823 ;;;###autoload
4825 (defvar org-inlinetask-min-level)
4827 (defun org-cycle (&optional arg)
4828 "TAB-action and visibility cycling for Org-mode.
4830 This is the command invoked in Org-mode by the TAB key. Its main purpose
4831 is outine visibility cycling, but it also invokes other actions
4832 in special contexts.
4834 - When this function is called with a prefix argument, rotate the entire
4835 buffer through 3 states (global cycling)
4836 1. OVERVIEW: Show only top-level headlines.
4837 2. CONTENTS: Show all headlines of all levels, but no body text.
4838 3. SHOW ALL: Show everything.
4839 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4840 determined by the variable `org-startup-folded', and by any VISIBILITY
4841 properties in the buffer.
4842 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4843 including any drawers.
4845 - When inside a table, re-align the table and move to the next field.
4847 - When point is at the beginning of a headline, rotate the subtree started
4848 by this line through 3 different states (local cycling)
4849 1. FOLDED: Only the main headline is shown.
4850 2. CHILDREN: The main headline and the direct children are shown.
4851 From this state, you can move to one of the children
4852 and zoom in further.
4853 3. SUBTREE: Show the entire subtree, including body text.
4854 If there is no subtree, switch directly from CHILDREN to FOLDED.
4856 - When there is a numeric prefix, go up to a heading with level ARG, do
4857 a `show-subtree' and return to the previous cursor position. If ARG
4858 is negative, go up that many levels.
4860 - When point is not at the beginning of a headline, execute the global
4861 binding for TAB, which is re-indenting the line. See the option
4862 `org-cycle-emulate-tab' for details.
4864 - Special case: if point is at the beginning of the buffer and there is
4865 no headline in line 1, this function will act as if called with prefix arg.
4866 But only if also the variable `org-cycle-global-at-bob' is t."
4867 (interactive "P")
4868 (org-load-modules-maybe)
4869 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4870 (let* ((limit-level
4871 (or org-cycle-max-level
4872 (and (boundp 'org-inlinetask-min-level)
4873 org-inlinetask-min-level
4874 (1- org-inlinetask-min-level))))
4875 (nstars (and limit-level
4876 (if org-odd-levels-only
4877 (and limit-level (1- (* limit-level 2)))
4878 limit-level)))
4879 (outline-regexp
4880 (cond
4881 ((not (org-mode-p)) outline-regexp)
4882 ((or (eq org-cycle-include-plain-lists 'integrate)
4883 (and org-cycle-include-plain-lists (org-at-item-p)))
4884 (concat "\\(?:\\*"
4885 (if nstars (format "\\{1,%d\\}" nstars) "+")
4886 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4887 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4888 (bob-special (and org-cycle-global-at-bob (bobp)
4889 (not (looking-at outline-regexp))))
4890 (org-cycle-hook
4891 (if bob-special
4892 (delq 'org-optimize-window-after-visibility-change
4893 (copy-sequence org-cycle-hook))
4894 org-cycle-hook))
4895 (pos (point)))
4897 (if (or bob-special (equal arg '(4)))
4898 ;; special case: use global cycling
4899 (setq arg t))
4901 (cond
4903 ((equal arg '(16))
4904 (org-set-startup-visibility)
4905 (message "Startup visibility, plus VISIBILITY properties"))
4907 ((equal arg '(64))
4908 (show-all)
4909 (message "Entire buffer visible, including drawers"))
4911 ((org-at-table-p 'any)
4912 ;; Enter the table or move to the next field in the table
4913 (or (org-table-recognize-table.el)
4914 (progn
4915 (if arg (org-table-edit-field t)
4916 (org-table-justify-field-maybe)
4917 (call-interactively 'org-table-next-field)))))
4919 ((run-hook-with-args-until-success
4920 'org-tab-after-check-for-table-hook))
4922 ((eq arg t) ;; Global cycling
4923 (org-cycle-internal-global))
4925 ((and org-drawers org-drawer-regexp
4926 (save-excursion
4927 (beginning-of-line 1)
4928 (looking-at org-drawer-regexp)))
4929 ;; Toggle block visibility
4930 (org-flag-drawer
4931 (not (get-char-property (match-end 0) 'invisible))))
4933 ((integerp arg)
4934 ;; Show-subtree, ARG levels up from here.
4935 (save-excursion
4936 (org-back-to-heading)
4937 (outline-up-heading (if (< arg 0) (- arg)
4938 (- (funcall outline-level) arg)))
4939 (org-show-subtree)))
4941 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4942 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4944 (org-cycle-internal-local))
4946 ;; TAB emulation and template completion
4947 (buffer-read-only (org-back-to-heading))
4949 ((run-hook-with-args-until-success
4950 'org-tab-after-check-for-cycling-hook))
4952 ((org-try-structure-completion))
4954 ((org-try-cdlatex-tab))
4956 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4957 (or (not (bolp))
4958 (not (looking-at outline-regexp))))
4959 (call-interactively (global-key-binding "\t")))
4961 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4962 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4963 (or (and (eq org-cycle-emulate-tab 'white)
4964 (= (match-end 0) (point-at-eol)))
4965 (and (eq org-cycle-emulate-tab 'whitestart)
4966 (>= (match-end 0) pos))))
4968 (eq org-cycle-emulate-tab t))
4969 (call-interactively (global-key-binding "\t")))
4971 (t (save-excursion
4972 (org-back-to-heading)
4973 (org-cycle)))))))
4975 (defun org-cycle-internal-global ()
4976 "Do the global cycling action."
4977 (cond
4978 ((and (eq last-command this-command)
4979 (eq org-cycle-global-status 'overview))
4980 ;; We just created the overview - now do table of contents
4981 ;; This can be slow in very large buffers, so indicate action
4982 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4983 (message "CONTENTS...")
4984 (org-content)
4985 (message "CONTENTS...done")
4986 (setq org-cycle-global-status 'contents)
4987 (run-hook-with-args 'org-cycle-hook 'contents))
4989 ((and (eq last-command this-command)
4990 (eq org-cycle-global-status 'contents))
4991 ;; We just showed the table of contents - now show everything
4992 (run-hook-with-args 'org-pre-cycle-hook 'all)
4993 (show-all)
4994 (message "SHOW ALL")
4995 (setq org-cycle-global-status 'all)
4996 (run-hook-with-args 'org-cycle-hook 'all))
4999 ;; Default action: go to overview
5000 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5001 (org-overview)
5002 (message "OVERVIEW")
5003 (setq org-cycle-global-status 'overview)
5004 (run-hook-with-args 'org-cycle-hook 'overview))))
5006 (defun org-cycle-internal-local ()
5007 "Do the local cycling action."
5008 (org-back-to-heading)
5009 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5010 ;; First, some boundaries
5011 (save-excursion
5012 (org-back-to-heading)
5013 (setq level (funcall outline-level))
5014 (save-excursion
5015 (beginning-of-line 2)
5016 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5017 ; XEmacs does not have `next-single-char-property-change'
5018 ; I'm not sure about Emacs 21.
5019 (while (and (not (eobp)) ;; this is like `next-line'
5020 (get-char-property (1- (point)) 'invisible))
5021 (beginning-of-line 2))
5022 (while (and (not (eobp)) ;; this is like `next-line'
5023 (get-char-property (1- (point)) 'invisible))
5024 (goto-char (next-single-char-property-change (point) 'invisible))
5025 ;;;??? (or (bolp) (beginning-of-line 2))))
5026 (and (eolp) (beginning-of-line 2))))
5027 (setq eol (point)))
5028 (outline-end-of-heading) (setq eoh (point))
5029 (save-excursion
5030 (outline-next-heading)
5031 (setq has-children (and (org-at-heading-p t)
5032 (> (funcall outline-level) level))))
5033 (org-end-of-subtree t)
5034 (unless (eobp)
5035 (skip-chars-forward " \t\n")
5036 (beginning-of-line 1) ; in case this is an item
5038 (setq eos (if (eobp) (point) (1- (point)))))
5039 ;; Find out what to do next and set `this-command'
5040 (cond
5041 ((= eos eoh)
5042 ;; Nothing is hidden behind this heading
5043 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5044 (message "EMPTY ENTRY")
5045 (setq org-cycle-subtree-status nil)
5046 (save-excursion
5047 (goto-char eos)
5048 (outline-next-heading)
5049 (if (org-invisible-p) (org-flag-heading nil))))
5050 ((and (or (>= eol eos)
5051 (not (string-match "\\S-" (buffer-substring eol eos))))
5052 (or has-children
5053 (not (setq children-skipped
5054 org-cycle-skip-children-state-if-no-children))))
5055 ;; Entire subtree is hidden in one line: children view
5056 (run-hook-with-args 'org-pre-cycle-hook 'children)
5057 (org-show-entry)
5058 (show-children)
5059 (message "CHILDREN")
5060 (save-excursion
5061 (goto-char eos)
5062 (outline-next-heading)
5063 (if (org-invisible-p) (org-flag-heading nil)))
5064 (setq org-cycle-subtree-status 'children)
5065 (run-hook-with-args 'org-cycle-hook 'children))
5066 ((or children-skipped
5067 (and (eq last-command this-command)
5068 (eq org-cycle-subtree-status 'children)))
5069 ;; We just showed the children, or no children are there,
5070 ;; now show everything.
5071 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5072 (org-show-subtree)
5073 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5074 (setq org-cycle-subtree-status 'subtree)
5075 (run-hook-with-args 'org-cycle-hook 'subtree))
5077 ;; Default action: hide the subtree.
5078 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5079 (hide-subtree)
5080 (message "FOLDED")
5081 (setq org-cycle-subtree-status 'folded)
5082 (run-hook-with-args 'org-cycle-hook 'folded)))))
5084 ;;;###autoload
5085 (defun org-global-cycle (&optional arg)
5086 "Cycle the global visibility. For details see `org-cycle'.
5087 With C-u prefix arg, switch to startup visibility.
5088 With a numeric prefix, show all headlines up to that level."
5089 (interactive "P")
5090 (let ((org-cycle-include-plain-lists
5091 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5092 (cond
5093 ((integerp arg)
5094 (show-all)
5095 (hide-sublevels arg)
5096 (setq org-cycle-global-status 'contents))
5097 ((equal arg '(4))
5098 (org-set-startup-visibility)
5099 (message "Startup visibility, plus VISIBILITY properties."))
5101 (org-cycle '(4))))))
5103 (defun org-set-startup-visibility ()
5104 "Set the visibility required by startup options and properties."
5105 (cond
5106 ((eq org-startup-folded t)
5107 (org-cycle '(4)))
5108 ((eq org-startup-folded 'content)
5109 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5110 (org-cycle '(4)) (org-cycle '(4)))))
5111 (unless (eq org-startup-folded 'showeverything)
5112 (if org-hide-block-startup (org-hide-block-all))
5113 (org-set-visibility-according-to-property 'no-cleanup)
5114 (org-cycle-hide-archived-subtrees 'all)
5115 (org-cycle-hide-drawers 'all)
5116 (org-cycle-show-empty-lines 'all)))
5118 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5119 "Switch subtree visibilities according to :VISIBILITY: property."
5120 (interactive)
5121 (let (org-show-entry-below state)
5122 (save-excursion
5123 (goto-char (point-min))
5124 (while (re-search-forward
5125 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5126 nil t)
5127 (setq state (match-string 1))
5128 (save-excursion
5129 (org-back-to-heading t)
5130 (hide-subtree)
5131 (org-reveal)
5132 (cond
5133 ((equal state '("fold" "folded"))
5134 (hide-subtree))
5135 ((equal state "children")
5136 (org-show-hidden-entry)
5137 (show-children))
5138 ((equal state "content")
5139 (save-excursion
5140 (save-restriction
5141 (org-narrow-to-subtree)
5142 (org-content))))
5143 ((member state '("all" "showall"))
5144 (show-subtree)))))
5145 (unless no-cleanup
5146 (org-cycle-hide-archived-subtrees 'all)
5147 (org-cycle-hide-drawers 'all)
5148 (org-cycle-show-empty-lines 'all)))))
5150 (defun org-overview ()
5151 "Switch to overview mode, showing only top-level headlines.
5152 Really, this shows all headlines with level equal or greater than the level
5153 of the first headline in the buffer. This is important, because if the
5154 first headline is not level one, then (hide-sublevels 1) gives confusing
5155 results."
5156 (interactive)
5157 (let ((level (save-excursion
5158 (goto-char (point-min))
5159 (if (re-search-forward (concat "^" outline-regexp) nil t)
5160 (progn
5161 (goto-char (match-beginning 0))
5162 (funcall outline-level))))))
5163 (and level (hide-sublevels level))))
5165 (defun org-content (&optional arg)
5166 "Show all headlines in the buffer, like a table of contents.
5167 With numerical argument N, show content up to level N."
5168 (interactive "P")
5169 (save-excursion
5170 ;; Visit all headings and show their offspring
5171 (and (integerp arg) (org-overview))
5172 (goto-char (point-max))
5173 (catch 'exit
5174 (while (and (progn (condition-case nil
5175 (outline-previous-visible-heading 1)
5176 (error (goto-char (point-min))))
5178 (looking-at outline-regexp))
5179 (if (integerp arg)
5180 (show-children (1- arg))
5181 (show-branches))
5182 (if (bobp) (throw 'exit nil))))))
5185 (defun org-optimize-window-after-visibility-change (state)
5186 "Adjust the window after a change in outline visibility.
5187 This function is the default value of the hook `org-cycle-hook'."
5188 (when (get-buffer-window (current-buffer))
5189 (cond
5190 ((eq state 'content) nil)
5191 ((eq state 'all) nil)
5192 ((eq state 'folded) nil)
5193 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5194 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5196 ;; FIXME: no longer in use
5197 (defun org-compact-display-after-subtree-move ()
5198 "Show a compacter version of the tree of the entry's parent."
5199 (save-excursion
5200 (if (org-up-heading-safe)
5201 (progn
5202 (hide-subtree)
5203 (show-entry)
5204 (show-children)
5205 (org-cycle-show-empty-lines 'children)
5206 (org-cycle-hide-drawers 'children))
5207 (org-overview))))
5209 (defun org-remove-empty-overlays-at (pos)
5210 "Remove outline overlays that do not contain non-white stuff."
5211 (mapc
5212 (lambda (o)
5213 (and (eq 'outline (org-overlay-get o 'invisible))
5214 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5215 (org-overlay-end o))))
5216 (org-delete-overlay o)))
5217 (org-overlays-at pos)))
5219 (defun org-clean-visibility-after-subtree-move ()
5220 "Fix visibility issues after moving a subtree."
5221 ;; First, find a reasonable region to look at:
5222 ;; Start two siblings above, end three below
5223 (let* ((beg (save-excursion
5224 (and (org-get-last-sibling)
5225 (org-get-last-sibling))
5226 (point)))
5227 (end (save-excursion
5228 (and (org-get-next-sibling)
5229 (org-get-next-sibling)
5230 (org-get-next-sibling))
5231 (if (org-at-heading-p)
5232 (point-at-eol)
5233 (point))))
5234 (level (looking-at "\\*+"))
5235 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5236 (save-excursion
5237 (save-restriction
5238 (narrow-to-region beg end)
5239 (when re
5240 ;; Properly fold already folded siblings
5241 (goto-char (point-min))
5242 (while (re-search-forward re nil t)
5243 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5244 (hide-entry))))
5245 (org-cycle-show-empty-lines 'overview)
5246 (org-cycle-hide-drawers 'overview)))))
5248 (defun org-cycle-show-empty-lines (state)
5249 "Show empty lines above all visible headlines.
5250 The region to be covered depends on STATE when called through
5251 `org-cycle-hook'. Lisp program can use t for STATE to get the
5252 entire buffer covered. Note that an empty line is only shown if there
5253 are at least `org-cycle-separator-lines' empty lines before the headline."
5254 (when (not (= org-cycle-separator-lines 0))
5255 (save-excursion
5256 (let* ((n (abs org-cycle-separator-lines))
5257 (re (cond
5258 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5259 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5260 (t (let ((ns (number-to-string (- n 2))))
5261 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5262 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5263 beg end b e)
5264 (cond
5265 ((memq state '(overview contents t))
5266 (setq beg (point-min) end (point-max)))
5267 ((memq state '(children folded))
5268 (setq beg (point) end (progn (org-end-of-subtree t t)
5269 (beginning-of-line 2)
5270 (point)))))
5271 (when beg
5272 (goto-char beg)
5273 (while (re-search-forward re end t)
5274 (unless (get-char-property (match-end 1) 'invisible)
5275 (setq e (match-end 1))
5276 (if (< org-cycle-separator-lines 0)
5277 (setq b (save-excursion
5278 (goto-char (match-beginning 0))
5279 (org-back-over-empty-lines)
5280 (if (save-excursion
5281 (goto-char (max (point-min) (1- (point))))
5282 (org-on-heading-p))
5283 (1- (point))
5284 (point))))
5285 (setq b (match-beginning 1)))
5286 (outline-flag-region b e nil)))))))
5287 ;; Never hide empty lines at the end of the file.
5288 (save-excursion
5289 (goto-char (point-max))
5290 (outline-previous-heading)
5291 (outline-end-of-heading)
5292 (if (and (looking-at "[ \t\n]+")
5293 (= (match-end 0) (point-max)))
5294 (outline-flag-region (point) (match-end 0) nil))))
5296 (defun org-show-empty-lines-in-parent ()
5297 "Move to the parent and re-show empty lines before visible headlines."
5298 (save-excursion
5299 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5300 (org-cycle-show-empty-lines context))))
5302 (defun org-cycle-hide-drawers (state)
5303 "Re-hide all drawers after a visibility state change."
5304 (when (and (org-mode-p)
5305 (not (memq state '(overview folded contents))))
5306 (save-excursion
5307 (let* ((globalp (memq state '(contents all)))
5308 (beg (if globalp (point-min) (point)))
5309 (end (if globalp (point-max)
5310 (if (eq state 'children)
5311 (save-excursion (outline-next-heading) (point))
5312 (org-end-of-subtree t)))))
5313 (goto-char beg)
5314 (while (re-search-forward org-drawer-regexp end t)
5315 (org-flag-drawer t))))))
5317 (defun org-flag-drawer (flag)
5318 (save-excursion
5319 (beginning-of-line 1)
5320 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5321 (let ((b (match-end 0))
5322 (outline-regexp org-outline-regexp))
5323 (if (re-search-forward
5324 "^[ \t]*:END:"
5325 (save-excursion (outline-next-heading) (point)) t)
5326 (outline-flag-region b (point-at-eol) flag)
5327 (error ":END: line missing at position %s" b))))))
5329 (defun org-subtree-end-visible-p ()
5330 "Is the end of the current subtree visible?"
5331 (pos-visible-in-window-p
5332 (save-excursion (org-end-of-subtree t) (point))))
5334 (defun org-first-headline-recenter (&optional N)
5335 "Move cursor to the first headline and recenter the headline.
5336 Optional argument N means, put the headline into the Nth line of the window."
5337 (goto-char (point-min))
5338 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5339 (beginning-of-line)
5340 (recenter (prefix-numeric-value N))))
5342 ;;; Folding of blocks
5344 (defconst org-block-regexp
5346 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5347 "Regular expression for hiding blocks.")
5349 (defvar org-hide-block-overlays nil
5350 "Overays hiding blocks.")
5351 (make-variable-buffer-local 'org-hide-block-overlays)
5353 (defun org-block-map (function &optional start end)
5354 "Call func at the head of all source blocks in the current
5355 buffer. Optional arguments START and END can be used to limit
5356 the range."
5357 (let ((start (or start (point-min)))
5358 (end (or end (point-max))))
5359 (save-excursion
5360 (goto-char start)
5361 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5362 (save-excursion
5363 (save-match-data
5364 (goto-char (match-beginning 0))
5365 (funcall function)))))))
5367 (defun org-hide-block-toggle-all ()
5368 "Toggle the visibility of all blocks in the current buffer."
5369 (org-block-map #'org-hide-block-toggle))
5371 (defun org-hide-block-all ()
5372 "Fold all blocks in the current buffer."
5373 (interactive)
5374 (org-show-block-all)
5375 (org-block-map #'org-hide-block-toggle-maybe))
5377 (defun org-show-block-all ()
5378 "Unfold all blocks in the current buffer."
5379 (mapc 'org-delete-overlay org-hide-block-overlays)
5380 (setq org-hide-block-overlays nil))
5382 (defun org-hide-block-toggle-maybe ()
5383 "Toggle visibility of block at point."
5384 (interactive)
5385 (let ((case-fold-search t))
5386 (if (save-excursion
5387 (beginning-of-line 1)
5388 (looking-at org-block-regexp))
5389 (progn (org-hide-block-toggle)
5390 t) ;; to signal that we took action
5391 nil))) ;; to signal that we did not
5393 (defun org-hide-block-toggle (&optional force)
5394 "Toggle the visibility of the current block."
5395 (interactive)
5396 (save-excursion
5397 (beginning-of-line)
5398 (if (re-search-forward org-block-regexp nil t)
5399 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5400 (end (match-end 0)) ;; end of entire body
5402 (if (memq t (mapcar (lambda (overlay)
5403 (eq (org-overlay-get overlay 'invisible)
5404 'org-hide-block))
5405 (org-overlays-at start)))
5406 (if (or (not force) (eq force 'off))
5407 (mapc (lambda (ov)
5408 (when (member ov org-hide-block-overlays)
5409 (setq org-hide-block-overlays
5410 (delq ov org-hide-block-overlays)))
5411 (when (eq (org-overlay-get ov 'invisible)
5412 'org-hide-block)
5413 (org-delete-overlay ov)))
5414 (org-overlays-at start)))
5415 (setq ov (org-make-overlay start end))
5416 (org-overlay-put ov 'invisible 'org-hide-block)
5417 ;; make the block accessible to isearch
5418 (org-overlay-put
5419 ov 'isearch-open-invisible
5420 (lambda (ov)
5421 (when (member ov org-hide-block-overlays)
5422 (setq org-hide-block-overlays
5423 (delq ov org-hide-block-overlays)))
5424 (when (eq (org-overlay-get ov 'invisible)
5425 'org-hide-block)
5426 (org-delete-overlay ov))))
5427 (push ov org-hide-block-overlays)))
5428 (error "Not looking at a source block"))))
5430 ;; org-tab-after-check-for-cycling-hook
5431 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5432 ;; Remove overlays when changing major mode
5433 (add-hook 'org-mode-hook
5434 (lambda () (org-add-hook 'change-major-mode-hook
5435 'org-show-block-all 'append 'local)))
5437 ;;; Org-goto
5439 (defvar org-goto-window-configuration nil)
5440 (defvar org-goto-marker nil)
5441 (defvar org-goto-map
5442 (let ((map (make-sparse-keymap)))
5443 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5444 (while (setq cmd (pop cmds))
5445 (substitute-key-definition cmd cmd map global-map)))
5446 (suppress-keymap map)
5447 (org-defkey map "\C-m" 'org-goto-ret)
5448 (org-defkey map [(return)] 'org-goto-ret)
5449 (org-defkey map [(left)] 'org-goto-left)
5450 (org-defkey map [(right)] 'org-goto-right)
5451 (org-defkey map [(control ?g)] 'org-goto-quit)
5452 (org-defkey map "\C-i" 'org-cycle)
5453 (org-defkey map [(tab)] 'org-cycle)
5454 (org-defkey map [(down)] 'outline-next-visible-heading)
5455 (org-defkey map [(up)] 'outline-previous-visible-heading)
5456 (if org-goto-auto-isearch
5457 (if (fboundp 'define-key-after)
5458 (define-key-after map [t] 'org-goto-local-auto-isearch)
5459 nil)
5460 (org-defkey map "q" 'org-goto-quit)
5461 (org-defkey map "n" 'outline-next-visible-heading)
5462 (org-defkey map "p" 'outline-previous-visible-heading)
5463 (org-defkey map "f" 'outline-forward-same-level)
5464 (org-defkey map "b" 'outline-backward-same-level)
5465 (org-defkey map "u" 'outline-up-heading))
5466 (org-defkey map "/" 'org-occur)
5467 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5468 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5469 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5470 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5471 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5472 map))
5474 (defconst org-goto-help
5475 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5476 RET=jump to location [Q]uit and return to previous location
5477 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5479 (defvar org-goto-start-pos) ; dynamically scoped parameter
5481 ;; FIXME: Docstring doe not mention both interfaces
5482 (defun org-goto (&optional alternative-interface)
5483 "Look up a different location in the current file, keeping current visibility.
5485 When you want look-up or go to a different location in a document, the
5486 fastest way is often to fold the entire buffer and then dive into the tree.
5487 This method has the disadvantage, that the previous location will be folded,
5488 which may not be what you want.
5490 This command works around this by showing a copy of the current buffer
5491 in an indirect buffer, in overview mode. You can dive into the tree in
5492 that copy, use org-occur and incremental search to find a location.
5493 When pressing RET or `Q', the command returns to the original buffer in
5494 which the visibility is still unchanged. After RET is will also jump to
5495 the location selected in the indirect buffer and expose the
5496 the headline hierarchy above."
5497 (interactive "P")
5498 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5499 (org-refile-use-outline-path t)
5500 (org-refile-target-verify-function nil)
5501 (interface
5502 (if (not alternative-interface)
5503 org-goto-interface
5504 (if (eq org-goto-interface 'outline)
5505 'outline-path-completion
5506 'outline)))
5507 (org-goto-start-pos (point))
5508 (selected-point
5509 (if (eq interface 'outline)
5510 (car (org-get-location (current-buffer) org-goto-help))
5511 (nth 3 (org-refile-get-location "Goto: ")))))
5512 (if selected-point
5513 (progn
5514 (org-mark-ring-push org-goto-start-pos)
5515 (goto-char selected-point)
5516 (if (or (org-invisible-p) (org-invisible-p2))
5517 (org-show-context 'org-goto)))
5518 (message "Quit"))))
5520 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5521 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5522 (defvar org-goto-local-auto-isearch-map) ; defined below
5524 (defun org-get-location (buf help)
5525 "Let the user select a location in the Org-mode buffer BUF.
5526 This function uses a recursive edit. It returns the selected position
5527 or nil."
5528 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5529 (isearch-hide-immediately nil)
5530 (isearch-search-fun-function
5531 (lambda () 'org-goto-local-search-headings))
5532 (org-goto-selected-point org-goto-exit-command))
5533 (save-excursion
5534 (save-window-excursion
5535 (delete-other-windows)
5536 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5537 (switch-to-buffer
5538 (condition-case nil
5539 (make-indirect-buffer (current-buffer) "*org-goto*")
5540 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5541 (with-output-to-temp-buffer "*Help*"
5542 (princ help))
5543 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5544 (setq buffer-read-only nil)
5545 (let ((org-startup-truncated t)
5546 (org-startup-folded nil)
5547 (org-startup-align-all-tables nil))
5548 (org-mode)
5549 (org-overview))
5550 (setq buffer-read-only t)
5551 (if (and (boundp 'org-goto-start-pos)
5552 (integer-or-marker-p org-goto-start-pos))
5553 (let ((org-show-hierarchy-above t)
5554 (org-show-siblings t)
5555 (org-show-following-heading t))
5556 (goto-char org-goto-start-pos)
5557 (and (org-invisible-p) (org-show-context)))
5558 (goto-char (point-min)))
5559 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5560 (message "Select location and press RET")
5561 (use-local-map org-goto-map)
5562 (recursive-edit)
5564 (kill-buffer "*org-goto*")
5565 (cons org-goto-selected-point org-goto-exit-command)))
5567 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5568 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5569 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5570 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5572 (defun org-goto-local-search-headings (string bound noerror)
5573 "Search and make sure that any matches are in headlines."
5574 (catch 'return
5575 (while (if isearch-forward
5576 (search-forward string bound noerror)
5577 (search-backward string bound noerror))
5578 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5579 (and (member :headline context)
5580 (not (member :tags context))))
5581 (throw 'return (point))))))
5583 (defun org-goto-local-auto-isearch ()
5584 "Start isearch."
5585 (interactive)
5586 (goto-char (point-min))
5587 (let ((keys (this-command-keys)))
5588 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5589 (isearch-mode t)
5590 (isearch-process-search-char (string-to-char keys)))))
5592 (defun org-goto-ret (&optional arg)
5593 "Finish `org-goto' by going to the new location."
5594 (interactive "P")
5595 (setq org-goto-selected-point (point)
5596 org-goto-exit-command 'return)
5597 (throw 'exit nil))
5599 (defun org-goto-left ()
5600 "Finish `org-goto' by going to the new location."
5601 (interactive)
5602 (if (org-on-heading-p)
5603 (progn
5604 (beginning-of-line 1)
5605 (setq org-goto-selected-point (point)
5606 org-goto-exit-command 'left)
5607 (throw 'exit nil))
5608 (error "Not on a heading")))
5610 (defun org-goto-right ()
5611 "Finish `org-goto' by going to the new location."
5612 (interactive)
5613 (if (org-on-heading-p)
5614 (progn
5615 (setq org-goto-selected-point (point)
5616 org-goto-exit-command 'right)
5617 (throw 'exit nil))
5618 (error "Not on a heading")))
5620 (defun org-goto-quit ()
5621 "Finish `org-goto' without cursor motion."
5622 (interactive)
5623 (setq org-goto-selected-point nil)
5624 (setq org-goto-exit-command 'quit)
5625 (throw 'exit nil))
5627 ;;; Indirect buffer display of subtrees
5629 (defvar org-indirect-dedicated-frame nil
5630 "This is the frame being used for indirect tree display.")
5631 (defvar org-last-indirect-buffer nil)
5633 (defun org-tree-to-indirect-buffer (&optional arg)
5634 "Create indirect buffer and narrow it to current subtree.
5635 With numerical prefix ARG, go up to this level and then take that tree.
5636 If ARG is negative, go up that many levels.
5637 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5638 indirect buffer previously made with this command, to avoid proliferation of
5639 indirect buffers. However, when you call the command with a `C-u' prefix, or
5640 when `org-indirect-buffer-display' is `new-frame', the last buffer
5641 is kept so that you can work with several indirect buffers at the same time.
5642 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5643 requests that a new frame be made for the new buffer, so that the dedicated
5644 frame is not changed."
5645 (interactive "P")
5646 (let ((cbuf (current-buffer))
5647 (cwin (selected-window))
5648 (pos (point))
5649 beg end level heading ibuf)
5650 (save-excursion
5651 (org-back-to-heading t)
5652 (when (numberp arg)
5653 (setq level (org-outline-level))
5654 (if (< arg 0) (setq arg (+ level arg)))
5655 (while (> (setq level (org-outline-level)) arg)
5656 (outline-up-heading 1 t)))
5657 (setq beg (point)
5658 heading (org-get-heading))
5659 (org-end-of-subtree t t) (setq end (point)))
5660 (if (and (buffer-live-p org-last-indirect-buffer)
5661 (not (eq org-indirect-buffer-display 'new-frame))
5662 (not arg))
5663 (kill-buffer org-last-indirect-buffer))
5664 (setq ibuf (org-get-indirect-buffer cbuf)
5665 org-last-indirect-buffer ibuf)
5666 (cond
5667 ((or (eq org-indirect-buffer-display 'new-frame)
5668 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5669 (select-frame (make-frame))
5670 (delete-other-windows)
5671 (switch-to-buffer ibuf)
5672 (org-set-frame-title heading))
5673 ((eq org-indirect-buffer-display 'dedicated-frame)
5674 (raise-frame
5675 (select-frame (or (and org-indirect-dedicated-frame
5676 (frame-live-p org-indirect-dedicated-frame)
5677 org-indirect-dedicated-frame)
5678 (setq org-indirect-dedicated-frame (make-frame)))))
5679 (delete-other-windows)
5680 (switch-to-buffer ibuf)
5681 (org-set-frame-title (concat "Indirect: " heading)))
5682 ((eq org-indirect-buffer-display 'current-window)
5683 (switch-to-buffer ibuf))
5684 ((eq org-indirect-buffer-display 'other-window)
5685 (pop-to-buffer ibuf))
5686 (t (error "Invalid value.")))
5687 (if (featurep 'xemacs)
5688 (save-excursion (org-mode) (turn-on-font-lock)))
5689 (narrow-to-region beg end)
5690 (show-all)
5691 (goto-char pos)
5692 (and (window-live-p cwin) (select-window cwin))))
5694 (defun org-get-indirect-buffer (&optional buffer)
5695 (setq buffer (or buffer (current-buffer)))
5696 (let ((n 1) (base (buffer-name buffer)) bname)
5697 (while (buffer-live-p
5698 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5699 (setq n (1+ n)))
5700 (condition-case nil
5701 (make-indirect-buffer buffer bname 'clone)
5702 (error (make-indirect-buffer buffer bname)))))
5704 (defun org-set-frame-title (title)
5705 "Set the title of the current frame to the string TITLE."
5706 ;; FIXME: how to name a single frame in XEmacs???
5707 (unless (featurep 'xemacs)
5708 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5710 ;;;; Structure editing
5712 ;;; Inserting headlines
5714 (defun org-previous-line-empty-p ()
5715 (save-excursion
5716 (and (not (bobp))
5717 (or (beginning-of-line 0) t)
5718 (save-match-data
5719 (looking-at "[ \t]*$")))))
5721 (defun org-insert-heading (&optional force-heading)
5722 "Insert a new heading or item with same depth at point.
5723 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5724 If point is at the beginning of a headline, insert a sibling before the
5725 current headline. If point is not at the beginning, do not split the line,
5726 but create the new headline after the current line."
5727 (interactive "P")
5728 (if (= (buffer-size) 0)
5729 (insert "\n* ")
5730 (when (or force-heading (not (org-insert-item)))
5731 (let* ((empty-line-p nil)
5732 (head (save-excursion
5733 (condition-case nil
5734 (progn
5735 (org-back-to-heading)
5736 (setq empty-line-p (org-previous-line-empty-p))
5737 (match-string 0))
5738 (error "*"))))
5739 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5740 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5741 pos hide-previous previous-pos)
5742 (cond
5743 ((and (org-on-heading-p) (bolp)
5744 (or (bobp)
5745 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5746 ;; insert before the current line
5747 (open-line (if blank 2 1)))
5748 ((and (bolp)
5749 (not org-insert-heading-respect-content)
5750 (or (bobp)
5751 (save-excursion
5752 (backward-char 1) (not (org-invisible-p)))))
5753 ;; insert right here
5754 nil)
5756 ;; somewhere in the line
5757 (save-excursion
5758 (setq previous-pos (point-at-bol))
5759 (end-of-line)
5760 (setq hide-previous (org-invisible-p)))
5761 (and org-insert-heading-respect-content (org-show-subtree))
5762 (let ((split
5763 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5764 (save-excursion
5765 (let ((p (point)))
5766 (goto-char (point-at-bol))
5767 (and (looking-at org-complex-heading-regexp)
5768 (> p (match-beginning 4)))))))
5769 tags pos)
5770 (cond
5771 (org-insert-heading-respect-content
5772 (org-end-of-subtree nil t)
5773 (or (bolp) (newline))
5774 (or (org-previous-line-empty-p)
5775 (and blank (newline)))
5776 (open-line 1))
5777 ((org-on-heading-p)
5778 (when hide-previous
5779 (show-children)
5780 (org-show-entry))
5781 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5782 (setq tags (and (match-end 2) (match-string 2)))
5783 (and (match-end 1)
5784 (delete-region (match-beginning 1) (match-end 1)))
5785 (setq pos (point-at-bol))
5786 (or split (end-of-line 1))
5787 (delete-horizontal-space)
5788 (newline (if blank 2 1))
5789 (when tags
5790 (save-excursion
5791 (goto-char pos)
5792 (end-of-line 1)
5793 (insert " " tags)
5794 (org-set-tags nil 'align))))
5796 (or split (end-of-line 1))
5797 (newline (if blank 2 1)))))))
5798 (insert head) (just-one-space)
5799 (setq pos (point))
5800 (end-of-line 1)
5801 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5802 (when (and org-insert-heading-respect-content hide-previous)
5803 (save-excursion
5804 (goto-char previous-pos)
5805 (hide-subtree)))
5806 (run-hooks 'org-insert-heading-hook)))))
5808 (defun org-get-heading (&optional no-tags)
5809 "Return the heading of the current entry, without the stars."
5810 (save-excursion
5811 (org-back-to-heading t)
5812 (if (looking-at
5813 (if no-tags
5814 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5815 "\\*+[ \t]+\\([^\r\n]*\\)"))
5816 (match-string 1) "")))
5818 (defun org-heading-components ()
5819 "Return the components of the current heading.
5820 This is a list with the following elements:
5821 - the level as an integer
5822 - the reduced level, different if `org-odd-levels-only' is set.
5823 - the TODO keyword, or nil
5824 - the priority character, like ?A, or nil if no priority is given
5825 - the headline text itself, or the tags string if no headline text
5826 - the tags string, or nil."
5827 (save-excursion
5828 (org-back-to-heading t)
5829 (if (looking-at org-complex-heading-regexp)
5830 (list (length (match-string 1))
5831 (org-reduced-level (length (match-string 1)))
5832 (org-match-string-no-properties 2)
5833 (and (match-end 3) (aref (match-string 3) 2))
5834 (org-match-string-no-properties 4)
5835 (org-match-string-no-properties 5)))))
5837 (defun org-get-entry ()
5838 "Get the entry text, after heading, entire subtree."
5839 (save-excursion
5840 (org-back-to-heading t)
5841 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5843 (defun org-insert-heading-after-current ()
5844 "Insert a new heading with same level as current, after current subtree."
5845 (interactive)
5846 (org-back-to-heading)
5847 (org-insert-heading)
5848 (org-move-subtree-down)
5849 (end-of-line 1))
5851 (defun org-insert-heading-respect-content ()
5852 (interactive)
5853 (let ((org-insert-heading-respect-content t))
5854 (org-insert-heading t)))
5856 (defun org-insert-todo-heading-respect-content (&optional force-state)
5857 (interactive "P")
5858 (let ((org-insert-heading-respect-content t))
5859 (org-insert-todo-heading force-state t)))
5861 (defun org-insert-todo-heading (arg &optional force-heading)
5862 "Insert a new heading with the same level and TODO state as current heading.
5863 If the heading has no TODO state, or if the state is DONE, use the first
5864 state (TODO by default). Also with prefix arg, force first state."
5865 (interactive "P")
5866 (when (or force-heading (not (org-insert-item 'checkbox)))
5867 (org-insert-heading force-heading)
5868 (save-excursion
5869 (org-back-to-heading)
5870 (outline-previous-heading)
5871 (looking-at org-todo-line-regexp))
5872 (let*
5873 ((new-mark-x
5874 (if (or arg
5875 (not (match-beginning 2))
5876 (member (match-string 2) org-done-keywords))
5877 (car org-todo-keywords-1)
5878 (match-string 2)))
5879 (new-mark
5881 (run-hook-with-args-until-success
5882 'org-todo-get-default-hook new-mark-x nil)
5883 new-mark-x)))
5884 (beginning-of-line 1)
5885 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5886 (if org-treat-insert-todo-heading-as-state-change
5887 (org-todo new-mark)
5888 (insert new-mark " "))))
5889 (when org-provide-todo-statistics
5890 (org-update-parent-todo-statistics))))
5892 (defun org-insert-subheading (arg)
5893 "Insert a new subheading and demote it.
5894 Works for outline headings and for plain lists alike."
5895 (interactive "P")
5896 (org-insert-heading arg)
5897 (cond
5898 ((org-on-heading-p) (org-do-demote))
5899 ((org-at-item-p) (org-indent-item 1))))
5901 (defun org-insert-todo-subheading (arg)
5902 "Insert a new subheading with TODO keyword or checkbox and demote it.
5903 Works for outline headings and for plain lists alike."
5904 (interactive "P")
5905 (org-insert-todo-heading arg)
5906 (cond
5907 ((org-on-heading-p) (org-do-demote))
5908 ((org-at-item-p) (org-indent-item 1))))
5910 ;;; Promotion and Demotion
5912 (defvar org-after-demote-entry-hook nil
5913 "Hook run after an entry has been demoted.
5914 The cursor will be at the beginning of the entry.
5915 When a subtree is being demoted, the hook will be called for each node.")
5917 (defvar org-after-promote-entry-hook nil
5918 "Hook run after an entry has been promoted.
5919 The cursor will be at the beginning of the entry.
5920 When a subtree is being promoted, the hook will be called for each node.")
5922 (defun org-promote-subtree ()
5923 "Promote the entire subtree.
5924 See also `org-promote'."
5925 (interactive)
5926 (save-excursion
5927 (org-map-tree 'org-promote))
5928 (org-fix-position-after-promote))
5930 (defun org-demote-subtree ()
5931 "Demote the entire subtree. See `org-demote'.
5932 See also `org-promote'."
5933 (interactive)
5934 (save-excursion
5935 (org-map-tree 'org-demote))
5936 (org-fix-position-after-promote))
5939 (defun org-do-promote ()
5940 "Promote the current heading higher up the tree.
5941 If the region is active in `transient-mark-mode', promote all headings
5942 in the region."
5943 (interactive)
5944 (save-excursion
5945 (if (org-region-active-p)
5946 (org-map-region 'org-promote (region-beginning) (region-end))
5947 (org-promote)))
5948 (org-fix-position-after-promote))
5950 (defun org-do-demote ()
5951 "Demote the current heading lower down the tree.
5952 If the region is active in `transient-mark-mode', demote all headings
5953 in the region."
5954 (interactive)
5955 (save-excursion
5956 (if (org-region-active-p)
5957 (org-map-region 'org-demote (region-beginning) (region-end))
5958 (org-demote)))
5959 (org-fix-position-after-promote))
5961 (defun org-fix-position-after-promote ()
5962 "Make sure that after pro/demotion cursor position is right."
5963 (let ((pos (point)))
5964 (when (save-excursion
5965 (beginning-of-line 1)
5966 (looking-at org-todo-line-regexp)
5967 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5968 (cond ((eobp) (insert " "))
5969 ((eolp) (insert " "))
5970 ((equal (char-after) ?\ ) (forward-char 1))))))
5972 (defun org-reduced-level (l)
5973 "Compute the effective level of a heading.
5974 This takes into account the setting of `org-odd-levels-only'."
5975 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5977 (defun org-get-valid-level (level &optional change)
5978 "Rectify a level change under the influence of `org-odd-levels-only'
5979 LEVEL is a current level, CHANGE is by how much the level should be
5980 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5981 even level numbers will become the next higher odd number."
5982 (if org-odd-levels-only
5983 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5984 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5985 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5986 (max 1 (+ level (or change 0)))))
5988 (if (boundp 'define-obsolete-function-alias)
5989 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5990 (define-obsolete-function-alias 'org-get-legal-level
5991 'org-get-valid-level)
5992 (define-obsolete-function-alias 'org-get-legal-level
5993 'org-get-valid-level "23.1")))
5995 (defun org-promote ()
5996 "Promote the current heading higher up the tree.
5997 If the region is active in `transient-mark-mode', promote all headings
5998 in the region."
5999 (org-back-to-heading t)
6000 (let* ((level (save-match-data (funcall outline-level)))
6001 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6002 (diff (abs (- level (length up-head) -1))))
6003 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6004 (replace-match up-head nil t)
6005 ;; Fixup tag positioning
6006 (and org-auto-align-tags (org-set-tags nil t))
6007 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6008 (run-hooks 'org-after-promote-entry-hook)))
6010 (defun org-demote ()
6011 "Demote the current heading lower down the tree.
6012 If the region is active in `transient-mark-mode', demote all headings
6013 in the region."
6014 (org-back-to-heading t)
6015 (let* ((level (save-match-data (funcall outline-level)))
6016 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6017 (diff (abs (- level (length down-head) -1))))
6018 (replace-match down-head nil t)
6019 ;; Fixup tag positioning
6020 (and org-auto-align-tags (org-set-tags nil t))
6021 (if org-adapt-indentation (org-fixup-indentation diff))
6022 (run-hooks 'org-after-demote-entry-hook)))
6024 (defun org-map-tree (fun)
6025 "Call FUN for every heading underneath the current one."
6026 (org-back-to-heading)
6027 (let ((level (funcall outline-level)))
6028 (save-excursion
6029 (funcall fun)
6030 (while (and (progn
6031 (outline-next-heading)
6032 (> (funcall outline-level) level))
6033 (not (eobp)))
6034 (funcall fun)))))
6036 (defun org-map-region (fun beg end)
6037 "Call FUN for every heading between BEG and END."
6038 (let ((org-ignore-region t))
6039 (save-excursion
6040 (setq end (copy-marker end))
6041 (goto-char beg)
6042 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6043 (< (point) end))
6044 (funcall fun))
6045 (while (and (progn
6046 (outline-next-heading)
6047 (< (point) end))
6048 (not (eobp)))
6049 (funcall fun)))))
6051 (defun org-fixup-indentation (diff)
6052 "Change the indentation in the current entry by DIFF
6053 However, if any line in the current entry has no indentation, or if it
6054 would end up with no indentation after the change, nothing at all is done."
6055 (save-excursion
6056 (let ((end (save-excursion (outline-next-heading)
6057 (point-marker)))
6058 (prohibit (if (> diff 0)
6059 "^\\S-"
6060 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6061 col)
6062 (unless (save-excursion (end-of-line 1)
6063 (re-search-forward prohibit end t))
6064 (while (and (< (point) end)
6065 (re-search-forward "^[ \t]+" end t))
6066 (goto-char (match-end 0))
6067 (setq col (current-column))
6068 (if (< diff 0) (replace-match ""))
6069 (org-indent-to-column (+ diff col))))
6070 (move-marker end nil))))
6072 (defun org-convert-to-odd-levels ()
6073 "Convert an org-mode file with all levels allowed to one with odd levels.
6074 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6075 level 5 etc."
6076 (interactive)
6077 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6078 (let ((outline-regexp org-outline-regexp)
6079 (outline-level 'org-outline-level)
6080 (org-odd-levels-only nil) n)
6081 (save-excursion
6082 (goto-char (point-min))
6083 (while (re-search-forward "^\\*\\*+ " nil t)
6084 (setq n (- (length (match-string 0)) 2))
6085 (while (>= (setq n (1- n)) 0)
6086 (org-demote))
6087 (end-of-line 1))))))
6089 (defun org-convert-to-oddeven-levels ()
6090 "Convert an org-mode file with only odd levels to one with odd and even levels.
6091 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6092 section with an even level, conversion would destroy the structure of the file. An error
6093 is signaled in this case."
6094 (interactive)
6095 (goto-char (point-min))
6096 ;; First check if there are no even levels
6097 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6098 (org-show-context t)
6099 (error "Not all levels are odd in this file. Conversion not possible."))
6100 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6101 (let ((outline-regexp org-outline-regexp)
6102 (outline-level 'org-outline-level)
6103 (org-odd-levels-only nil) n)
6104 (save-excursion
6105 (goto-char (point-min))
6106 (while (re-search-forward "^\\*\\*+ " nil t)
6107 (setq n (/ (1- (length (match-string 0))) 2))
6108 (while (>= (setq n (1- n)) 0)
6109 (org-promote))
6110 (end-of-line 1))))))
6112 (defun org-tr-level (n)
6113 "Make N odd if required."
6114 (if org-odd-levels-only (1+ (/ n 2)) n))
6116 ;;; Vertical tree motion, cutting and pasting of subtrees
6118 (defun org-move-subtree-up (&optional arg)
6119 "Move the current subtree up past ARG headlines of the same level."
6120 (interactive "p")
6121 (org-move-subtree-down (- (prefix-numeric-value arg))))
6123 (defun org-move-subtree-down (&optional arg)
6124 "Move the current subtree down past ARG headlines of the same level."
6125 (interactive "p")
6126 (setq arg (prefix-numeric-value arg))
6127 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6128 'org-get-last-sibling))
6129 (ins-point (make-marker))
6130 (cnt (abs arg))
6131 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6132 ;; Select the tree
6133 (org-back-to-heading)
6134 (setq beg0 (point))
6135 (save-excursion
6136 (setq ne-beg (org-back-over-empty-lines))
6137 (setq beg (point)))
6138 (save-match-data
6139 (save-excursion (outline-end-of-heading)
6140 (setq folded (org-invisible-p)))
6141 (outline-end-of-subtree))
6142 (outline-next-heading)
6143 (setq ne-end (org-back-over-empty-lines))
6144 (setq end (point))
6145 (goto-char beg0)
6146 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6147 ;; include less whitespace
6148 (save-excursion
6149 (goto-char beg)
6150 (forward-line (- ne-beg ne-end))
6151 (setq beg (point))))
6152 ;; Find insertion point, with error handling
6153 (while (> cnt 0)
6154 (or (and (funcall movfunc) (looking-at outline-regexp))
6155 (progn (goto-char beg0)
6156 (error "Cannot move past superior level or buffer limit")))
6157 (setq cnt (1- cnt)))
6158 (if (> arg 0)
6159 ;; Moving forward - still need to move over subtree
6160 (progn (org-end-of-subtree t t)
6161 (save-excursion
6162 (org-back-over-empty-lines)
6163 (or (bolp) (newline)))))
6164 (setq ne-ins (org-back-over-empty-lines))
6165 (move-marker ins-point (point))
6166 (setq txt (buffer-substring beg end))
6167 (org-save-markers-in-region beg end)
6168 (delete-region beg end)
6169 (org-remove-empty-overlays-at beg)
6170 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6171 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6172 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6173 (let ((bbb (point)))
6174 (insert-before-markers txt)
6175 (org-reinstall-markers-in-region bbb)
6176 (move-marker ins-point bbb))
6177 (or (bolp) (insert "\n"))
6178 (setq ins-end (point))
6179 (goto-char ins-point)
6180 (org-skip-whitespace)
6181 (when (and (< arg 0)
6182 (org-first-sibling-p)
6183 (> ne-ins ne-beg))
6184 ;; Move whitespace back to beginning
6185 (save-excursion
6186 (goto-char ins-end)
6187 (let ((kill-whole-line t))
6188 (kill-line (- ne-ins ne-beg)) (point)))
6189 (insert (make-string (- ne-ins ne-beg) ?\n)))
6190 (move-marker ins-point nil)
6191 (if folded
6192 (hide-subtree)
6193 (org-show-entry)
6194 (show-children)
6195 (org-cycle-hide-drawers 'children))
6196 (org-clean-visibility-after-subtree-move)))
6198 (defvar org-subtree-clip ""
6199 "Clipboard for cut and paste of subtrees.
6200 This is actually only a copy of the kill, because we use the normal kill
6201 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6203 (defvar org-subtree-clip-folded nil
6204 "Was the last copied subtree folded?
6205 This is used to fold the tree back after pasting.")
6207 (defun org-cut-subtree (&optional n)
6208 "Cut the current subtree into the clipboard.
6209 With prefix arg N, cut this many sequential subtrees.
6210 This is a short-hand for marking the subtree and then cutting it."
6211 (interactive "p")
6212 (org-copy-subtree n 'cut))
6214 (defun org-copy-subtree (&optional n cut force-store-markers)
6215 "Cut the current subtree into the clipboard.
6216 With prefix arg N, cut this many sequential subtrees.
6217 This is a short-hand for marking the subtree and then copying it.
6218 If CUT is non-nil, actually cut the subtree.
6219 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6220 of some markers in the region, even if CUT is non-nil. This is
6221 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6222 (interactive "p")
6223 (let (beg end folded (beg0 (point)))
6224 (if (interactive-p)
6225 (org-back-to-heading nil) ; take what looks like a subtree
6226 (org-back-to-heading t)) ; take what is really there
6227 (org-back-over-empty-lines)
6228 (setq beg (point))
6229 (skip-chars-forward " \t\r\n")
6230 (save-match-data
6231 (save-excursion (outline-end-of-heading)
6232 (setq folded (org-invisible-p)))
6233 (condition-case nil
6234 (org-forward-same-level (1- n) t)
6235 (error nil))
6236 (org-end-of-subtree t t))
6237 (org-back-over-empty-lines)
6238 (setq end (point))
6239 (goto-char beg0)
6240 (when (> end beg)
6241 (setq org-subtree-clip-folded folded)
6242 (when (or cut force-store-markers)
6243 (org-save-markers-in-region beg end))
6244 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6245 (setq org-subtree-clip (current-kill 0))
6246 (message "%s: Subtree(s) with %d characters"
6247 (if cut "Cut" "Copied")
6248 (length org-subtree-clip)))))
6250 (defun org-paste-subtree (&optional level tree for-yank)
6251 "Paste the clipboard as a subtree, with modification of headline level.
6252 The entire subtree is promoted or demoted in order to match a new headline
6253 level.
6255 If the cursor is at the beginning of a headline, the same level as
6256 that headline is used to paste the tree
6258 If not, the new level is derived from the *visible* headings
6259 before and after the insertion point, and taken to be the inferior headline
6260 level of the two. So if the previous visible heading is level 3 and the
6261 next is level 4 (or vice versa), level 4 will be used for insertion.
6262 This makes sure that the subtree remains an independent subtree and does
6263 not swallow low level entries.
6265 You can also force a different level, either by using a numeric prefix
6266 argument, or by inserting the heading marker by hand. For example, if the
6267 cursor is after \"*****\", then the tree will be shifted to level 5.
6269 If optional TREE is given, use this text instead of the kill ring.
6271 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6272 move back over whitespace before inserting, and move point to the end of
6273 the inserted text when done."
6274 (interactive "P")
6275 (setq tree (or tree (and kill-ring (current-kill 0))))
6276 (unless (org-kill-is-subtree-p tree)
6277 (error "%s"
6278 (substitute-command-keys
6279 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6280 (let* ((visp (not (org-invisible-p)))
6281 (txt tree)
6282 (^re (concat "^\\(" outline-regexp "\\)"))
6283 (re (concat "\\(" outline-regexp "\\)"))
6284 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6286 (old-level (if (string-match ^re txt)
6287 (- (match-end 0) (match-beginning 0) 1)
6288 -1))
6289 (force-level (cond (level (prefix-numeric-value level))
6290 ((and (looking-at "[ \t]*$")
6291 (string-match
6292 ^re_ (buffer-substring
6293 (point-at-bol) (point))))
6294 (- (match-end 1) (match-beginning 1)))
6295 ((and (bolp)
6296 (looking-at org-outline-regexp))
6297 (- (match-end 0) (point) 1))
6298 (t nil)))
6299 (previous-level (save-excursion
6300 (condition-case nil
6301 (progn
6302 (outline-previous-visible-heading 1)
6303 (if (looking-at re)
6304 (- (match-end 0) (match-beginning 0) 1)
6306 (error 1))))
6307 (next-level (save-excursion
6308 (condition-case nil
6309 (progn
6310 (or (looking-at outline-regexp)
6311 (outline-next-visible-heading 1))
6312 (if (looking-at re)
6313 (- (match-end 0) (match-beginning 0) 1)
6315 (error 1))))
6316 (new-level (or force-level (max previous-level next-level)))
6317 (shift (if (or (= old-level -1)
6318 (= new-level -1)
6319 (= old-level new-level))
6321 (- new-level old-level)))
6322 (delta (if (> shift 0) -1 1))
6323 (func (if (> shift 0) 'org-demote 'org-promote))
6324 (org-odd-levels-only nil)
6325 beg end newend)
6326 ;; Remove the forced level indicator
6327 (if force-level
6328 (delete-region (point-at-bol) (point)))
6329 ;; Paste
6330 (beginning-of-line 1)
6331 (unless for-yank (org-back-over-empty-lines))
6332 (setq beg (point))
6333 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6334 (insert-before-markers txt)
6335 (unless (string-match "\n\\'" txt) (insert "\n"))
6336 (setq newend (point))
6337 (org-reinstall-markers-in-region beg)
6338 (setq end (point))
6339 (goto-char beg)
6340 (skip-chars-forward " \t\n\r")
6341 (setq beg (point))
6342 (if (and (org-invisible-p) visp)
6343 (save-excursion (outline-show-heading)))
6344 ;; Shift if necessary
6345 (unless (= shift 0)
6346 (save-restriction
6347 (narrow-to-region beg end)
6348 (while (not (= shift 0))
6349 (org-map-region func (point-min) (point-max))
6350 (setq shift (+ delta shift)))
6351 (goto-char (point-min))
6352 (setq newend (point-max))))
6353 (when (or (interactive-p) for-yank)
6354 (message "Clipboard pasted as level %d subtree" new-level))
6355 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6356 kill-ring
6357 (eq org-subtree-clip (current-kill 0))
6358 org-subtree-clip-folded)
6359 ;; The tree was folded before it was killed/copied
6360 (hide-subtree))
6361 (and for-yank (goto-char newend))))
6363 (defun org-kill-is-subtree-p (&optional txt)
6364 "Check if the current kill is an outline subtree, or a set of trees.
6365 Returns nil if kill does not start with a headline, or if the first
6366 headline level is not the largest headline level in the tree.
6367 So this will actually accept several entries of equal levels as well,
6368 which is OK for `org-paste-subtree'.
6369 If optional TXT is given, check this string instead of the current kill."
6370 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6371 (start-level (and kill
6372 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6373 org-outline-regexp "\\)")
6374 kill)
6375 (- (match-end 2) (match-beginning 2) 1)))
6376 (re (concat "^" org-outline-regexp))
6377 (start (1+ (or (match-beginning 2) -1))))
6378 (if (not start-level)
6379 (progn
6380 nil) ;; does not even start with a heading
6381 (catch 'exit
6382 (while (setq start (string-match re kill (1+ start)))
6383 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6384 (throw 'exit nil)))
6385 t))))
6387 (defvar org-markers-to-move nil
6388 "Markers that should be moved with a cut-and-paste operation.
6389 Those markers are stored together with their positions relative to
6390 the start of the region.")
6392 (defun org-save-markers-in-region (beg end)
6393 "Check markers in region.
6394 If these markers are between BEG and END, record their position relative
6395 to BEG, so that after moving the block of text, we can put the markers back
6396 into place.
6397 This function gets called just before an entry or tree gets cut from the
6398 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6399 called immediately, to move the markers with the entries."
6400 (setq org-markers-to-move nil)
6401 (when (featurep 'org-clock)
6402 (org-clock-save-markers-for-cut-and-paste beg end))
6403 (when (featurep 'org-agenda)
6404 (org-agenda-save-markers-for-cut-and-paste beg end)))
6406 (defun org-check-and-save-marker (marker beg end)
6407 "Check if MARKER is between BEG and END.
6408 If yes, remember the marker and the distance to BEG."
6409 (when (and (marker-buffer marker)
6410 (equal (marker-buffer marker) (current-buffer)))
6411 (if (and (>= marker beg) (< marker end))
6412 (push (cons marker (- marker beg)) org-markers-to-move))))
6414 (defun org-reinstall-markers-in-region (beg)
6415 "Move all remembered markers to their position relative to BEG."
6416 (mapc (lambda (x)
6417 (move-marker (car x) (+ beg (cdr x))))
6418 org-markers-to-move)
6419 (setq org-markers-to-move nil))
6421 (defun org-narrow-to-subtree ()
6422 "Narrow buffer to the current subtree."
6423 (interactive)
6424 (save-excursion
6425 (save-match-data
6426 (narrow-to-region
6427 (progn (org-back-to-heading t) (point))
6428 (progn (org-end-of-subtree t t) (point))))))
6430 (defun org-clone-subtree-with-time-shift (n &optional shift)
6431 "Clone the task (subtree) at point N times.
6432 The clones will be inserted as siblings.
6434 In interactive use, the user will be prompted for the number of clones
6435 to be produced, and for a time SHIFT, which may be a repeater as used
6436 in time stamps, for example `+3d'.
6438 When a valid repeater is given and the entry contains any time stamps,
6439 the clones will become a sequence in time, with time stamps in the
6440 subtree shifted for each clone produced. If SHIFT is nil or the
6441 empty string, time stamps will be left alone.
6443 If the original subtree did contain time stamps with a repeater,
6444 the following will happen:
6445 - the repeater will be removed in each clone
6446 - an additional clone will be produced, with the current, unshifted
6447 date(s) in the entry.
6448 - the original entry will be placed *after* all the clones, with
6449 repeater intact.
6450 - the start days in the repeater in the original entry will be shifted
6451 to past the last clone.
6452 I this way you can spell out a number of instances of a repeating task,
6453 and still retain the repeater to cover future instances of the task."
6454 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6455 (let (beg end template task
6456 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6457 (if (not (and (integerp n) (> n 0)))
6458 (error "Invalid number of replications %s" n))
6459 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6460 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6461 shift)))
6462 (error "Invalid shift specification %s" shift))
6463 (when doshift
6464 (setq shift-n (string-to-number (match-string 1 shift))
6465 shift-what (cdr (assoc (match-string 2 shift)
6466 '(("d" . day) ("w" . week)
6467 ("m" . month) ("y" . year))))))
6468 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6469 (setq nmin 1 nmax n)
6470 (org-back-to-heading t)
6471 (setq beg (point))
6472 (org-end-of-subtree t t)
6473 (setq end (point))
6474 (setq template (buffer-substring beg end))
6475 (when (and doshift
6476 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6477 (delete-region beg end)
6478 (setq end beg)
6479 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6480 (goto-char end)
6481 (loop for n from nmin to nmax do
6482 (if (not doshift)
6483 (setq task template)
6484 (with-temp-buffer
6485 (insert template)
6486 (org-mode)
6487 (goto-char (point-min))
6488 (while (re-search-forward org-ts-regexp-both nil t)
6489 (org-timestamp-change (* n shift-n) shift-what))
6490 (unless (= n n-no-remove)
6491 (goto-char (point-min))
6492 (while (re-search-forward org-ts-regexp nil t)
6493 (save-excursion
6494 (goto-char (match-beginning 0))
6495 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6496 (delete-region (match-beginning 1) (match-end 1))))))
6497 (setq task (buffer-string))))
6498 (insert task))
6499 (goto-char beg)))
6501 ;;; Outline Sorting
6503 (defun org-sort (with-case)
6504 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6505 Optional argument WITH-CASE means sort case-sensitively.
6506 With a double prefix argument, also remove duplicate entries."
6507 (interactive "P")
6508 (if (org-at-table-p)
6509 (org-call-with-arg 'org-table-sort-lines with-case)
6510 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6512 (defun org-sort-remove-invisible (s)
6513 (remove-text-properties 0 (length s) org-rm-props s)
6514 (while (string-match org-bracket-link-regexp s)
6515 (setq s (replace-match (if (match-end 2)
6516 (match-string 3 s)
6517 (match-string 1 s)) t t s)))
6520 (defvar org-priority-regexp) ; defined later in the file
6522 (defvar org-after-sorting-entries-or-items-hook nil
6523 "Hook that is run after a bunch of entries or items have been sorted.
6524 When children are sorted, the cursor is in the parent line when this
6525 hook gets called. When a region or a plain list is sorted, the cursor
6526 will be in the first entry of the sorted region/list.")
6528 (defun org-sort-entries-or-items
6529 (&optional with-case sorting-type getkey-func compare-func property)
6530 "Sort entries on a certain level of an outline tree, or plain list items.
6531 If there is an active region, the entries in the region are sorted.
6532 Else, if the cursor is before the first entry, sort the top-level items.
6533 Else, the children of the entry at point are sorted.
6534 If the cursor is at the first item in a plain list, the list items will be
6535 sorted.
6537 Sorting can be alphabetically, numerically, by date/time as given by
6538 a time stamp, by a property or by priority.
6540 The command prompts for the sorting type unless it has been given to the
6541 function through the SORTING-TYPE argument, which needs to a character,
6542 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6543 precise meaning of each character:
6545 n Numerically, by converting the beginning of the entry/item to a number.
6546 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6547 t By date/time, either the first active time stamp in the entry, or, if
6548 none exist, by the first inactive one.
6549 In items, only the first line will be chekced.
6550 s By the scheduled date/time.
6551 d By deadline date/time.
6552 c By creation time, which is assumed to be the first inactive time stamp
6553 at the beginning of a line.
6554 p By priority according to the cookie.
6555 r By the value of a property.
6557 Capital letters will reverse the sort order.
6559 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6560 called with point at the beginning of the record. It must return either
6561 a string or a number that should serve as the sorting key for that record.
6563 Comparing entries ignores case by default. However, with an optional argument
6564 WITH-CASE, the sorting considers case as well."
6565 (interactive "P")
6566 (let ((case-func (if with-case 'identity 'downcase))
6567 start beg end stars re re2
6568 txt what tmp plain-list-p)
6569 ;; Find beginning and end of region to sort
6570 (cond
6571 ((org-region-active-p)
6572 ;; we will sort the region
6573 (setq end (region-end)
6574 what "region")
6575 (goto-char (region-beginning))
6576 (if (not (org-on-heading-p)) (outline-next-heading))
6577 (setq start (point)))
6578 ((org-at-item-p)
6579 ;; we will sort this plain list
6580 (org-beginning-of-item-list) (setq start (point))
6581 (org-end-of-item-list) (setq end (point))
6582 (goto-char start)
6583 (setq plain-list-p t
6584 what "plain list"))
6585 ((or (org-on-heading-p)
6586 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6587 ;; we will sort the children of the current headline
6588 (org-back-to-heading)
6589 (setq start (point)
6590 end (progn (org-end-of-subtree t t)
6591 (org-back-over-empty-lines)
6592 (point))
6593 what "children")
6594 (goto-char start)
6595 (show-subtree)
6596 (outline-next-heading))
6598 ;; we will sort the top-level entries in this file
6599 (goto-char (point-min))
6600 (or (org-on-heading-p) (outline-next-heading))
6601 (setq start (point) end (point-max) what "top-level")
6602 (goto-char start)
6603 (show-all)))
6605 (setq beg (point))
6606 (if (>= beg end) (error "Nothing to sort"))
6608 (unless plain-list-p
6609 (looking-at "\\(\\*+\\)")
6610 (setq stars (match-string 1)
6611 re (concat "^" (regexp-quote stars) " +")
6612 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6613 txt (buffer-substring beg end))
6614 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6615 (if (and (not (equal stars "*")) (string-match re2 txt))
6616 (error "Region to sort contains a level above the first entry")))
6618 (unless sorting-type
6619 (message
6620 (if plain-list-p
6621 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6622 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6623 [t]ime [s]cheduled [d]eadline [c]reated
6624 A/N/T/S/D/C/P/O/F means reversed:")
6625 what)
6626 (setq sorting-type (read-char-exclusive))
6628 (and (= (downcase sorting-type) ?f)
6629 (setq getkey-func
6630 (org-icompleting-read "Sort using function: "
6631 obarray 'fboundp t nil nil))
6632 (setq getkey-func (intern getkey-func)))
6634 (and (= (downcase sorting-type) ?r)
6635 (setq property
6636 (org-icompleting-read "Property: "
6637 (mapcar 'list (org-buffer-property-keys t))
6638 nil t))))
6640 (message "Sorting entries...")
6642 (save-restriction
6643 (narrow-to-region start end)
6645 (let ((dcst (downcase sorting-type))
6646 (case-fold-search nil)
6647 (now (current-time)))
6648 (sort-subr
6649 (/= dcst sorting-type)
6650 ;; This function moves to the beginning character of the "record" to
6651 ;; be sorted.
6652 (if plain-list-p
6653 (lambda nil
6654 (if (org-at-item-p) t (goto-char (point-max))))
6655 (lambda nil
6656 (if (re-search-forward re nil t)
6657 (goto-char (match-beginning 0))
6658 (goto-char (point-max)))))
6659 ;; This function moves to the last character of the "record" being
6660 ;; sorted.
6661 (if plain-list-p
6662 'org-end-of-item
6663 (lambda nil
6664 (save-match-data
6665 (condition-case nil
6666 (outline-forward-same-level 1)
6667 (error
6668 (goto-char (point-max)))))))
6670 ;; This function returns the value that gets sorted against.
6671 (if plain-list-p
6672 (lambda nil
6673 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6674 (cond
6675 ((= dcst ?n)
6676 (string-to-number (buffer-substring (match-end 0)
6677 (point-at-eol))))
6678 ((= dcst ?a)
6679 (buffer-substring (match-end 0) (point-at-eol)))
6680 ((= dcst ?t)
6681 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6682 (re-search-forward org-ts-regexp-both
6683 (point-at-eol) t))
6684 (org-time-string-to-seconds (match-string 0))
6685 (org-float-time now)))
6686 ((= dcst ?f)
6687 (if getkey-func
6688 (progn
6689 (setq tmp (funcall getkey-func))
6690 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6691 tmp)
6692 (error "Invalid key function `%s'" getkey-func)))
6693 (t (error "Invalid sorting type `%c'" sorting-type)))))
6694 (lambda nil
6695 (cond
6696 ((= dcst ?n)
6697 (if (looking-at org-complex-heading-regexp)
6698 (string-to-number (match-string 4))
6699 nil))
6700 ((= dcst ?a)
6701 (if (looking-at org-complex-heading-regexp)
6702 (funcall case-func (match-string 4))
6703 nil))
6704 ((= dcst ?t)
6705 (let ((end (save-excursion (outline-next-heading) (point))))
6706 (if (or (re-search-forward org-ts-regexp end t)
6707 (re-search-forward org-ts-regexp-both end t))
6708 (org-time-string-to-seconds (match-string 0))
6709 (org-float-time now))))
6710 ((= dcst ?c)
6711 (let ((end (save-excursion (outline-next-heading) (point))))
6712 (if (re-search-forward
6713 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6714 end t)
6715 (org-time-string-to-seconds (match-string 0))
6716 (org-float-time now))))
6717 ((= dcst ?s)
6718 (let ((end (save-excursion (outline-next-heading) (point))))
6719 (if (re-search-forward org-scheduled-time-regexp end t)
6720 (org-time-string-to-seconds (match-string 1))
6721 (org-float-time now))))
6722 ((= dcst ?d)
6723 (let ((end (save-excursion (outline-next-heading) (point))))
6724 (if (re-search-forward org-deadline-time-regexp end t)
6725 (org-time-string-to-seconds (match-string 1))
6726 (org-float-time now))))
6727 ((= dcst ?p)
6728 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6729 (string-to-char (match-string 2))
6730 org-default-priority))
6731 ((= dcst ?r)
6732 (or (org-entry-get nil property) ""))
6733 ((= dcst ?o)
6734 (if (looking-at org-complex-heading-regexp)
6735 (- 9999 (length (member (match-string 2)
6736 org-todo-keywords-1)))))
6737 ((= dcst ?f)
6738 (if getkey-func
6739 (progn
6740 (setq tmp (funcall getkey-func))
6741 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6742 tmp)
6743 (error "Invalid key function `%s'" getkey-func)))
6744 (t (error "Invalid sorting type `%c'" sorting-type)))))
6746 (cond
6747 ((= dcst ?a) 'string<)
6748 ((= dcst ?f) compare-func)
6749 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6750 (t nil)))))
6751 (run-hooks 'org-after-sorting-entries-or-items-hook)
6752 (message "Sorting entries...done")))
6754 (defun org-do-sort (table what &optional with-case sorting-type)
6755 "Sort TABLE of WHAT according to SORTING-TYPE.
6756 The user will be prompted for the SORTING-TYPE if the call to this
6757 function does not specify it. WHAT is only for the prompt, to indicate
6758 what is being sorted. The sorting key will be extracted from
6759 the car of the elements of the table.
6760 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6761 (unless sorting-type
6762 (message
6763 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6764 what)
6765 (setq sorting-type (read-char-exclusive)))
6766 (let ((dcst (downcase sorting-type))
6767 extractfun comparefun)
6768 ;; Define the appropriate functions
6769 (cond
6770 ((= dcst ?n)
6771 (setq extractfun 'string-to-number
6772 comparefun (if (= dcst sorting-type) '< '>)))
6773 ((= dcst ?a)
6774 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6775 (lambda(x) (downcase (org-sort-remove-invisible x))))
6776 comparefun (if (= dcst sorting-type)
6777 'string<
6778 (lambda (a b) (and (not (string< a b))
6779 (not (string= a b)))))))
6780 ((= dcst ?t)
6781 (setq extractfun
6782 (lambda (x)
6783 (if (or (string-match org-ts-regexp x)
6784 (string-match org-ts-regexp-both x))
6785 (org-float-time
6786 (org-time-string-to-time (match-string 0 x)))
6788 comparefun (if (= dcst sorting-type) '< '>)))
6789 (t (error "Invalid sorting type `%c'" sorting-type)))
6791 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6792 table)
6793 (lambda (a b) (funcall comparefun (car a) (car b))))))
6796 ;;; The orgstruct minor mode
6798 ;; Define a minor mode which can be used in other modes in order to
6799 ;; integrate the org-mode structure editing commands.
6801 ;; This is really a hack, because the org-mode structure commands use
6802 ;; keys which normally belong to the major mode. Here is how it
6803 ;; works: The minor mode defines all the keys necessary to operate the
6804 ;; structure commands, but wraps the commands into a function which
6805 ;; tests if the cursor is currently at a headline or a plain list
6806 ;; item. If that is the case, the structure command is used,
6807 ;; temporarily setting many Org-mode variables like regular
6808 ;; expressions for filling etc. However, when any of those keys is
6809 ;; used at a different location, function uses `key-binding' to look
6810 ;; up if the key has an associated command in another currently active
6811 ;; keymap (minor modes, major mode, global), and executes that
6812 ;; command. There might be problems if any of the keys is otherwise
6813 ;; used as a prefix key.
6815 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6816 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6817 ;; addresses this by checking explicitly for both bindings.
6819 (defvar orgstruct-mode-map (make-sparse-keymap)
6820 "Keymap for the minor `orgstruct-mode'.")
6822 (defvar org-local-vars nil
6823 "List of local variables, for use by `orgstruct-mode'")
6825 ;;;###autoload
6826 (define-minor-mode orgstruct-mode
6827 "Toggle the minor more `orgstruct-mode'.
6828 This mode is for using Org-mode structure commands in other modes.
6829 The following key behave as if Org-mode was active, if the cursor
6830 is on a headline, or on a plain list item (both in the definition
6831 of Org-mode).
6833 M-up Move entry/item up
6834 M-down Move entry/item down
6835 M-left Promote
6836 M-right Demote
6837 M-S-up Move entry/item up
6838 M-S-down Move entry/item down
6839 M-S-left Promote subtree
6840 M-S-right Demote subtree
6841 M-q Fill paragraph and items like in Org-mode
6842 C-c ^ Sort entries
6843 C-c - Cycle list bullet
6844 TAB Cycle item visibility
6845 M-RET Insert new heading/item
6846 S-M-RET Insert new TODO heading / Checkbox item
6847 C-c C-c Set tags / toggle checkbox"
6848 nil " OrgStruct" nil
6849 (org-load-modules-maybe)
6850 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6852 ;;;###autoload
6853 (defun turn-on-orgstruct ()
6854 "Unconditionally turn on `orgstruct-mode'."
6855 (orgstruct-mode 1))
6857 (defun orgstruct++-mode (&optional arg)
6858 "Toggle `orgstruct-mode', the enhanced version of it.
6859 In addition to setting orgstruct-mode, this also exports all indentation
6860 and autofilling variables from org-mode into the buffer. It will also
6861 recognize item context in multiline items.
6862 Note that turning off orgstruct-mode will *not* remove the
6863 indentation/paragraph settings. This can only be done by refreshing the
6864 major mode, for example with \\[normal-mode]."
6865 (interactive "P")
6866 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6867 (if (< arg 1)
6868 (orgstruct-mode -1)
6869 (orgstruct-mode 1)
6870 (let (var val)
6871 (mapc
6872 (lambda (x)
6873 (when (string-match
6874 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6875 (symbol-name (car x)))
6876 (setq var (car x) val (nth 1 x))
6877 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6878 org-local-vars)
6879 (org-set-local 'orgstruct-is-++ t))))
6881 (defvar orgstruct-is-++ nil
6882 "Is orgstruct-mode in ++ version in the current-buffer?")
6883 (make-variable-buffer-local 'orgstruct-is-++)
6885 ;;;###autoload
6886 (defun turn-on-orgstruct++ ()
6887 "Unconditionally turn on `orgstruct++-mode'."
6888 (orgstruct++-mode 1))
6890 (defun orgstruct-error ()
6891 "Error when there is no default binding for a structure key."
6892 (interactive)
6893 (error "This key has no function outside structure elements"))
6895 (defun orgstruct-setup ()
6896 "Setup orgstruct keymaps."
6897 (let ((nfunc 0)
6898 (bindings
6899 (list
6900 '([(meta up)] org-metaup)
6901 '([(meta down)] org-metadown)
6902 '([(meta left)] org-metaleft)
6903 '([(meta right)] org-metaright)
6904 '([(meta shift up)] org-shiftmetaup)
6905 '([(meta shift down)] org-shiftmetadown)
6906 '([(meta shift left)] org-shiftmetaleft)
6907 '([(meta shift right)] org-shiftmetaright)
6908 '([?\e (up)] org-metaup)
6909 '([?\e (down)] org-metadown)
6910 '([?\e (left)] org-metaleft)
6911 '([?\e (right)] org-metaright)
6912 '([?\e (shift up)] org-shiftmetaup)
6913 '([?\e (shift down)] org-shiftmetadown)
6914 '([?\e (shift left)] org-shiftmetaleft)
6915 '([?\e (shift right)] org-shiftmetaright)
6916 '([(shift up)] org-shiftup)
6917 '([(shift down)] org-shiftdown)
6918 '([(shift left)] org-shiftleft)
6919 '([(shift right)] org-shiftright)
6920 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6921 '("\M-q" fill-paragraph)
6922 '("\C-c^" org-sort)
6923 '("\C-c-" org-cycle-list-bullet)))
6924 elt key fun cmd)
6925 (while (setq elt (pop bindings))
6926 (setq nfunc (1+ nfunc))
6927 (setq key (org-key (car elt))
6928 fun (nth 1 elt)
6929 cmd (orgstruct-make-binding fun nfunc key))
6930 (org-defkey orgstruct-mode-map key cmd))
6932 ;; Special treatment needed for TAB and RET
6933 (org-defkey orgstruct-mode-map [(tab)]
6934 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6935 (org-defkey orgstruct-mode-map "\C-i"
6936 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6938 (org-defkey orgstruct-mode-map "\M-\C-m"
6939 (orgstruct-make-binding 'org-insert-heading 105
6940 "\M-\C-m" [(meta return)]))
6941 (org-defkey orgstruct-mode-map [(meta return)]
6942 (orgstruct-make-binding 'org-insert-heading 106
6943 [(meta return)] "\M-\C-m"))
6945 (org-defkey orgstruct-mode-map [(shift meta return)]
6946 (orgstruct-make-binding 'org-insert-todo-heading 107
6947 [(meta return)] "\M-\C-m"))
6949 (org-defkey orgstruct-mode-map "\e\C-m"
6950 (orgstruct-make-binding 'org-insert-heading 108
6951 "\e\C-m" [?\e (return)]))
6952 (org-defkey orgstruct-mode-map [?\e (return)]
6953 (orgstruct-make-binding 'org-insert-heading 109
6954 [?\e (return)] "\e\C-m"))
6955 (org-defkey orgstruct-mode-map [?\e (shift return)]
6956 (orgstruct-make-binding 'org-insert-todo-heading 110
6957 [?\e (return)] "\e\C-m"))
6959 (unless org-local-vars
6960 (setq org-local-vars (org-get-local-variables)))
6964 (defun orgstruct-make-binding (fun n &rest keys)
6965 "Create a function for binding in the structure minor mode.
6966 FUN is the command to call inside a table. N is used to create a unique
6967 command name. KEYS are keys that should be checked in for a command
6968 to execute outside of tables."
6969 (eval
6970 (list 'defun
6971 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6972 '(arg)
6973 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6974 "Outside of structure, run the binding of `"
6975 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6976 "'.")
6977 '(interactive "p")
6978 (list 'if
6979 `(org-context-p 'headline 'item
6980 (and orgstruct-is-++
6981 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6982 'item-body))
6983 (list 'org-run-like-in-org-mode (list 'quote fun))
6984 (list 'let '(orgstruct-mode)
6985 (list 'call-interactively
6986 (append '(or)
6987 (mapcar (lambda (k)
6988 (list 'key-binding k))
6989 keys)
6990 '('orgstruct-error))))))))
6992 (defun org-context-p (&rest contexts)
6993 "Check if local context is any of CONTEXTS.
6994 Possible values in the list of contexts are `table', `headline', and `item'."
6995 (let ((pos (point)))
6996 (goto-char (point-at-bol))
6997 (prog1 (or (and (memq 'table contexts)
6998 (looking-at "[ \t]*|"))
6999 (and (memq 'headline contexts)
7000 ;;????????? (looking-at "\\*+"))
7001 (looking-at outline-regexp))
7002 (and (memq 'item contexts)
7003 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7004 (and (memq 'item-body contexts)
7005 (org-in-item-p)))
7006 (goto-char pos))))
7008 (defun org-get-local-variables ()
7009 "Return a list of all local variables in an org-mode buffer."
7010 (let (varlist)
7011 (with-current-buffer (get-buffer-create "*Org tmp*")
7012 (erase-buffer)
7013 (org-mode)
7014 (setq varlist (buffer-local-variables)))
7015 (kill-buffer "*Org tmp*")
7016 (delq nil
7017 (mapcar
7018 (lambda (x)
7019 (setq x
7020 (if (symbolp x)
7021 (list x)
7022 (list (car x) (list 'quote (cdr x)))))
7023 (if (string-match
7024 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7025 (symbol-name (car x)))
7026 x nil))
7027 varlist))))
7029 ;;;###autoload
7030 (defun org-run-like-in-org-mode (cmd)
7031 "Run a command, pretending that the current buffer is in Org-mode.
7032 This will temporarily bind local variables that are typically bound in
7033 Org-mode to the values they have in Org-mode, and then interactively
7034 call CMD."
7035 (org-load-modules-maybe)
7036 (unless org-local-vars
7037 (setq org-local-vars (org-get-local-variables)))
7038 (eval (list 'let org-local-vars
7039 (list 'call-interactively (list 'quote cmd)))))
7041 ;;;; Archiving
7043 (defun org-get-category (&optional pos)
7044 "Get the category applying to position POS."
7045 (get-text-property (or pos (point)) 'org-category))
7047 (defun org-refresh-category-properties ()
7048 "Refresh category text properties in the buffer."
7049 (let ((def-cat (cond
7050 ((null org-category)
7051 (if buffer-file-name
7052 (file-name-sans-extension
7053 (file-name-nondirectory buffer-file-name))
7054 "???"))
7055 ((symbolp org-category) (symbol-name org-category))
7056 (t org-category)))
7057 beg end cat pos optionp)
7058 (org-unmodified
7059 (save-excursion
7060 (save-restriction
7061 (widen)
7062 (goto-char (point-min))
7063 (put-text-property (point) (point-max) 'org-category def-cat)
7064 (while (re-search-forward
7065 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7066 (setq pos (match-end 0)
7067 optionp (equal (char-after (match-beginning 0)) ?#)
7068 cat (org-trim (match-string 2)))
7069 (if optionp
7070 (setq beg (point-at-bol) end (point-max))
7071 (org-back-to-heading t)
7072 (setq beg (point) end (org-end-of-subtree t t)))
7073 (put-text-property beg end 'org-category cat)
7074 (goto-char pos)))))))
7077 ;;;; Link Stuff
7079 ;;; Link abbreviations
7081 (defun org-link-expand-abbrev (link)
7082 "Apply replacements as defined in `org-link-abbrev-alist."
7083 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7084 (let* ((key (match-string 1 link))
7085 (as (or (assoc key org-link-abbrev-alist-local)
7086 (assoc key org-link-abbrev-alist)))
7087 (tag (and (match-end 2) (match-string 3 link)))
7088 rpl)
7089 (if (not as)
7090 link
7091 (setq rpl (cdr as))
7092 (cond
7093 ((symbolp rpl) (funcall rpl tag))
7094 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7095 ((string-match "%h" rpl)
7096 (replace-match (url-hexify-string (or tag "")) t t rpl))
7097 (t (concat rpl tag)))))
7098 link))
7100 ;;; Storing and inserting links
7102 (defvar org-insert-link-history nil
7103 "Minibuffer history for links inserted with `org-insert-link'.")
7105 (defvar org-stored-links nil
7106 "Contains the links stored with `org-store-link'.")
7108 (defvar org-store-link-plist nil
7109 "Plist with info about the most recently link created with `org-store-link'.")
7111 (defvar org-link-protocols nil
7112 "Link protocols added to Org-mode using `org-add-link-type'.")
7114 (defvar org-store-link-functions nil
7115 "List of functions that are called to create and store a link.
7116 Each function will be called in turn until one returns a non-nil
7117 value. Each function should check if it is responsible for creating
7118 this link (for example by looking at the major mode).
7119 If not, it must exit and return nil.
7120 If yes, it should return a non-nil value after a calling
7121 `org-store-link-props' with a list of properties and values.
7122 Special properties are:
7124 :type The link prefix. like \"http\". This must be given.
7125 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7126 This is obligatory as well.
7127 :description Optional default description for the second pair
7128 of brackets in an Org-mode link. The user can still change
7129 this when inserting this link into an Org-mode buffer.
7131 In addition to these, any additional properties can be specified
7132 and then used in remember templates.")
7134 (defun org-add-link-type (type &optional follow export)
7135 "Add TYPE to the list of `org-link-types'.
7136 Re-compute all regular expressions depending on `org-link-types'
7138 FOLLOW and EXPORT are two functions.
7140 FOLLOW should take the link path as the single argument and do whatever
7141 is necessary to follow the link, for example find a file or display
7142 a mail message.
7144 EXPORT should format the link path for export to one of the export formats.
7145 It should be a function accepting three arguments:
7147 path the path of the link, the text after the prefix (like \"http:\")
7148 desc the description of the link, if any, nil if there was no description
7149 format the export format, a symbol like `html' or `latex'.
7151 The function may use the FORMAT information to return different values
7152 depending on the format. The return value will be put literally into
7153 the exported file.
7154 Org-mode has a built-in default for exporting links. If you are happy with
7155 this default, there is no need to define an export function for the link
7156 type. For a simple example of an export function, see `org-bbdb.el'."
7157 (add-to-list 'org-link-types type t)
7158 (org-make-link-regexps)
7159 (if (assoc type org-link-protocols)
7160 (setcdr (assoc type org-link-protocols) (list follow export))
7161 (push (list type follow export) org-link-protocols)))
7163 (defvar org-agenda-buffer-name)
7165 ;;;###autoload
7166 (defun org-store-link (arg)
7167 "\\<org-mode-map>Store an org-link to the current location.
7168 This link is added to `org-stored-links' and can later be inserted
7169 into an org-buffer with \\[org-insert-link].
7171 For some link types, a prefix arg is interpreted:
7172 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7173 For file links, arg negates `org-context-in-file-links'."
7174 (interactive "P")
7175 (org-load-modules-maybe)
7176 (setq org-store-link-plist nil) ; reset
7177 (let ((outline-regexp (org-get-limited-outline-regexp))
7178 link cpltxt desc description search txt custom-id)
7179 (cond
7181 ((run-hook-with-args-until-success 'org-store-link-functions)
7182 (setq link (plist-get org-store-link-plist :link)
7183 desc (or (plist-get org-store-link-plist :description) link)))
7185 ((equal (buffer-name) "*Org Edit Src Example*")
7186 (let (label gc)
7187 (while (or (not label)
7188 (save-excursion
7189 (save-restriction
7190 (widen)
7191 (goto-char (point-min))
7192 (re-search-forward
7193 (regexp-quote (format org-coderef-label-format label))
7194 nil t))))
7195 (when label (message "Label exists already") (sit-for 2))
7196 (setq label (read-string "Code line label: " label)))
7197 (end-of-line 1)
7198 (setq link (format org-coderef-label-format label))
7199 (setq gc (- 79 (length link)))
7200 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7201 (insert link)
7202 (setq link (concat "(" label ")") desc nil)))
7204 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7205 ;; We are in the agenda, link to referenced location
7206 (let ((m (or (get-text-property (point) 'org-hd-marker)
7207 (get-text-property (point) 'org-marker))))
7208 (unless m (error "Don't know what location to link to"))
7209 (org-with-point-at m
7210 (call-interactively 'org-store-link))))
7212 ((eq major-mode 'calendar-mode)
7213 (let ((cd (calendar-cursor-to-date)))
7214 (setq link
7215 (format-time-string
7216 (car org-time-stamp-formats)
7217 (apply 'encode-time
7218 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7219 nil nil nil))))
7220 (org-store-link-props :type "calendar" :date cd)))
7222 ((eq major-mode 'w3-mode)
7223 (setq cpltxt (if (and (buffer-name)
7224 (not (string-match "Untitled" (buffer-name))))
7225 (buffer-name)
7226 (url-view-url t))
7227 link (org-make-link (url-view-url t)))
7228 (org-store-link-props :type "w3" :url (url-view-url t)))
7230 ((eq major-mode 'w3m-mode)
7231 (setq cpltxt (or w3m-current-title w3m-current-url)
7232 link (org-make-link w3m-current-url))
7233 (org-store-link-props :type "w3m" :url (url-view-url t)))
7235 ((setq search (run-hook-with-args-until-success
7236 'org-create-file-search-functions))
7237 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7238 "::" search))
7239 (setq cpltxt (or description link)))
7241 ((eq major-mode 'image-mode)
7242 (setq cpltxt (concat "file:"
7243 (abbreviate-file-name buffer-file-name))
7244 link (org-make-link cpltxt))
7245 (org-store-link-props :type "image" :file buffer-file-name))
7247 ((eq major-mode 'dired-mode)
7248 ;; link to the file in the current line
7249 (setq cpltxt (concat "file:"
7250 (abbreviate-file-name
7251 (expand-file-name
7252 (dired-get-filename nil t))))
7253 link (org-make-link cpltxt)))
7255 ((and buffer-file-name (org-mode-p))
7256 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7257 (cond
7258 ((org-in-regexp "<<\\(.*?\\)>>")
7259 (setq cpltxt
7260 (concat "file:"
7261 (abbreviate-file-name buffer-file-name)
7262 "::" (match-string 1))
7263 link (org-make-link cpltxt)))
7264 ((and (featurep 'org-id)
7265 (or (eq org-link-to-org-use-id t)
7266 (and (eq org-link-to-org-use-id 'create-if-interactive)
7267 (interactive-p))
7268 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7269 (interactive-p)
7270 (not custom-id))
7271 (and org-link-to-org-use-id
7272 (condition-case nil
7273 (org-entry-get nil "ID")
7274 (error nil)))))
7275 ;; We can make a link using the ID.
7276 (setq link (condition-case nil
7277 (prog1 (org-id-store-link)
7278 (setq desc (plist-get org-store-link-plist
7279 :description)))
7280 (error
7281 ;; probably before first headline, link to file only
7282 (concat "file:"
7283 (abbreviate-file-name buffer-file-name))))))
7285 ;; Just link to current headline
7286 (setq cpltxt (concat "file:"
7287 (abbreviate-file-name buffer-file-name)))
7288 ;; Add a context search string
7289 (when (org-xor org-context-in-file-links arg)
7290 (setq txt (cond
7291 ((org-on-heading-p) nil)
7292 ((org-region-active-p)
7293 (buffer-substring (region-beginning) (region-end)))
7294 (t nil)))
7295 (when (or (null txt) (string-match "\\S-" txt))
7296 (setq cpltxt
7297 (concat cpltxt "::"
7298 (condition-case nil
7299 (org-make-org-heading-search-string txt)
7300 (error "")))
7301 desc (or (nth 4 (ignore-errors
7302 (org-heading-components))) "NONE"))))
7303 (if (string-match "::\\'" cpltxt)
7304 (setq cpltxt (substring cpltxt 0 -2)))
7305 (setq link (org-make-link cpltxt)))))
7307 ((buffer-file-name (buffer-base-buffer))
7308 ;; Just link to this file here.
7309 (setq cpltxt (concat "file:"
7310 (abbreviate-file-name
7311 (buffer-file-name (buffer-base-buffer)))))
7312 ;; Add a context string
7313 (when (org-xor org-context-in-file-links arg)
7314 (setq txt (if (org-region-active-p)
7315 (buffer-substring (region-beginning) (region-end))
7316 (buffer-substring (point-at-bol) (point-at-eol))))
7317 ;; Only use search option if there is some text.
7318 (when (string-match "\\S-" txt)
7319 (setq cpltxt
7320 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7321 desc "NONE")))
7322 (setq link (org-make-link cpltxt)))
7324 ((interactive-p)
7325 (error "Cannot link to a buffer which is not visiting a file"))
7327 (t (setq link nil)))
7329 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7330 (setq link (or link cpltxt)
7331 desc (or desc cpltxt))
7332 (if (equal desc "NONE") (setq desc nil))
7334 (if (and (or (interactive-p) executing-kbd-macro) link)
7335 (progn
7336 (setq org-stored-links
7337 (cons (list link desc) org-stored-links))
7338 (message "Stored: %s" (or desc link))
7339 (when custom-id
7340 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7341 "::#" custom-id))
7342 (setq org-stored-links
7343 (cons (list link desc) org-stored-links))))
7344 (and link (org-make-link-string link desc)))))
7346 (defun org-store-link-props (&rest plist)
7347 "Store link properties, extract names and addresses."
7348 (let (x adr)
7349 (when (setq x (plist-get plist :from))
7350 (setq adr (mail-extract-address-components x))
7351 (setq plist (plist-put plist :fromname (car adr)))
7352 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7353 (when (setq x (plist-get plist :to))
7354 (setq adr (mail-extract-address-components x))
7355 (setq plist (plist-put plist :toname (car adr)))
7356 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7357 (let ((from (plist-get plist :from))
7358 (to (plist-get plist :to)))
7359 (when (and from to org-from-is-user-regexp)
7360 (setq plist
7361 (plist-put plist :fromto
7362 (if (string-match org-from-is-user-regexp from)
7363 (concat "to %t")
7364 (concat "from %f"))))))
7365 (setq org-store-link-plist plist))
7367 (defun org-add-link-props (&rest plist)
7368 "Add these properties to the link property list."
7369 (let (key value)
7370 (while plist
7371 (setq key (pop plist) value (pop plist))
7372 (setq org-store-link-plist
7373 (plist-put org-store-link-plist key value)))))
7375 (defun org-email-link-description (&optional fmt)
7376 "Return the description part of an email link.
7377 This takes information from `org-store-link-plist' and formats it
7378 according to FMT (default from `org-email-link-description-format')."
7379 (setq fmt (or fmt org-email-link-description-format))
7380 (let* ((p org-store-link-plist)
7381 (to (plist-get p :toaddress))
7382 (from (plist-get p :fromaddress))
7383 (table
7384 (list
7385 (cons "%c" (plist-get p :fromto))
7386 (cons "%F" (plist-get p :from))
7387 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7388 (cons "%T" (plist-get p :to))
7389 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7390 (cons "%s" (plist-get p :subject))
7391 (cons "%m" (plist-get p :message-id)))))
7392 (when (string-match "%c" fmt)
7393 ;; Check if the user wrote this message
7394 (if (and org-from-is-user-regexp from to
7395 (save-match-data (string-match org-from-is-user-regexp from)))
7396 (setq fmt (replace-match "to %t" t t fmt))
7397 (setq fmt (replace-match "from %f" t t fmt))))
7398 (org-replace-escapes fmt table)))
7400 (defun org-make-org-heading-search-string (&optional string heading)
7401 "Make search string for STRING or current headline."
7402 (interactive)
7403 (let ((s (or string (org-get-heading))))
7404 (unless (and string (not heading))
7405 ;; We are using a headline, clean up garbage in there.
7406 (if (string-match org-todo-regexp s)
7407 (setq s (replace-match "" t t s)))
7408 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7409 (setq s (replace-match "" t t s)))
7410 (setq s (org-trim s))
7411 (if (string-match (concat "^\\(" org-quote-string "\\|"
7412 org-comment-string "\\)") s)
7413 (setq s (replace-match "" t t s)))
7414 (while (string-match org-ts-regexp s)
7415 (setq s (replace-match "" t t s))))
7416 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7417 (setq s (replace-match " " t t s)))
7418 (or string (setq s (concat "*" s))) ; Add * for headlines
7419 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7421 (defun org-make-link (&rest strings)
7422 "Concatenate STRINGS."
7423 (apply 'concat strings))
7425 (defun org-make-link-string (link &optional description)
7426 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7427 (unless (string-match "\\S-" link)
7428 (error "Empty link"))
7429 (when (stringp description)
7430 ;; Remove brackets from the description, they are fatal.
7431 (while (string-match "\\[" description)
7432 (setq description (replace-match "{" t t description)))
7433 (while (string-match "\\]" description)
7434 (setq description (replace-match "}" t t description))))
7435 (when (equal (org-link-escape link) description)
7436 ;; No description needed, it is identical
7437 (setq description nil))
7438 (when (and (not description)
7439 (not (equal link (org-link-escape link))))
7440 (setq description (org-extract-attributes link)))
7441 (concat "[[" (org-link-escape link) "]"
7442 (if description (concat "[" description "]") "")
7443 "]"))
7445 (defconst org-link-escape-chars
7446 '((?\ . "%20")
7447 (?\[ . "%5B")
7448 (?\] . "%5D")
7449 (?\340 . "%E0") ; `a
7450 (?\342 . "%E2") ; ^a
7451 (?\347 . "%E7") ; ,c
7452 (?\350 . "%E8") ; `e
7453 (?\351 . "%E9") ; 'e
7454 (?\352 . "%EA") ; ^e
7455 (?\356 . "%EE") ; ^i
7456 (?\364 . "%F4") ; ^o
7457 (?\371 . "%F9") ; `u
7458 (?\373 . "%FB") ; ^u
7459 (?\; . "%3B")
7460 (?? . "%3F")
7461 (?= . "%3D")
7462 (?+ . "%2B")
7464 "Association list of escapes for some characters problematic in links.
7465 This is the list that is used for internal purposes.")
7467 (defvar org-url-encoding-use-url-hexify nil)
7469 (defconst org-link-escape-chars-browser
7470 '((?\ . "%20")) ; 32 for the SPC char
7471 "Association list of escapes for some characters problematic in links.
7472 This is the list that is used before handing over to the browser.")
7474 (defun org-link-escape (text &optional table)
7475 "Escape characters in TEXT that are problematic for links."
7476 (if org-url-encoding-use-url-hexify
7477 (url-hexify-string text)
7478 (setq table (or table org-link-escape-chars))
7479 (when text
7480 (let ((re (mapconcat (lambda (x) (regexp-quote
7481 (char-to-string (car x))))
7482 table "\\|")))
7483 (while (string-match re text)
7484 (setq text
7485 (replace-match
7486 (cdr (assoc (string-to-char (match-string 0 text))
7487 table))
7488 t t text)))
7489 text))))
7491 (defun org-link-unescape (text &optional table)
7492 "Reverse the action of `org-link-escape'."
7493 (if org-url-encoding-use-url-hexify
7494 (url-unhex-string text)
7495 (setq table (or table org-link-escape-chars))
7496 (when text
7497 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7498 table "\\|")))
7499 (while (string-match re text)
7500 (setq text
7501 (replace-match
7502 (char-to-string (car (rassoc (match-string 0 text) table)))
7503 t t text)))
7504 text))))
7506 (defun org-xor (a b)
7507 "Exclusive or."
7508 (if a (not b) b))
7510 (defun org-fixup-message-id-for-http (s)
7511 "Replace special characters in a message id, so it can be used in an http query."
7512 (while (string-match "<" s)
7513 (setq s (replace-match "%3C" t t s)))
7514 (while (string-match ">" s)
7515 (setq s (replace-match "%3E" t t s)))
7516 (while (string-match "@" s)
7517 (setq s (replace-match "%40" t t s)))
7520 ;;;###autoload
7521 (defun org-insert-link-global ()
7522 "Insert a link like Org-mode does.
7523 This command can be called in any mode to insert a link in Org-mode syntax."
7524 (interactive)
7525 (org-load-modules-maybe)
7526 (org-run-like-in-org-mode 'org-insert-link))
7528 (defun org-insert-link (&optional complete-file link-location)
7529 "Insert a link. At the prompt, enter the link.
7531 Completion can be used to insert any of the link protocol prefixes like
7532 http or ftp in use.
7534 The history can be used to select a link previously stored with
7535 `org-store-link'. When the empty string is entered (i.e. if you just
7536 press RET at the prompt), the link defaults to the most recently
7537 stored link. As SPC triggers completion in the minibuffer, you need to
7538 use M-SPC or C-q SPC to force the insertion of a space character.
7540 You will also be prompted for a description, and if one is given, it will
7541 be displayed in the buffer instead of the link.
7543 If there is already a link at point, this command will allow you to edit link
7544 and description parts.
7546 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7547 be selected using completion. The path to the file will be relative to the
7548 current directory if the file is in the current directory or a subdirectory.
7549 Otherwise, the link will be the absolute path as completed in the minibuffer
7550 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7551 option `org-link-file-path-type'.
7553 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7554 the current directory or below.
7556 With three \\[universal-argument] prefixes, negate the meaning of
7557 `org-keep-stored-link-after-insertion'.
7559 If `org-make-link-description-function' is non-nil, this function will be
7560 called with the link target, and the result will be the default
7561 link description.
7563 If the LINK-LOCATION parameter is non-nil, this value will be
7564 used as the link location instead of reading one interactively."
7565 (interactive "P")
7566 (let* ((wcf (current-window-configuration))
7567 (region (if (org-region-active-p)
7568 (buffer-substring (region-beginning) (region-end))))
7569 (remove (and region (list (region-beginning) (region-end))))
7570 (desc region)
7571 tmphist ; byte-compile incorrectly complains about this
7572 (link link-location)
7573 entry file all-prefixes)
7574 (cond
7575 (link-location) ; specified by arg, just use it.
7576 ((org-in-regexp org-bracket-link-regexp 1)
7577 ;; We do have a link at point, and we are going to edit it.
7578 (setq remove (list (match-beginning 0) (match-end 0)))
7579 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7580 (setq link (read-string "Link: "
7581 (org-link-unescape
7582 (org-match-string-no-properties 1)))))
7583 ((or (org-in-regexp org-angle-link-re)
7584 (org-in-regexp org-plain-link-re))
7585 ;; Convert to bracket link
7586 (setq remove (list (match-beginning 0) (match-end 0))
7587 link (read-string "Link: "
7588 (org-remove-angle-brackets (match-string 0)))))
7589 ((member complete-file '((4) (16)))
7590 ;; Completing read for file names.
7591 (setq link (org-file-complete-link complete-file)))
7593 ;; Read link, with completion for stored links.
7594 (with-output-to-temp-buffer "*Org Links*"
7595 (princ "Insert a link.
7596 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7597 (when org-stored-links
7598 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7599 (princ (mapconcat
7600 (lambda (x)
7601 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7602 (reverse org-stored-links) "\n"))))
7603 (let ((cw (selected-window)))
7604 (select-window (get-buffer-window "*Org Links*"))
7605 (setq truncate-lines t)
7606 (unless (pos-visible-in-window-p (point-max))
7607 (org-fit-window-to-buffer))
7608 (and (window-live-p cw) (select-window cw)))
7609 ;; Fake a link history, containing the stored links.
7610 (setq tmphist (append (mapcar 'car org-stored-links)
7611 org-insert-link-history))
7612 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7613 (mapcar 'car org-link-abbrev-alist)
7614 org-link-types))
7615 (unwind-protect
7616 (progn
7617 (setq link
7618 (let ((org-completion-use-ido nil)
7619 (org-completion-use-iswitchb nil))
7620 (org-completing-read
7621 "Link: "
7622 (append
7623 (mapcar (lambda (x) (list (concat x ":")))
7624 all-prefixes)
7625 (mapcar 'car org-stored-links))
7626 nil nil nil
7627 'tmphist
7628 (car (car org-stored-links)))))
7629 (if (or (member link all-prefixes)
7630 (and (equal ":" (substring link -1))
7631 (member (substring link 0 -1) all-prefixes)
7632 (setq link (substring link 0 -1))))
7633 (setq link (org-link-try-special-completion link))))
7634 (set-window-configuration wcf)
7635 (kill-buffer "*Org Links*"))
7636 (setq entry (assoc link org-stored-links))
7637 (or entry (push link org-insert-link-history))
7638 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7639 (not org-keep-stored-link-after-insertion))
7640 (setq org-stored-links (delq (assoc link org-stored-links)
7641 org-stored-links)))
7642 (setq desc (or desc (nth 1 entry)))))
7644 (if (string-match org-plain-link-re link)
7645 ;; URL-like link, normalize the use of angular brackets.
7646 (setq link (org-make-link (org-remove-angle-brackets link))))
7648 ;; Check if we are linking to the current file with a search option
7649 ;; If yes, simplify the link by using only the search option.
7650 (when (and buffer-file-name
7651 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7652 (let* ((path (match-string 1 link))
7653 (case-fold-search nil)
7654 (search (match-string 2 link)))
7655 (save-match-data
7656 (if (equal (file-truename buffer-file-name) (file-truename path))
7657 ;; We are linking to this same file, with a search option
7658 (setq link search)))))
7660 ;; Check if we can/should use a relative path. If yes, simplify the link
7661 (when (string-match "^file:\\(.*\\)" link)
7662 (let* ((path (match-string 1 link))
7663 (origpath path)
7664 (case-fold-search nil))
7665 (cond
7666 ((or (eq org-link-file-path-type 'absolute)
7667 (equal complete-file '(16)))
7668 (setq path (abbreviate-file-name (expand-file-name path))))
7669 ((eq org-link-file-path-type 'noabbrev)
7670 (setq path (expand-file-name path)))
7671 ((eq org-link-file-path-type 'relative)
7672 (setq path (file-relative-name path)))
7674 (save-match-data
7675 (if (string-match (concat "^" (regexp-quote
7676 (file-name-as-directory
7677 (expand-file-name "."))))
7678 (expand-file-name path))
7679 ;; We are linking a file with relative path name.
7680 (setq path (substring (expand-file-name path)
7681 (match-end 0)))
7682 (setq path (abbreviate-file-name (expand-file-name path)))))))
7683 (setq link (concat "file:" path))
7684 (if (equal desc origpath)
7685 (setq desc path))))
7687 (if org-make-link-description-function
7688 (setq desc (funcall org-make-link-description-function link desc)))
7690 (setq desc (read-string "Description: " desc))
7691 (unless (string-match "\\S-" desc) (setq desc nil))
7692 (if remove (apply 'delete-region remove))
7693 (insert (org-make-link-string link desc))))
7695 (defun org-link-try-special-completion (type)
7696 "If there is completion support for link type TYPE, offer it."
7697 (let ((fun (intern (concat "org-" type "-complete-link"))))
7698 (if (functionp fun)
7699 (funcall fun)
7700 (read-string "Link (no completion support): " (concat type ":")))))
7702 (defun org-file-complete-link (&optional arg)
7703 "Create a file link using completion."
7704 (let (file link)
7705 (setq file (read-file-name "File: "))
7706 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7707 (pwd1 (file-name-as-directory (abbreviate-file-name
7708 (expand-file-name ".")))))
7709 (cond
7710 ((equal arg '(16))
7711 (setq link (org-make-link
7712 "file:"
7713 (abbreviate-file-name (expand-file-name file)))))
7714 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7715 (setq link (org-make-link "file:" (match-string 1 file))))
7716 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7717 (expand-file-name file))
7718 (setq link (org-make-link
7719 "file:" (match-string 1 (expand-file-name file)))))
7720 (t (setq link (org-make-link "file:" file)))))
7721 link))
7723 (defun org-completing-read (&rest args)
7724 "Completing-read with SPACE being a normal character."
7725 (let ((minibuffer-local-completion-map
7726 (copy-keymap minibuffer-local-completion-map)))
7727 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7728 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7729 (apply 'org-icompleting-read args)))
7731 (defun org-completing-read-no-i (&rest args)
7732 (let (org-completion-use-ido org-completion-use-iswitchb)
7733 (apply 'org-completing-read args)))
7735 (defun org-iswitchb-completing-read (prompt choices &rest args)
7736 "Use iswitch as a completing-read replacement to choose from choices.
7737 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7738 from."
7739 (let* ((iswitchb-use-virtual-buffers nil)
7740 (iswitchb-make-buflist-hook
7741 (lambda ()
7742 (setq iswitchb-temp-buflist choices))))
7743 (iswitchb-read-buffer prompt)))
7745 (defun org-icompleting-read (&rest args)
7746 "Completing-read using `ido-mode' or `iswitchb' speedups if available"
7747 (if (and org-completion-use-ido
7748 (fboundp 'ido-completing-read)
7749 (boundp 'ido-mode) ido-mode
7750 (listp (second args)))
7751 (let ((ido-enter-matching-directory nil))
7752 (apply 'ido-completing-read (concat (car args))
7753 (if (consp (car (nth 1 args)))
7754 (mapcar (lambda (x) (car x)) (nth 1 args))
7755 (nth 1 args))
7756 (cddr args)))
7757 (if (and org-completion-use-iswitchb
7758 (boundp 'iswitchb-mode) iswitchb-mode
7759 (listp (second args)))
7760 (apply 'org-iswitchb-completing-read (concat (car args))
7761 (mapcar (lambda (x) (car x)) (nth 1 args))
7762 (cddr args))
7763 (apply 'completing-read args))))
7765 (defun org-extract-attributes (s)
7766 "Extract the attributes cookie from a string and set as text property."
7767 (let (a attr (start 0) key value)
7768 (save-match-data
7769 (when (string-match "{{\\([^}]+\\)}}$" s)
7770 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7771 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7772 (setq key (match-string 1 a) value (match-string 2 a)
7773 start (match-end 0)
7774 attr (plist-put attr (intern key) value))))
7775 (org-add-props s nil 'org-attr attr))
7778 (defun org-extract-attributes-from-string (tag)
7779 (let (key value attr)
7780 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7781 (setq key (match-string 1 tag) value (match-string 2 tag)
7782 tag (replace-match "" t t tag)
7783 attr (plist-put attr (intern key) value)))
7784 (cons tag attr)))
7786 (defun org-attributes-to-string (plist)
7787 "Format a property list into an HTML attribute list."
7788 (let ((s "") key value)
7789 (while plist
7790 (setq key (pop plist) value (pop plist))
7791 (and value
7792 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7795 ;;; Opening/following a link
7797 (defvar org-link-search-failed nil)
7799 (defun org-next-link ()
7800 "Move forward to the next link.
7801 If the link is in hidden text, expose it."
7802 (interactive)
7803 (when (and org-link-search-failed (eq this-command last-command))
7804 (goto-char (point-min))
7805 (message "Link search wrapped back to beginning of buffer"))
7806 (setq org-link-search-failed nil)
7807 (let* ((pos (point))
7808 (ct (org-context))
7809 (a (assoc :link ct)))
7810 (if a (goto-char (nth 2 a)))
7811 (if (re-search-forward org-any-link-re nil t)
7812 (progn
7813 (goto-char (match-beginning 0))
7814 (if (org-invisible-p) (org-show-context)))
7815 (goto-char pos)
7816 (setq org-link-search-failed t)
7817 (error "No further link found"))))
7819 (defun org-previous-link ()
7820 "Move backward to the previous link.
7821 If the link is in hidden text, expose it."
7822 (interactive)
7823 (when (and org-link-search-failed (eq this-command last-command))
7824 (goto-char (point-max))
7825 (message "Link search wrapped back to end of buffer"))
7826 (setq org-link-search-failed nil)
7827 (let* ((pos (point))
7828 (ct (org-context))
7829 (a (assoc :link ct)))
7830 (if a (goto-char (nth 1 a)))
7831 (if (re-search-backward org-any-link-re nil t)
7832 (progn
7833 (goto-char (match-beginning 0))
7834 (if (org-invisible-p) (org-show-context)))
7835 (goto-char pos)
7836 (setq org-link-search-failed t)
7837 (error "No further link found"))))
7839 (defun org-translate-link (s)
7840 "Translate a link string if a translation function has been defined."
7841 (if (and org-link-translation-function
7842 (fboundp org-link-translation-function)
7843 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7844 (progn
7845 (setq s (funcall org-link-translation-function
7846 (match-string 1) (match-string 2)))
7847 (concat (car s) ":" (cdr s)))
7850 (defun org-translate-link-from-planner (type path)
7851 "Translate a link from Emacs Planner syntax so that Org can follow it.
7852 This is still an experimental function, your mileage may vary."
7853 (cond
7854 ((member type '("http" "https" "news" "ftp"))
7855 ;; standard Internet links are the same.
7856 nil)
7857 ((and (equal type "irc") (string-match "^//" path))
7858 ;; Planner has two / at the beginning of an irc link, we have 1.
7859 ;; We should have zero, actually....
7860 (setq path (substring path 1)))
7861 ((and (equal type "lisp") (string-match "^/" path))
7862 ;; Planner has a slash, we do not.
7863 (setq type "elisp" path (substring path 1)))
7864 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7865 ;; A typical message link. Planner has the id after the fina slash,
7866 ;; we separate it with a hash mark
7867 (setq path (concat (match-string 1 path) "#"
7868 (org-remove-angle-brackets (match-string 2 path)))))
7870 (cons type path))
7872 (defun org-find-file-at-mouse (ev)
7873 "Open file link or URL at mouse."
7874 (interactive "e")
7875 (mouse-set-point ev)
7876 (org-open-at-point 'in-emacs))
7878 (defun org-open-at-mouse (ev)
7879 "Open file link or URL at mouse."
7880 (interactive "e")
7881 (mouse-set-point ev)
7882 (if (eq major-mode 'org-agenda-mode)
7883 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7884 (org-open-at-point))
7886 (defvar org-window-config-before-follow-link nil
7887 "The window configuration before following a link.
7888 This is saved in case the need arises to restore it.")
7890 (defvar org-open-link-marker (make-marker)
7891 "Marker pointing to the location where `org-open-at-point; was called.")
7893 ;;;###autoload
7894 (defun org-open-at-point-global ()
7895 "Follow a link like Org-mode does.
7896 This command can be called in any mode to follow a link that has
7897 Org-mode syntax."
7898 (interactive)
7899 (org-run-like-in-org-mode 'org-open-at-point))
7901 ;;;###autoload
7902 (defun org-open-link-from-string (s &optional arg reference-buffer)
7903 "Open a link in the string S, as if it was in Org-mode."
7904 (interactive "sLink: \nP")
7905 (let ((reference-buffer (or reference-buffer (current-buffer))))
7906 (with-temp-buffer
7907 (let ((org-inhibit-startup t))
7908 (org-mode)
7909 (insert s)
7910 (goto-char (point-min))
7911 (org-open-at-point arg reference-buffer)))))
7913 (defun org-open-at-point (&optional in-emacs reference-buffer)
7914 "Open link at or after point.
7915 If there is no link at point, this function will search forward up to
7916 the end of the current line.
7917 Normally, files will be opened by an appropriate application. If the
7918 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7919 With a double prefix argument, try to open outside of Emacs, in the
7920 application the system uses for this file type."
7921 (interactive "P")
7922 (org-load-modules-maybe)
7923 (move-marker org-open-link-marker (point))
7924 (setq org-window-config-before-follow-link (current-window-configuration))
7925 (org-remove-occur-highlights nil nil t)
7926 (cond
7927 ((and (org-on-heading-p)
7928 (not (org-in-regexp
7929 (concat org-plain-link-re "\\|"
7930 org-bracket-link-regexp "\\|"
7931 org-angle-link-re "\\|"
7932 "[ \t]:[^ \t\n]+:[ \t]*$"))))
7933 (org-offer-links-in-entry in-emacs))
7934 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7935 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7936 (org-footnote-action))
7938 (let (type path link line search (pos (point)))
7939 (catch 'match
7940 (save-excursion
7941 (skip-chars-forward "^]\n\r")
7942 (when (org-in-regexp org-bracket-link-regexp)
7943 (setq link (org-extract-attributes
7944 (org-link-unescape (org-match-string-no-properties 1))))
7945 (while (string-match " *\n *" link)
7946 (setq link (replace-match " " t t link)))
7947 (setq link (org-link-expand-abbrev link))
7948 (cond
7949 ((or (file-name-absolute-p link)
7950 (string-match "^\\.\\.?/" link))
7951 (setq type "file" path link))
7952 ((string-match org-link-re-with-space3 link)
7953 (setq type (match-string 1 link) path (match-string 2 link)))
7954 (t (setq type "thisfile" path link)))
7955 (throw 'match t)))
7957 (when (get-text-property (point) 'org-linked-text)
7958 (setq type "thisfile"
7959 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7960 (1+ (point)) (point))
7961 path (buffer-substring
7962 (previous-single-property-change pos 'org-linked-text)
7963 (next-single-property-change pos 'org-linked-text)))
7964 (throw 'match t))
7966 (save-excursion
7967 (when (or (org-in-regexp org-angle-link-re)
7968 (org-in-regexp org-plain-link-re))
7969 (setq type (match-string 1) path (match-string 2))
7970 (throw 'match t)))
7971 (save-excursion
7972 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7973 (setq type "tags"
7974 path (match-string 1))
7975 (while (string-match ":" path)
7976 (setq path (replace-match "+" t t path)))
7977 (throw 'match t)))
7978 (when (org-in-regexp "<\\([^><\n]+\\)>")
7979 (setq type "tree-match"
7980 path (match-string 1))
7981 (throw 'match t)))
7982 (unless path
7983 (error "No link found"))
7985 ;; switch back to reference buffer
7986 ;; needed when if called in a temporary buffer through
7987 ;; org-open-link-from-string
7988 (with-current-buffer (or reference-buffer (current-buffer))
7990 ;; Remove any trailing spaces in path
7991 (if (string-match " +\\'" path)
7992 (setq path (replace-match "" t t path)))
7993 (if (and org-link-translation-function
7994 (fboundp org-link-translation-function))
7995 ;; Check if we need to translate the link
7996 (let ((tmp (funcall org-link-translation-function type path)))
7997 (setq type (car tmp) path (cdr tmp))))
7999 (cond
8001 ((assoc type org-link-protocols)
8002 (funcall (nth 1 (assoc type org-link-protocols)) path))
8004 ((equal type "mailto")
8005 (let ((cmd (car org-link-mailto-program))
8006 (args (cdr org-link-mailto-program)) args1
8007 (address path) (subject "") a)
8008 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8009 (setq address (match-string 1 path)
8010 subject (org-link-escape (match-string 2 path))))
8011 (while args
8012 (cond
8013 ((not (stringp (car args))) (push (pop args) args1))
8014 (t (setq a (pop args))
8015 (if (string-match "%a" a)
8016 (setq a (replace-match address t t a)))
8017 (if (string-match "%s" a)
8018 (setq a (replace-match subject t t a)))
8019 (push a args1))))
8020 (apply cmd (nreverse args1))))
8022 ((member type '("http" "https" "ftp" "news"))
8023 (browse-url (concat type ":" (org-link-escape
8024 path org-link-escape-chars-browser))))
8026 ((member type '("message"))
8027 (browse-url (concat type ":" path)))
8029 ((string= type "tags")
8030 (org-tags-view in-emacs path))
8031 ((string= type "thisfile")
8032 (if in-emacs
8033 (switch-to-buffer-other-window
8034 (org-get-buffer-for-internal-link (current-buffer)))
8035 (org-mark-ring-push))
8036 (let ((cmd `(org-link-search
8037 ,path
8038 ,(cond ((equal in-emacs '(4)) 'occur)
8039 ((equal in-emacs '(16)) 'org-occur)
8040 (t nil))
8041 ,pos)))
8042 (condition-case nil (eval cmd)
8043 (error (progn (widen) (eval cmd))))))
8045 ((string= type "tree-match")
8046 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8048 ((string= type "file")
8049 (if (string-match "::\\([0-9]+\\)\\'" path)
8050 (setq line (string-to-number (match-string 1 path))
8051 path (substring path 0 (match-beginning 0)))
8052 (if (string-match "::\\(.+\\)\\'" path)
8053 (setq search (match-string 1 path)
8054 path (substring path 0 (match-beginning 0)))))
8055 (if (string-match "[*?{]" (file-name-nondirectory path))
8056 (dired path)
8057 (org-open-file path in-emacs line search)))
8059 ((string= type "news")
8060 (require 'org-gnus)
8061 (org-gnus-follow-link path))
8063 ((string= type "shell")
8064 (let ((cmd path))
8065 (if (or (not org-confirm-shell-link-function)
8066 (funcall org-confirm-shell-link-function
8067 (format "Execute \"%s\" in shell? "
8068 (org-add-props cmd nil
8069 'face 'org-warning))))
8070 (progn
8071 (message "Executing %s" cmd)
8072 (shell-command cmd))
8073 (error "Abort"))))
8075 ((string= type "elisp")
8076 (let ((cmd path))
8077 (if (or (not org-confirm-elisp-link-function)
8078 (funcall org-confirm-elisp-link-function
8079 (format "Execute \"%s\" as elisp? "
8080 (org-add-props cmd nil
8081 'face 'org-warning))))
8082 (message "%s => %s" cmd
8083 (if (equal (string-to-char cmd) ?\()
8084 (eval (read cmd))
8085 (call-interactively (read cmd))))
8086 (error "Abort"))))
8089 (browse-url-at-point))))))
8090 (move-marker org-open-link-marker nil)
8091 (run-hook-with-args 'org-follow-link-hook)))
8093 (defun org-offer-links-in-entry (&optional nth zero)
8094 "Offer links in the curren entry and follow the selected link.
8095 If there is only one link, follow it immediately as well.
8096 If NTH is an integer, immediately pick the NTH link found.
8097 If ZERO is a string, check also this string for a link, and if
8098 there is one, offer it as link number zero."
8099 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8100 "\\(" org-angle-link-re "\\)\\|"
8101 "\\(" org-plain-link-re "\\)"))
8102 (cnt ?0)
8103 (in-emacs (if (integerp nth) nil nth))
8104 have-zero end links link c)
8105 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8106 (push (match-string 0 zero) links)
8107 (setq cnt (1- cnt) have-zero t))
8108 (save-excursion
8109 (org-back-to-heading t)
8110 (setq end (save-excursion (outline-next-heading) (point)))
8111 (while (re-search-forward re end t)
8112 (push (match-string 0) links))
8113 (setq links (org-uniquify (reverse links))))
8115 (cond
8116 ((null links) (error "No links"))
8117 ((equal (length links) 1)
8118 (setq link (car links)))
8119 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8120 (setq link (nth (if have-zero nth (1- nth)) links)))
8121 (t ; we have to select a link
8122 (save-excursion
8123 (save-window-excursion
8124 (delete-other-windows)
8125 (with-output-to-temp-buffer "*Select Link*"
8126 (mapc (lambda (l)
8127 (if (not (string-match org-bracket-link-regexp l))
8128 (princ (format "[%c] %s\n" (incf cnt)
8129 (org-remove-angle-brackets l)))
8130 (if (match-end 3)
8131 (princ (format "[%c] %s (%s)\n" (incf cnt)
8132 (match-string 3 l) (match-string 1 l)))
8133 (princ (format "[%c] %s\n" (incf cnt)
8134 (match-string 1 l))))))
8135 links))
8136 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8137 (message "Select link to open:")
8138 (setq c (read-char-exclusive))
8139 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8140 (when (equal c ?q) (error "Abort"))
8141 (setq nth (- c ?0))
8142 (if have-zero (setq nth (1+ nth)))
8143 (unless (and (integerp nth) (>= (length links) nth))
8144 (error "Invalid link selection"))
8145 (setq link (nth (1- nth) links))))
8146 (org-open-link-from-string link in-emacs (current-buffer))))
8148 ;;;; Time estimates
8150 (defun org-get-effort (&optional pom)
8151 "Get the effort estimate for the current entry."
8152 (org-entry-get pom org-effort-property))
8154 ;;; File search
8156 (defvar org-create-file-search-functions nil
8157 "List of functions to construct the right search string for a file link.
8158 These functions are called in turn with point at the location to
8159 which the link should point.
8161 A function in the hook should first test if it would like to
8162 handle this file type, for example by checking the major-mode or
8163 the file extension. If it decides not to handle this file, it
8164 should just return nil to give other functions a chance. If it
8165 does handle the file, it must return the search string to be used
8166 when following the link. The search string will be part of the
8167 file link, given after a double colon, and `org-open-at-point'
8168 will automatically search for it. If special measures must be
8169 taken to make the search successful, another function should be
8170 added to the companion hook `org-execute-file-search-functions',
8171 which see.
8173 A function in this hook may also use `setq' to set the variable
8174 `description' to provide a suggestion for the descriptive text to
8175 be used for this link when it gets inserted into an Org-mode
8176 buffer with \\[org-insert-link].")
8178 (defvar org-execute-file-search-functions nil
8179 "List of functions to execute a file search triggered by a link.
8181 Functions added to this hook must accept a single argument, the
8182 search string that was part of the file link, the part after the
8183 double colon. The function must first check if it would like to
8184 handle this search, for example by checking the major-mode or the
8185 file extension. If it decides not to handle this search, it
8186 should just return nil to give other functions a chance. If it
8187 does handle the search, it must return a non-nil value to keep
8188 other functions from trying.
8190 Each function can access the current prefix argument through the
8191 variable `current-prefix-argument'. Note that a single prefix is
8192 used to force opening a link in Emacs, so it may be good to only
8193 use a numeric or double prefix to guide the search function.
8195 In case this is needed, a function in this hook can also restore
8196 the window configuration before `org-open-at-point' was called using:
8198 (set-window-configuration org-window-config-before-follow-link)")
8200 (defun org-link-search (s &optional type avoid-pos)
8201 "Search for a link search option.
8202 If S is surrounded by forward slashes, it is interpreted as a
8203 regular expression. In org-mode files, this will create an `org-occur'
8204 sparse tree. In ordinary files, `occur' will be used to list matches.
8205 If the current buffer is in `dired-mode', grep will be used to search
8206 in all files. If AVOID-POS is given, ignore matches near that position."
8207 (let ((case-fold-search t)
8208 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8209 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8210 (append '(("") (" ") ("\t") ("\n"))
8211 org-emphasis-alist)
8212 "\\|") "\\)"))
8213 (pos (point))
8214 (pre nil) (post nil)
8215 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8216 (cond
8217 ;; First check if there are any special
8218 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8219 ;; Now try the builtin stuff
8220 ((and (equal (string-to-char s0) ?#)
8221 (> (length s0) 1)
8222 (save-excursion
8223 (goto-char (point-min))
8224 (and
8225 (re-search-forward
8226 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8227 (setq type 'dedicated
8228 pos (match-beginning 0))))
8229 ;; There is an exact target for this
8230 (goto-char pos)
8231 (org-back-to-heading t)))
8232 ((save-excursion
8233 (goto-char (point-min))
8234 (and
8235 (re-search-forward
8236 (concat "<<" (regexp-quote s0) ">>") nil t)
8237 (setq type 'dedicated
8238 pos (match-beginning 0))))
8239 ;; There is an exact target for this
8240 (goto-char pos))
8241 ((and (string-match "^(\\(.*\\))$" s0)
8242 (save-excursion
8243 (goto-char (point-min))
8244 (and
8245 (re-search-forward
8246 (concat "[^[]" (regexp-quote
8247 (format org-coderef-label-format
8248 (match-string 1 s0))))
8249 nil t)
8250 (setq type 'dedicated
8251 pos (1+ (match-beginning 0))))))
8252 ;; There is a coderef target for this
8253 (goto-char pos))
8254 ((string-match "^/\\(.*\\)/$" s)
8255 ;; A regular expression
8256 (cond
8257 ((org-mode-p)
8258 (org-occur (match-string 1 s)))
8259 ;;((eq major-mode 'dired-mode)
8260 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8261 (t (org-do-occur (match-string 1 s)))))
8263 ;; A normal search strings
8264 (when (equal (string-to-char s) ?*)
8265 ;; Anchor on headlines, post may include tags.
8266 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8267 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8268 s (substring s 1)))
8269 (remove-text-properties
8270 0 (length s)
8271 '(face nil mouse-face nil keymap nil fontified nil) s)
8272 ;; Make a series of regular expressions to find a match
8273 (setq words (org-split-string s "[ \n\r\t]+")
8275 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8276 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8277 "\\)" markers)
8278 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8279 re2a (concat "[ \t\r\n]" re2a_)
8280 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8281 re4 (concat "[^a-zA-Z_]" re4_)
8283 re1 (concat pre re2 post)
8284 re3 (concat pre (if pre re4_ re4) post)
8285 re5 (concat pre ".*" re4)
8286 re2 (concat pre re2)
8287 re2a (concat pre (if pre re2a_ re2a))
8288 re4 (concat pre (if pre re4_ re4))
8289 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8290 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8291 re5 "\\)"
8293 (cond
8294 ((eq type 'org-occur) (org-occur reall))
8295 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8296 (t (goto-char (point-min))
8297 (setq type 'fuzzy)
8298 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8299 (org-search-not-self 1 re1 nil t)
8300 (org-search-not-self 1 re2 nil t)
8301 (org-search-not-self 1 re2a nil t)
8302 (org-search-not-self 1 re3 nil t)
8303 (org-search-not-self 1 re4 nil t)
8304 (org-search-not-self 1 re5 nil t)
8306 (goto-char (match-beginning 1))
8307 (goto-char pos)
8308 (error "No match")))))
8310 ;; Normal string-search
8311 (goto-char (point-min))
8312 (if (search-forward s nil t)
8313 (goto-char (match-beginning 0))
8314 (error "No match"))))
8315 (and (org-mode-p) (org-show-context 'link-search))
8316 type))
8318 (defun org-search-not-self (group &rest args)
8319 "Execute `re-search-forward', but only accept matches that do not
8320 enclose the position of `org-open-link-marker'."
8321 (let ((m org-open-link-marker))
8322 (catch 'exit
8323 (while (apply 're-search-forward args)
8324 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8325 (goto-char (match-end group))
8326 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8327 (> (match-beginning 0) (marker-position m))
8328 (< (match-end 0) (marker-position m)))
8329 (save-match-data
8330 (or (not (org-in-regexp
8331 org-bracket-link-analytic-regexp 1))
8332 (not (match-end 4)) ; no description
8333 (and (<= (match-beginning 4) (point))
8334 (>= (match-end 4) (point))))))
8335 (throw 'exit (point))))))))
8337 (defun org-get-buffer-for-internal-link (buffer)
8338 "Return a buffer to be used for displaying the link target of internal links."
8339 (cond
8340 ((not org-display-internal-link-with-indirect-buffer)
8341 buffer)
8342 ((string-match "(Clone)$" (buffer-name buffer))
8343 (message "Buffer is already a clone, not making another one")
8344 ;; we also do not modify visibility in this case
8345 buffer)
8346 (t ; make a new indirect buffer for displaying the link
8347 (let* ((bn (buffer-name buffer))
8348 (ibn (concat bn "(Clone)"))
8349 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8350 (with-current-buffer ib (org-overview))
8351 ib))))
8353 (defun org-do-occur (regexp &optional cleanup)
8354 "Call the Emacs command `occur'.
8355 If CLEANUP is non-nil, remove the printout of the regular expression
8356 in the *Occur* buffer. This is useful if the regex is long and not useful
8357 to read."
8358 (occur regexp)
8359 (when cleanup
8360 (let ((cwin (selected-window)) win beg end)
8361 (when (setq win (get-buffer-window "*Occur*"))
8362 (select-window win))
8363 (goto-char (point-min))
8364 (when (re-search-forward "match[a-z]+" nil t)
8365 (setq beg (match-end 0))
8366 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8367 (setq end (1- (match-beginning 0)))))
8368 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8369 (goto-char (point-min))
8370 (select-window cwin))))
8372 ;;; The mark ring for links jumps
8374 (defvar org-mark-ring nil
8375 "Mark ring for positions before jumps in Org-mode.")
8376 (defvar org-mark-ring-last-goto nil
8377 "Last position in the mark ring used to go back.")
8378 ;; Fill and close the ring
8379 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8380 (loop for i from 1 to org-mark-ring-length do
8381 (push (make-marker) org-mark-ring))
8382 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8383 org-mark-ring)
8385 (defun org-mark-ring-push (&optional pos buffer)
8386 "Put the current position or POS into the mark ring and rotate it."
8387 (interactive)
8388 (setq pos (or pos (point)))
8389 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8390 (move-marker (car org-mark-ring)
8391 (or pos (point))
8392 (or buffer (current-buffer)))
8393 (message "%s"
8394 (substitute-command-keys
8395 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8397 (defun org-mark-ring-goto (&optional n)
8398 "Jump to the previous position in the mark ring.
8399 With prefix arg N, jump back that many stored positions. When
8400 called several times in succession, walk through the entire ring.
8401 Org-mode commands jumping to a different position in the current file,
8402 or to another Org-mode file, automatically push the old position
8403 onto the ring."
8404 (interactive "p")
8405 (let (p m)
8406 (if (eq last-command this-command)
8407 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8408 (setq p org-mark-ring))
8409 (setq org-mark-ring-last-goto p)
8410 (setq m (car p))
8411 (switch-to-buffer (marker-buffer m))
8412 (goto-char m)
8413 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8415 (defun org-remove-angle-brackets (s)
8416 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8417 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8419 (defun org-add-angle-brackets (s)
8420 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8421 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8423 (defun org-remove-double-quotes (s)
8424 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8425 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8428 ;;; Following specific links
8430 (defun org-follow-timestamp-link ()
8431 (cond
8432 ((org-at-date-range-p t)
8433 (let ((org-agenda-start-on-weekday)
8434 (t1 (match-string 1))
8435 (t2 (match-string 2)))
8436 (setq t1 (time-to-days (org-time-string-to-time t1))
8437 t2 (time-to-days (org-time-string-to-time t2)))
8438 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8439 ((org-at-timestamp-p t)
8440 (org-agenda-list nil (time-to-days (org-time-string-to-time
8441 (substring (match-string 1) 0 10)))
8443 (t (error "This should not happen"))))
8446 ;;; Following file links
8447 (defvar org-wait nil)
8448 (defun org-open-file (path &optional in-emacs line search)
8449 "Open the file at PATH.
8450 First, this expands any special file name abbreviations. Then the
8451 configuration variable `org-file-apps' is checked if it contains an
8452 entry for this file type, and if yes, the corresponding command is launched.
8454 If no application is found, Emacs simply visits the file.
8456 With optional prefix argument IN-EMACS, Emacs will visit the file.
8457 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8458 and o use an external application to visit the file.
8460 Optional LINE specifies a line to go to, optional SEARCH a string to
8461 search for. If LINE or SEARCH is given, the file will always be
8462 opened in Emacs.
8463 If the file does not exist, an error is thrown."
8464 (setq in-emacs (or in-emacs line search))
8465 (let* ((file (if (equal path "")
8466 buffer-file-name
8467 (substitute-in-file-name (expand-file-name path))))
8468 (apps (append org-file-apps (org-default-apps)))
8469 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8470 (dirp (if remp nil (file-directory-p file)))
8471 (file (if (and dirp org-open-directory-means-index-dot-org)
8472 (concat (file-name-as-directory file) "index.org")
8473 file))
8474 (a-m-a-p (assq 'auto-mode apps))
8475 (dfile (downcase file))
8476 (old-buffer (current-buffer))
8477 (old-pos (point))
8478 (old-mode major-mode)
8479 ext cmd)
8480 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8481 (setq ext (match-string 1 dfile))
8482 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8483 (setq ext (match-string 1 dfile))))
8484 (cond
8485 ((equal in-emacs '(16))
8486 (setq cmd (cdr (assoc 'system apps))))
8487 (in-emacs (setq cmd 'emacs))
8489 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8490 (and dirp (cdr (assoc 'directory apps)))
8491 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8492 'string-match)
8493 (cdr (assoc ext apps))
8494 (cdr (assoc t apps))))))
8495 (when (eq cmd 'system)
8496 (setq cmd (cdr (assoc 'system apps))))
8497 (when (eq cmd 'default)
8498 (setq cmd (cdr (assoc t apps))))
8499 (when (eq cmd 'mailcap)
8500 (require 'mailcap)
8501 (mailcap-parse-mailcaps)
8502 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8503 (command (mailcap-mime-info mime-type)))
8504 (if (stringp command)
8505 (setq cmd command)
8506 (setq cmd 'emacs))))
8507 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8508 (not (file-exists-p file))
8509 (not org-open-non-existing-files))
8510 (error "No such file: %s" file))
8511 (cond
8512 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8513 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8514 (while (string-match "['\"]%s['\"]" cmd)
8515 (setq cmd (replace-match "%s" t t cmd)))
8516 (while (string-match "%s" cmd)
8517 (setq cmd (replace-match
8518 (save-match-data
8519 (shell-quote-argument
8520 (convert-standard-filename file)))
8521 t t cmd)))
8522 (save-window-excursion
8523 (start-process-shell-command cmd nil cmd)
8524 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8526 ((or (stringp cmd)
8527 (eq cmd 'emacs))
8528 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8529 (widen)
8530 (if line (org-goto-line line)
8531 (if search (org-link-search search))))
8532 ((consp cmd)
8533 (let ((file (convert-standard-filename file)))
8534 (eval cmd)))
8535 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8536 (and (org-mode-p) (eq old-mode 'org-mode)
8537 (or (not (equal old-buffer (current-buffer)))
8538 (not (equal old-pos (point))))
8539 (org-mark-ring-push old-pos old-buffer))))
8541 (defun org-default-apps ()
8542 "Return the default applications for this operating system."
8543 (cond
8544 ((eq system-type 'darwin)
8545 org-file-apps-defaults-macosx)
8546 ((eq system-type 'windows-nt)
8547 org-file-apps-defaults-windowsnt)
8548 (t org-file-apps-defaults-gnu)))
8550 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8551 "Convert extensions to regular expressions in the cars of LIST.
8552 Also, weed out any non-string entries, because the return value is used
8553 only for regexp matching.
8554 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8555 point to the symbol `emacs', indicating that the file should
8556 be opened in Emacs."
8557 (append
8558 (delq nil
8559 (mapcar (lambda (x)
8560 (if (not (stringp (car x)))
8562 (if (string-match "\\W" (car x))
8564 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8565 list))
8566 (if add-auto-mode
8567 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8569 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8570 (defun org-file-remote-p (file)
8571 "Test whether FILE specifies a location on a remote system.
8572 Return non-nil if the location is indeed remote.
8574 For example, the filename \"/user@host:/foo\" specifies a location
8575 on the system \"/user@host:\"."
8576 (cond ((fboundp 'file-remote-p)
8577 (file-remote-p file))
8578 ((fboundp 'tramp-handle-file-remote-p)
8579 (tramp-handle-file-remote-p file))
8580 ((and (boundp 'ange-ftp-name-format)
8581 (string-match (car ange-ftp-name-format) file))
8583 (t nil)))
8586 ;;;; Refiling
8588 (defun org-get-org-file ()
8589 "Read a filename, with default directory `org-directory'."
8590 (let ((default (or org-default-notes-file remember-data-file)))
8591 (read-file-name (format "File name [%s]: " default)
8592 (file-name-as-directory org-directory)
8593 default)))
8595 (defun org-notes-order-reversed-p ()
8596 "Check if the current file should receive notes in reversed order."
8597 (cond
8598 ((not org-reverse-note-order) nil)
8599 ((eq t org-reverse-note-order) t)
8600 ((not (listp org-reverse-note-order)) nil)
8601 (t (catch 'exit
8602 (let ((all org-reverse-note-order)
8603 entry)
8604 (while (setq entry (pop all))
8605 (if (string-match (car entry) buffer-file-name)
8606 (throw 'exit (cdr entry))))
8607 nil)))))
8609 (defvar org-refile-target-table nil
8610 "The list of refile targets, created by `org-refile'.")
8612 (defvar org-agenda-new-buffers nil
8613 "Buffers created to visit agenda files.")
8615 (defun org-get-refile-targets (&optional default-buffer)
8616 "Produce a table with refile targets."
8617 (let ((case-fold-search nil)
8618 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8619 (entries (or org-refile-targets '((nil . (:level . 1)))))
8620 targets txt re files f desc descre fast-path-p level pos0)
8621 (message "Getting targets...")
8622 (with-current-buffer (or default-buffer (current-buffer))
8623 (while (setq entry (pop entries))
8624 (setq files (car entry) desc (cdr entry))
8625 (setq fast-path-p nil)
8626 (cond
8627 ((null files) (setq files (list (current-buffer))))
8628 ((eq files 'org-agenda-files)
8629 (setq files (org-agenda-files 'unrestricted)))
8630 ((and (symbolp files) (fboundp files))
8631 (setq files (funcall files)))
8632 ((and (symbolp files) (boundp files))
8633 (setq files (symbol-value files))))
8634 (if (stringp files) (setq files (list files)))
8635 (cond
8636 ((eq (car desc) :tag)
8637 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8638 ((eq (car desc) :todo)
8639 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8640 ((eq (car desc) :regexp)
8641 (setq descre (cdr desc)))
8642 ((eq (car desc) :level)
8643 (setq descre (concat "^\\*\\{" (number-to-string
8644 (if org-odd-levels-only
8645 (1- (* 2 (cdr desc)))
8646 (cdr desc)))
8647 "\\}[ \t]")))
8648 ((eq (car desc) :maxlevel)
8649 (setq fast-path-p t)
8650 (setq descre (concat "^\\*\\{1," (number-to-string
8651 (if org-odd-levels-only
8652 (1- (* 2 (cdr desc)))
8653 (cdr desc)))
8654 "\\}[ \t]")))
8655 (t (error "Bad refiling target description %s" desc)))
8656 (while (setq f (pop files))
8657 (save-excursion
8658 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8659 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8660 (setq f (expand-file-name f))
8661 (if (eq org-refile-use-outline-path 'file)
8662 (push (list (file-name-nondirectory f) f nil nil) targets))
8663 (save-excursion
8664 (save-restriction
8665 (widen)
8666 (goto-char (point-min))
8667 (while (re-search-forward descre nil t)
8668 (goto-char (setq pos0 (point-at-bol)))
8669 (catch 'next
8670 (when org-refile-target-verify-function
8671 (save-match-data
8672 (or (funcall org-refile-target-verify-function)
8673 (throw 'next t))))
8674 (when (looking-at org-complex-heading-regexp)
8675 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8676 txt (org-link-display-format (match-string 4))
8677 re (concat "^" (regexp-quote
8678 (buffer-substring (match-beginning 1)
8679 (match-end 4)))))
8680 (if (match-end 5) (setq re (concat re "[ \t]+"
8681 (regexp-quote
8682 (match-string 5)))))
8683 (setq re (concat re "[ \t]*$"))
8684 (when org-refile-use-outline-path
8685 (setq txt (mapconcat 'org-protect-slash
8686 (append
8687 (if (eq org-refile-use-outline-path 'file)
8688 (list (file-name-nondirectory
8689 (buffer-file-name (buffer-base-buffer))))
8690 (if (eq org-refile-use-outline-path 'full-file-path)
8691 (list (buffer-file-name (buffer-base-buffer)))))
8692 (org-get-outline-path fast-path-p level txt)
8693 (list txt))
8694 "/")))
8695 (push (list txt f re (point)) targets)))
8696 (when (= (point) pos0)
8697 ;; verification function has not moved point
8698 (goto-char (point-at-eol))))))))))
8699 (message "Getting targets...done")
8700 (nreverse targets)))
8702 (defun org-protect-slash (s)
8703 (while (string-match "/" s)
8704 (setq s (replace-match "\\" t t s)))
8707 (defvar org-olpa (make-vector 20 nil))
8709 (defun org-get-outline-path (&optional fastp level heading)
8710 "Return the outline path to the current entry, as a list."
8711 (if fastp
8712 (progn
8713 (if (> level 19)
8714 (error "Outline path failure, more than 19 levels."))
8715 (loop for i from level upto 19 do
8716 (aset org-olpa i nil))
8717 (prog1
8718 (delq nil (append org-olpa nil))
8719 (aset org-olpa level heading)))
8720 (let (rtn)
8721 (save-excursion
8722 (while (org-up-heading-safe)
8723 (when (looking-at org-complex-heading-regexp)
8724 (push (org-match-string-no-properties 4) rtn)))
8725 rtn))))
8727 (defvar org-refile-history nil
8728 "History for refiling operations.")
8730 (defvar org-after-refile-insert-hook nil
8731 "Hook run after `org-refile' has inserted its stuff at the new location.
8732 Note that this is still *before* the stuff will be removed from
8733 the *old* location.")
8735 (defun org-refile (&optional goto default-buffer rfloc)
8736 "Move the entry at point to another heading.
8737 The list of target headings is compiled using the information in
8738 `org-refile-targets', which see. This list is created before each use
8739 and will therefore always be up-to-date.
8741 At the target location, the entry is filed as a subitem of the target heading.
8742 Depending on `org-reverse-note-order', the new subitem will either be the
8743 first or the last subitem.
8745 If there is an active region, all entries in that region will be moved.
8746 However, the region must fulfil the requirement that the first heading
8747 is the first one sets the top-level of the moved text - at most siblings
8748 below it are allowed.
8750 With prefix arg GOTO, the command will only visit the target location,
8751 not actually move anything.
8752 With a double prefix `C-u C-u', go to the location where the last refiling
8753 operation has put the subtree.
8755 RFLOC can be a refile location obtained in a different way.
8757 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8758 (interactive "P")
8759 (let* ((cbuf (current-buffer))
8760 (regionp (org-region-active-p))
8761 (region-start (and regionp (region-beginning)))
8762 (region-end (and regionp (region-end)))
8763 (region-length (and regionp (- region-end region-start)))
8764 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8765 pos it nbuf file re level reversed)
8766 (when regionp
8767 (goto-char region-start)
8768 (or (bolp) (goto-char (point-at-bol)))
8769 (setq region-start (point))
8770 (unless (org-kill-is-subtree-p
8771 (buffer-substring region-start region-end))
8772 (error "The region is not a (sequence of) subtree(s)")))
8773 (if (equal goto '(16))
8774 (org-refile-goto-last-stored)
8775 (when (setq it (or rfloc
8776 (save-excursion
8777 (org-refile-get-location
8778 (if goto "Goto: " "Refile to: ") default-buffer
8779 org-refile-allow-creating-parent-nodes))))
8780 (setq file (nth 1 it)
8781 re (nth 2 it)
8782 pos (nth 3 it))
8783 (if (and (not goto)
8785 (equal (buffer-file-name) file)
8786 (if regionp
8787 (and (>= pos region-start)
8788 (<= pos region-end))
8789 (and (>= pos (point))
8790 (< pos (save-excursion
8791 (org-end-of-subtree t t))))))
8792 (error "Cannot refile to position inside the tree or region"))
8794 (setq nbuf (or (find-buffer-visiting file)
8795 (find-file-noselect file)))
8796 (if goto
8797 (progn
8798 (switch-to-buffer nbuf)
8799 (goto-char pos)
8800 (org-show-context 'org-goto))
8801 (if regionp
8802 (progn
8803 (org-kill-new (buffer-substring region-start region-end))
8804 (org-save-markers-in-region region-start region-end))
8805 (org-copy-subtree 1 nil t))
8806 (save-excursion
8807 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8808 (find-file-noselect file))))
8809 (setq reversed (org-notes-order-reversed-p))
8810 (save-excursion
8811 (save-restriction
8812 (widen)
8813 (if pos
8814 (progn
8815 (goto-char pos)
8816 (looking-at outline-regexp)
8817 (setq level (org-get-valid-level (funcall outline-level) 1))
8818 (goto-char
8819 (if reversed
8820 (or (outline-next-heading) (point-max))
8821 (or (save-excursion (org-get-next-sibling))
8822 (org-end-of-subtree t t)
8823 (point-max)))))
8824 (setq level 1)
8825 (if (not reversed)
8826 (goto-char (point-max))
8827 (goto-char (point-min))
8828 (or (outline-next-heading) (goto-char (point-max)))))
8829 (if (not (bolp)) (newline))
8830 (bookmark-set "org-refile-last-stored")
8831 (org-paste-subtree level)
8832 (if (fboundp 'deactivate-mark) (deactivate-mark))
8833 (run-hooks 'org-after-refile-insert-hook))))
8834 (if regionp
8835 (delete-region (point) (+ (point) region-length))
8836 (org-cut-subtree))
8837 (when (featurep 'org-inlinetask)
8838 (org-inlinetask-remove-END-maybe))
8839 (setq org-markers-to-move nil)
8840 (message "Refiled to \"%s\"" (car it))))))
8841 (org-reveal))
8843 (defun org-refile-goto-last-stored ()
8844 "Go to the location where the last refile was stored."
8845 (interactive)
8846 (bookmark-jump "org-refile-last-stored")
8847 (message "This is the location of the last refile"))
8849 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8850 "Prompt the user for a refile location, using PROMPT."
8851 (let ((org-refile-targets org-refile-targets)
8852 (org-refile-use-outline-path org-refile-use-outline-path))
8853 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8854 (unless org-refile-target-table
8855 (error "No refile targets"))
8856 (let* ((cbuf (current-buffer))
8857 (partial-completion-mode nil)
8858 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8859 (cfunc (if (and org-refile-use-outline-path
8860 org-outline-path-complete-in-steps)
8861 'org-olpath-completing-read
8862 'org-icompleting-read))
8863 (extra (if org-refile-use-outline-path "/" ""))
8864 (filename (and cfn (expand-file-name cfn)))
8865 (tbl (mapcar
8866 (lambda (x)
8867 (if (and (not (member org-refile-use-outline-path
8868 '(file full-file-path)))
8869 (not (equal filename (nth 1 x))))
8870 (cons (concat (car x) extra " ("
8871 (file-name-nondirectory (nth 1 x)) ")")
8872 (cdr x))
8873 (cons (concat (car x) extra) (cdr x))))
8874 org-refile-target-table))
8875 (completion-ignore-case t)
8876 pa answ parent-target child parent old-hist)
8877 (setq old-hist org-refile-history)
8878 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8879 nil 'org-refile-history))
8880 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8881 (if pa
8882 (progn
8883 (when (or (not org-refile-history)
8884 (not (eq old-hist org-refile-history))
8885 (not (equal (car pa) (car org-refile-history))))
8886 (setq org-refile-history
8887 (cons (car pa) (if (assoc (car org-refile-history) tbl)
8888 org-refile-history
8889 (cdr org-refile-history))))
8890 (if (equal (car org-refile-history) (nth 1 org-refile-history))
8891 (pop org-refile-history)))
8893 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8894 (setq parent (match-string 1 answ)
8895 child (match-string 2 answ))
8896 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8897 (when (and parent-target
8898 (or (eq new-nodes t)
8899 (and (eq new-nodes 'confirm)
8900 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8901 (org-refile-new-child parent-target child))))))
8903 (defun org-refile-new-child (parent-target child)
8904 "Use refile target PARENT-TARGET to add new CHILD below it."
8905 (unless parent-target
8906 (error "Cannot find parent for new node"))
8907 (let ((file (nth 1 parent-target))
8908 (pos (nth 3 parent-target))
8909 level)
8910 (with-current-buffer (or (find-buffer-visiting file)
8911 (find-file-noselect file))
8912 (save-excursion
8913 (save-restriction
8914 (widen)
8915 (if pos
8916 (goto-char pos)
8917 (goto-char (point-max))
8918 (if (not (bolp)) (newline)))
8919 (when (looking-at outline-regexp)
8920 (setq level (funcall outline-level))
8921 (org-end-of-subtree t t))
8922 (org-back-over-empty-lines)
8923 (insert "\n" (make-string
8924 (if pos (org-get-valid-level level 1) 1) ?*)
8925 " " child "\n")
8926 (beginning-of-line 0)
8927 (list (concat (car parent-target) "/" child) file "" (point)))))))
8929 (defun org-olpath-completing-read (prompt collection &rest args)
8930 "Read an outline path like a file name."
8931 (let ((thetable collection)
8932 (org-completion-use-ido nil) ; does not work with ido.
8933 (org-completion-use-iswitchb nil)) ; or iswitchb
8934 (apply
8935 'org-icompleting-read prompt
8936 (lambda (string predicate &optional flag)
8937 (let (rtn r f (l (length string)))
8938 (cond
8939 ((eq flag nil)
8940 ;; try completion
8941 (try-completion string thetable))
8942 ((eq flag t)
8943 ;; all-completions
8944 (setq rtn (all-completions string thetable predicate))
8945 (mapcar
8946 (lambda (x)
8947 (setq r (substring x l))
8948 (if (string-match " ([^)]*)$" x)
8949 (setq f (match-string 0 x))
8950 (setq f ""))
8951 (if (string-match "/" r)
8952 (concat string (substring r 0 (match-end 0)) f)
8954 rtn))
8955 ((eq flag 'lambda)
8956 ;; exact match?
8957 (assoc string thetable)))
8959 args)))
8961 ;;;; Dynamic blocks
8963 (defun org-find-dblock (name)
8964 "Find the first dynamic block with name NAME in the buffer.
8965 If not found, stay at current position and return nil."
8966 (let (pos)
8967 (save-excursion
8968 (goto-char (point-min))
8969 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8970 nil t)
8971 (match-beginning 0))))
8972 (if pos (goto-char pos))
8973 pos))
8975 (defconst org-dblock-start-re
8976 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8977 "Matches the startline of a dynamic block, with parameters.")
8979 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
8980 "Matches the end of a dynamic block.")
8982 (defun org-create-dblock (plist)
8983 "Create a dynamic block section, with parameters taken from PLIST.
8984 PLIST must contain a :name entry which is used as name of the block."
8985 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
8986 (end-of-line 1)
8987 (newline))
8988 (let ((col (current-column))
8989 (name (plist-get plist :name)))
8990 (insert "#+BEGIN: " name)
8991 (while plist
8992 (if (eq (car plist) :name)
8993 (setq plist (cddr plist))
8994 (insert " " (prin1-to-string (pop plist)))))
8995 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
8996 (beginning-of-line -2)))
8998 (defun org-prepare-dblock ()
8999 "Prepare dynamic block for refresh.
9000 This empties the block, puts the cursor at the insert position and returns
9001 the property list including an extra property :name with the block name."
9002 (unless (looking-at org-dblock-start-re)
9003 (error "Not at a dynamic block"))
9004 (let* ((begdel (1+ (match-end 0)))
9005 (name (org-no-properties (match-string 1)))
9006 (params (append (list :name name)
9007 (read (concat "(" (match-string 3) ")")))))
9008 (save-excursion
9009 (beginning-of-line 1)
9010 (skip-chars-forward " \t")
9011 (setq params (plist-put params :indentation-column (current-column))))
9012 (unless (re-search-forward org-dblock-end-re nil t)
9013 (error "Dynamic block not terminated"))
9014 (setq params
9015 (append params
9016 (list :content (buffer-substring
9017 begdel (match-beginning 0)))))
9018 (delete-region begdel (match-beginning 0))
9019 (goto-char begdel)
9020 (open-line 1)
9021 params))
9023 (defun org-map-dblocks (&optional command)
9024 "Apply COMMAND to all dynamic blocks in the current buffer.
9025 If COMMAND is not given, use `org-update-dblock'."
9026 (let ((cmd (or command 'org-update-dblock))
9027 pos)
9028 (save-excursion
9029 (goto-char (point-min))
9030 (while (re-search-forward org-dblock-start-re nil t)
9031 (goto-char (setq pos (match-beginning 0)))
9032 (condition-case nil
9033 (funcall cmd)
9034 (error (message "Error during update of dynamic block")))
9035 (goto-char pos)
9036 (unless (re-search-forward org-dblock-end-re nil t)
9037 (error "Dynamic block not terminated"))))))
9039 (defun org-dblock-update (&optional arg)
9040 "User command for updating dynamic blocks.
9041 Update the dynamic block at point. With prefix ARG, update all dynamic
9042 blocks in the buffer."
9043 (interactive "P")
9044 (if arg
9045 (org-update-all-dblocks)
9046 (or (looking-at org-dblock-start-re)
9047 (org-beginning-of-dblock))
9048 (org-update-dblock)))
9050 (defun org-update-dblock ()
9051 "Update the dynamic block at point
9052 This means to empty the block, parse for parameters and then call
9053 the correct writing function."
9054 (save-window-excursion
9055 (let* ((pos (point))
9056 (line (org-current-line))
9057 (params (org-prepare-dblock))
9058 (name (plist-get params :name))
9059 (indent (plist-get params :indentation-column))
9060 (cmd (intern (concat "org-dblock-write:" name))))
9061 (message "Updating dynamic block `%s' at line %d..." name line)
9062 (funcall cmd params)
9063 (message "Updating dynamic block `%s' at line %d...done" name line)
9064 (goto-char pos)
9065 (when (and indent (> indent 0))
9066 (setq indent (make-string indent ?\ ))
9067 (save-excursion
9068 (org-beginning-of-dblock)
9069 (forward-line 1)
9070 (while (not (looking-at org-dblock-end-re))
9071 (insert indent)
9072 (beginning-of-line 2))
9073 (when (looking-at org-dblock-end-re)
9074 (and (looking-at "[ \t]+")
9075 (replace-match ""))
9076 (insert indent)))))))
9078 (defun org-beginning-of-dblock ()
9079 "Find the beginning of the dynamic block at point.
9080 Error if there is no such block at point."
9081 (let ((pos (point))
9082 beg)
9083 (end-of-line 1)
9084 (if (and (re-search-backward org-dblock-start-re nil t)
9085 (setq beg (match-beginning 0))
9086 (re-search-forward org-dblock-end-re nil t)
9087 (> (match-end 0) pos))
9088 (goto-char beg)
9089 (goto-char pos)
9090 (error "Not in a dynamic block"))))
9092 (defun org-update-all-dblocks ()
9093 "Update all dynamic blocks in the buffer.
9094 This function can be used in a hook."
9095 (when (org-mode-p)
9096 (org-map-dblocks 'org-update-dblock)))
9099 ;;;; Completion
9101 (defconst org-additional-option-like-keywords
9102 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9103 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9104 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
9105 "BEGIN:" "END:"
9106 "ORGTBL" "TBLFM:" "TBLNAME:"
9107 "BEGIN_EXAMPLE" "END_EXAMPLE"
9108 "BEGIN_QUOTE" "END_QUOTE"
9109 "BEGIN_VERSE" "END_VERSE"
9110 "BEGIN_CENTER" "END_CENTER"
9111 "BEGIN_SRC" "END_SRC"
9112 "CATEGORY" "COLUMNS"
9113 "CAPTION" "LABEL"
9114 "BIND"
9115 "MACRO"))
9117 (defcustom org-structure-template-alist
9119 ("s" "#+begin_src ?\n\n#+end_src"
9120 "<src lang=\"?\">\n\n</src>")
9121 ("e" "#+begin_example\n?\n#+end_example"
9122 "<example>\n?\n</example>")
9123 ("q" "#+begin_quote\n?\n#+end_quote"
9124 "<quote>\n?\n</quote>")
9125 ("v" "#+begin_verse\n?\n#+end_verse"
9126 "<verse>\n?\n/verse>")
9127 ("c" "#+begin_center\n?\n#+end_center"
9128 "<center>\n?\n/center>")
9129 ("l" "#+begin_latex\n?\n#+end_latex"
9130 "<literal style=\"latex\">\n?\n</literal>")
9131 ("L" "#+latex: "
9132 "<literal style=\"latex\">?</literal>")
9133 ("h" "#+begin_html\n?\n#+end_html"
9134 "<literal style=\"html\">\n?\n</literal>")
9135 ("H" "#+html: "
9136 "<literal style=\"html\">?</literal>")
9137 ("a" "#+begin_ascii\n?\n#+end_ascii")
9138 ("A" "#+ascii: ")
9139 ("i" "#+include %file ?"
9140 "<include file=%file markup=\"?\">")
9142 "Structure completion elements.
9143 This is a list of abbreviation keys and values. The value gets inserted
9144 it you type @samp{.} followed by the key and then the completion key,
9145 usually `M-TAB'. %file will be replaced by a file name after prompting
9146 for the file using completion.
9147 There are two templates for each key, the first uses the original Org syntax,
9148 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9149 the default when the /org-mtags.el/ module has been loaded. See also the
9150 variable `org-mtags-prefer-muse-templates'.
9151 This is an experimental feature, it is undecided if it is going to stay in."
9152 :group 'org-completion
9153 :type '(repeat
9154 (string :tag "Key")
9155 (string :tag "Template")
9156 (string :tag "Muse Template")))
9158 (defun org-try-structure-completion ()
9159 "Try to complete a structure template before point.
9160 This looks for strings like \"<e\" on an otherwise empty line and
9161 expands them."
9162 (let ((l (buffer-substring (point-at-bol) (point)))
9164 (when (and (looking-at "[ \t]*$")
9165 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9166 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9167 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9168 (match-beginning 1)) a)
9169 t)))
9171 (defun org-complete-expand-structure-template (start cell)
9172 "Expand a structure template."
9173 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9174 (rpl (nth (if musep 2 1) cell))
9175 (ind ""))
9176 (delete-region start (point))
9177 (when (string-match "\\`#\\+" rpl)
9178 (cond
9179 ((bolp))
9180 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9181 (setq ind (buffer-substring (point-at-bol) (point))))
9182 (t (newline))))
9183 (setq start (point))
9184 (if (string-match "%file" rpl)
9185 (setq rpl (replace-match
9186 (concat
9187 "\""
9188 (save-match-data
9189 (abbreviate-file-name (read-file-name "Include file: ")))
9190 "\"")
9191 t t rpl)))
9192 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9193 (concat "\n" ind)))
9194 (insert rpl)
9195 (if (re-search-backward "\\?" start t) (delete-char 1))))
9198 (defun org-complete (&optional arg)
9199 "Perform completion on word at point.
9200 At the beginning of a headline, this completes TODO keywords as given in
9201 `org-todo-keywords'.
9202 If the current word is preceded by a backslash, completes the TeX symbols
9203 that are supported for HTML support.
9204 If the current word is preceded by \"#+\", completes special words for
9205 setting file options.
9206 In the line after \"#+STARTUP:, complete valid keywords.\"
9207 At all other locations, this simply calls the value of
9208 `org-completion-fallback-command'."
9209 (interactive "P")
9210 (org-without-partial-completion
9211 (catch 'exit
9212 (let* ((a nil)
9213 (end (point))
9214 (beg1 (save-excursion
9215 (skip-chars-backward (org-re "[:alnum:]_@"))
9216 (point)))
9217 (beg (save-excursion
9218 (skip-chars-backward "a-zA-Z0-9_:$")
9219 (point)))
9220 (confirm (lambda (x) (stringp (car x))))
9221 (searchhead (equal (char-before beg) ?*))
9222 (struct
9223 (when (and (member (char-before beg1) '(?. ?<))
9224 (setq a (assoc (buffer-substring beg1 (point))
9225 org-structure-template-alist)))
9226 (org-complete-expand-structure-template (1- beg1) a)
9227 (throw 'exit t)))
9228 (tag (and (equal (char-before beg1) ?:)
9229 (equal (char-after (point-at-bol)) ?*)))
9230 (prop (and (equal (char-before beg1) ?:)
9231 (not (equal (char-after (point-at-bol)) ?*))))
9232 (texp (equal (char-before beg) ?\\))
9233 (link (equal (char-before beg) ?\[))
9234 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9235 beg)
9236 "#+"))
9237 (startup (string-match "^#\\+STARTUP:.*"
9238 (buffer-substring (point-at-bol) (point))))
9239 (completion-ignore-case opt)
9240 (type nil)
9241 (tbl nil)
9242 (table (cond
9243 (opt
9244 (setq type :opt)
9245 (require 'org-exp)
9246 (append
9247 (delq nil
9248 (mapcar
9249 (lambda (x)
9250 (if (string-match
9251 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9252 (cons (match-string 2 x)
9253 (match-string 1 x))))
9254 (org-split-string (org-get-current-options) "\n")))
9255 (mapcar 'list org-additional-option-like-keywords)))
9256 (startup
9257 (setq type :startup)
9258 org-startup-options)
9259 (link (append org-link-abbrev-alist-local
9260 org-link-abbrev-alist))
9261 (texp
9262 (setq type :tex)
9263 org-html-entities)
9264 ((string-match "\\`\\*+[ \t]+\\'"
9265 (buffer-substring (point-at-bol) beg))
9266 (setq type :todo)
9267 (mapcar 'list org-todo-keywords-1))
9268 (searchhead
9269 (setq type :searchhead)
9270 (save-excursion
9271 (goto-char (point-min))
9272 (while (re-search-forward org-todo-line-regexp nil t)
9273 (push (list
9274 (org-make-org-heading-search-string
9275 (match-string 3) t))
9276 tbl)))
9277 tbl)
9278 (tag (setq type :tag beg beg1)
9279 (or org-tag-alist (org-get-buffer-tags)))
9280 (prop (setq type :prop beg beg1)
9281 (mapcar 'list (org-buffer-property-keys nil t t)))
9282 (t (progn
9283 (call-interactively org-completion-fallback-command)
9284 (throw 'exit nil)))))
9285 (pattern (buffer-substring-no-properties beg end))
9286 (completion (try-completion pattern table confirm)))
9287 (cond ((eq completion t)
9288 (if (not (assoc (upcase pattern) table))
9289 (message "Already complete")
9290 (if (and (equal type :opt)
9291 (not (member (car (assoc (upcase pattern) table))
9292 org-additional-option-like-keywords)))
9293 (insert (substring (cdr (assoc (upcase pattern) table))
9294 (length pattern)))
9295 (if (memq type '(:tag :prop)) (insert ":")))))
9296 ((null completion)
9297 (message "Can't find completion for \"%s\"" pattern)
9298 (ding))
9299 ((not (string= pattern completion))
9300 (delete-region beg end)
9301 (if (string-match " +$" completion)
9302 (setq completion (replace-match "" t t completion)))
9303 (insert completion)
9304 (if (get-buffer-window "*Completions*")
9305 (delete-window (get-buffer-window "*Completions*")))
9306 (if (assoc completion table)
9307 (if (eq type :todo) (insert " ")
9308 (if (memq type '(:tag :prop)) (insert ":"))))
9309 (if (and (equal type :opt) (assoc completion table))
9310 (message "%s" (substitute-command-keys
9311 "Press \\[org-complete] again to insert example settings"))))
9313 (message "Making completion list...")
9314 (let ((list (sort (all-completions pattern table confirm)
9315 'string<)))
9316 (with-output-to-temp-buffer "*Completions*"
9317 (condition-case nil
9318 ;; Protection needed for XEmacs and emacs 21
9319 (display-completion-list list pattern)
9320 (error (display-completion-list list)))))
9321 (message "Making completion list...%s" "done")))))))
9323 ;;;; TODO, DEADLINE, Comments
9325 (defun org-toggle-comment ()
9326 "Change the COMMENT state of an entry."
9327 (interactive)
9328 (save-excursion
9329 (org-back-to-heading)
9330 (let (case-fold-search)
9331 (if (looking-at (concat outline-regexp
9332 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9333 (replace-match "" t t nil 1)
9334 (if (looking-at outline-regexp)
9335 (progn
9336 (goto-char (match-end 0))
9337 (insert org-comment-string " ")))))))
9339 (defvar org-last-todo-state-is-todo nil
9340 "This is non-nil when the last TODO state change led to a TODO state.
9341 If the last change removed the TODO tag or switched to DONE, then
9342 this is nil.")
9344 (defvar org-setting-tags nil) ; dynamically skipped
9346 (defun org-parse-local-options (string var)
9347 "Parse STRING for startup setting relevant for variable VAR."
9348 (let ((rtn (symbol-value var))
9349 e opts)
9350 (save-match-data
9351 (if (or (not string) (not (string-match "\\S-" string)))
9353 (setq opts (delq nil (mapcar (lambda (x)
9354 (setq e (assoc x org-startup-options))
9355 (if (eq (nth 1 e) var) e nil))
9356 (org-split-string string "[ \t]+"))))
9357 (if (not opts)
9359 (setq rtn nil)
9360 (while (setq e (pop opts))
9361 (if (not (nth 3 e))
9362 (setq rtn (nth 2 e))
9363 (if (not (listp rtn)) (setq rtn nil))
9364 (push (nth 2 e) rtn)))
9365 rtn)))))
9367 (defvar org-todo-setup-filter-hook nil
9368 "Hook for functions that pre-filter todo specs.
9370 Each function takes a todo spec and returns either `nil' or the spec
9371 transformed into canonical form." )
9373 (defvar org-todo-get-default-hook nil
9374 "Hook for functions that get a default item for todo.
9376 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9377 `nil' or a string to be used for the todo mark." )
9379 (defvar org-agenda-headline-snapshot-before-repeat)
9381 (defun org-todo (&optional arg)
9382 "Change the TODO state of an item.
9383 The state of an item is given by a keyword at the start of the heading,
9384 like
9385 *** TODO Write paper
9386 *** DONE Call mom
9388 The different keywords are specified in the variable `org-todo-keywords'.
9389 By default the available states are \"TODO\" and \"DONE\".
9390 So for this example: when the item starts with TODO, it is changed to DONE.
9391 When it starts with DONE, the DONE is removed. And when neither TODO nor
9392 DONE are present, add TODO at the beginning of the heading.
9394 With C-u prefix arg, use completion to determine the new state.
9395 With numeric prefix arg, switch to that state.
9396 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9397 With a tripple C-u prefix, circumvent any state blocking.
9399 For calling through lisp, arg is also interpreted in the following way:
9400 'none -> empty state
9401 \"\"(empty string) -> switch to empty state
9402 'done -> switch to DONE
9403 'nextset -> switch to the next set of keywords
9404 'previousset -> switch to the previous set of keywords
9405 \"WAITING\" -> switch to the specified keyword, but only if it
9406 really is a member of `org-todo-keywords'."
9407 (interactive "P")
9408 (if (equal arg '(16)) (setq arg 'nextset))
9409 (let ((org-blocker-hook org-blocker-hook)
9410 (case-fold-search nil))
9411 (when (equal arg '(64))
9412 (setq arg nil org-blocker-hook nil))
9413 (when (and org-blocker-hook
9414 (or org-inhibit-blocking
9415 (org-entry-get nil "NOBLOCKING")))
9416 (setq org-blocker-hook nil))
9417 (save-excursion
9418 (catch 'exit
9419 (org-back-to-heading)
9420 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9421 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9422 (looking-at " *"))
9423 (let* ((match-data (match-data))
9424 (startpos (point-at-bol))
9425 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9426 (org-log-done org-log-done)
9427 (org-log-repeat org-log-repeat)
9428 (org-todo-log-states org-todo-log-states)
9429 (this (match-string 1))
9430 (hl-pos (match-beginning 0))
9431 (head (org-get-todo-sequence-head this))
9432 (ass (assoc head org-todo-kwd-alist))
9433 (interpret (nth 1 ass))
9434 (done-word (nth 3 ass))
9435 (final-done-word (nth 4 ass))
9436 (last-state (or this ""))
9437 (completion-ignore-case t)
9438 (member (member this org-todo-keywords-1))
9439 (tail (cdr member))
9440 (state (cond
9441 ((and org-todo-key-trigger
9442 (or (and (equal arg '(4))
9443 (eq org-use-fast-todo-selection 'prefix))
9444 (and (not arg) org-use-fast-todo-selection
9445 (not (eq org-use-fast-todo-selection
9446 'prefix)))))
9447 ;; Use fast selection
9448 (org-fast-todo-selection))
9449 ((and (equal arg '(4))
9450 (or (not org-use-fast-todo-selection)
9451 (not org-todo-key-trigger)))
9452 ;; Read a state with completion
9453 (org-icompleting-read
9454 "State: " (mapcar (lambda(x) (list x))
9455 org-todo-keywords-1)
9456 nil t))
9457 ((eq arg 'right)
9458 (if this
9459 (if tail (car tail) nil)
9460 (car org-todo-keywords-1)))
9461 ((eq arg 'left)
9462 (if (equal member org-todo-keywords-1)
9464 (if this
9465 (nth (- (length org-todo-keywords-1)
9466 (length tail) 2)
9467 org-todo-keywords-1)
9468 (org-last org-todo-keywords-1))))
9469 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9470 (setq arg nil))) ; hack to fall back to cycling
9471 (arg
9472 ;; user or caller requests a specific state
9473 (cond
9474 ((equal arg "") nil)
9475 ((eq arg 'none) nil)
9476 ((eq arg 'done) (or done-word (car org-done-keywords)))
9477 ((eq arg 'nextset)
9478 (or (car (cdr (member head org-todo-heads)))
9479 (car org-todo-heads)))
9480 ((eq arg 'previousset)
9481 (let ((org-todo-heads (reverse org-todo-heads)))
9482 (or (car (cdr (member head org-todo-heads)))
9483 (car org-todo-heads))))
9484 ((car (member arg org-todo-keywords-1)))
9485 ((nth (1- (prefix-numeric-value arg))
9486 org-todo-keywords-1))))
9487 ((null member) (or head (car org-todo-keywords-1)))
9488 ((equal this final-done-word) nil) ;; -> make empty
9489 ((null tail) nil) ;; -> first entry
9490 ((memq interpret '(type priority))
9491 (if (eq this-command last-command)
9492 (car tail)
9493 (if (> (length tail) 0)
9494 (or done-word (car org-done-keywords))
9495 nil)))
9497 (car tail))))
9498 (state (or
9499 (run-hook-with-args-until-success
9500 'org-todo-get-default-hook state last-state)
9501 state))
9502 (next (if state (concat " " state " ") " "))
9503 (change-plist (list :type 'todo-state-change :from this :to state
9504 :position startpos))
9505 dolog now-done-p)
9506 (when org-blocker-hook
9507 (setq org-last-todo-state-is-todo
9508 (not (member this org-done-keywords)))
9509 (unless (save-excursion
9510 (save-match-data
9511 (run-hook-with-args-until-failure
9512 'org-blocker-hook change-plist)))
9513 (if (interactive-p)
9514 (error "TODO state change from %s to %s blocked" this state)
9515 ;; fail silently
9516 (message "TODO state change from %s to %s blocked" this state)
9517 (throw 'exit nil))))
9518 (store-match-data match-data)
9519 (replace-match next t t)
9520 (unless (pos-visible-in-window-p hl-pos)
9521 (message "TODO state changed to %s" (org-trim next)))
9522 (unless head
9523 (setq head (org-get-todo-sequence-head state)
9524 ass (assoc head org-todo-kwd-alist)
9525 interpret (nth 1 ass)
9526 done-word (nth 3 ass)
9527 final-done-word (nth 4 ass)))
9528 (when (memq arg '(nextset previousset))
9529 (message "Keyword-Set %d/%d: %s"
9530 (- (length org-todo-sets) -1
9531 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9532 (length org-todo-sets)
9533 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9534 (setq org-last-todo-state-is-todo
9535 (not (member state org-done-keywords)))
9536 (setq now-done-p (and (member state org-done-keywords)
9537 (not (member this org-done-keywords))))
9538 (and logging (org-local-logging logging))
9539 (when (and (or org-todo-log-states org-log-done)
9540 (not (eq org-inhibit-logging t))
9541 (not (memq arg '(nextset previousset))))
9542 ;; we need to look at recording a time and note
9543 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9544 (nth 2 (assoc this org-todo-log-states))))
9545 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9546 (setq dolog 'time))
9547 (when (and state
9548 (member state org-not-done-keywords)
9549 (not (member this org-not-done-keywords)))
9550 ;; This is now a todo state and was not one before
9551 ;; If there was a CLOSED time stamp, get rid of it.
9552 (org-add-planning-info nil nil 'closed))
9553 (when (and now-done-p org-log-done)
9554 ;; It is now done, and it was not done before
9555 (org-add-planning-info 'closed (org-current-time))
9556 (if (and (not dolog) (eq 'note org-log-done))
9557 (org-add-log-setup 'done state this 'findpos 'note)))
9558 (when (and state dolog)
9559 ;; This is a non-nil state, and we need to log it
9560 (org-add-log-setup 'state state this 'findpos dolog)))
9561 ;; Fixup tag positioning
9562 (org-todo-trigger-tag-changes state)
9563 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9564 (when org-provide-todo-statistics
9565 (org-update-parent-todo-statistics))
9566 (run-hooks 'org-after-todo-state-change-hook)
9567 (if (and arg (not (member state org-done-keywords)))
9568 (setq head (org-get-todo-sequence-head state)))
9569 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9570 ;; Do we need to trigger a repeat?
9571 (when now-done-p
9572 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9573 ;; This is for the agenda, take a snapshot of the headline.
9574 (save-match-data
9575 (setq org-agenda-headline-snapshot-before-repeat
9576 (org-get-heading))))
9577 (org-auto-repeat-maybe state))
9578 ;; Fixup cursor location if close to the keyword
9579 (if (and (outline-on-heading-p)
9580 (not (bolp))
9581 (save-excursion (beginning-of-line 1)
9582 (looking-at org-todo-line-regexp))
9583 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9584 (progn
9585 (goto-char (or (match-end 2) (match-end 1)))
9586 (and (looking-at " ") (just-one-space))))
9587 (when org-trigger-hook
9588 (save-excursion
9589 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9591 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9592 "Block turning an entry into a TODO, using the hierarchy.
9593 This checks whether the current task should be blocked from state
9594 changes. Such blocking occurs when:
9596 1. The task has children which are not all in a completed state.
9598 2. A task has a parent with the property :ORDERED:, and there
9599 are siblings prior to the current task with incomplete
9600 status.
9602 3. The parent of the task is blocked because it has siblings that should
9603 be done first, or is child of a block grandparent TODO entry."
9605 (catch 'dont-block
9606 ;; If this is not a todo state change, or if this entry is already DONE,
9607 ;; do not block
9608 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9609 (member (plist-get change-plist :from)
9610 (cons 'done org-done-keywords))
9611 (member (plist-get change-plist :to)
9612 (cons 'todo org-not-done-keywords)))
9613 (throw 'dont-block t))
9614 ;; If this task has children, and any are undone, it's blocked
9615 (save-excursion
9616 (org-back-to-heading t)
9617 (let ((this-level (funcall outline-level)))
9618 (outline-next-heading)
9619 (let ((child-level (funcall outline-level)))
9620 (while (and (not (eobp))
9621 (> child-level this-level))
9622 ;; this todo has children, check whether they are all
9623 ;; completed
9624 (if (and (not (org-entry-is-done-p))
9625 (org-entry-is-todo-p))
9626 (throw 'dont-block nil))
9627 (outline-next-heading)
9628 (setq child-level (funcall outline-level))))))
9629 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9630 ;; any previous siblings are undone, it's blocked
9631 (save-excursion
9632 (org-back-to-heading t)
9633 (let* ((pos (point))
9634 (parent-pos (and (org-up-heading-safe) (point))))
9635 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9636 (when (and (org-entry-get (point) "ORDERED")
9637 (forward-line 1)
9638 (re-search-forward org-not-done-heading-regexp pos t))
9639 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9640 ;; Search further up the hierarchy, to see if an anchestor is blocked
9641 (while t
9642 (goto-char parent-pos)
9643 (if (not (looking-at org-not-done-heading-regexp))
9644 (throw 'dont-block t)) ; do not block, parent is not a TODO
9645 (setq pos (point))
9646 (setq parent-pos (and (org-up-heading-safe) (point)))
9647 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9648 (when (and (org-entry-get (point) "ORDERED")
9649 (forward-line 1)
9650 (re-search-forward org-not-done-heading-regexp pos t))
9651 (throw 'dont-block nil))))))) ; block, older sibling not done.
9653 (defcustom org-track-ordered-property-with-tag nil
9654 "Should the ORDERED property also be shown as a tag?
9655 The ORDERED property decides if an entry should require subtasks to be
9656 completed in sequence. Since a property is not very visible, setting
9657 this option means that toggling the ORDERED property with the command
9658 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9659 not relevant for the behavior, but it makes things more visible.
9661 Note that toggling the tag with tags commands will not change the property
9662 and therefore not influence behavior!
9664 This can be t, meaning the tag ORDERED should be used, It can also be a
9665 string to select a different tag for this task."
9666 :group 'org-todo
9667 :type '(choice
9668 (const :tag "No tracking" nil)
9669 (const :tag "Track with ORDERED tag" t)
9670 (string :tag "Use other tag")))
9672 (defun org-toggle-ordered-property ()
9673 "Toggle the ORDERED property of the current entry.
9674 For better visibility, you can track the value of this property with a tag.
9675 See variable `org-track-ordered-property-with-tag'."
9676 (interactive)
9677 (let* ((t1 org-track-ordered-property-with-tag)
9678 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9679 (save-excursion
9680 (org-back-to-heading)
9681 (if (org-entry-get nil "ORDERED")
9682 (progn
9683 (org-delete-property "ORDERED")
9684 (and tag (org-toggle-tag tag 'off))
9685 (message "Subtasks can be completed in arbitrary order"))
9686 (org-entry-put nil "ORDERED" "t")
9687 (and tag (org-toggle-tag tag 'on))
9688 (message "Subtasks must be completed in sequence")))))
9690 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9691 (defun org-block-todo-from-checkboxes (change-plist)
9692 "Block turning an entry into a TODO, using checkboxes.
9693 This checks whether the current task should be blocked from state
9694 changes because there are uncheckd boxes in this entry."
9695 (catch 'dont-block
9696 ;; If this is not a todo state change, or if this entry is already DONE,
9697 ;; do not block
9698 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9699 (member (plist-get change-plist :from)
9700 (cons 'done org-done-keywords))
9701 (member (plist-get change-plist :to)
9702 (cons 'todo org-not-done-keywords)))
9703 (throw 'dont-block t))
9704 ;; If this task has checkboxes that are not checked, it's blocked
9705 (save-excursion
9706 (org-back-to-heading t)
9707 (let ((beg (point)) end)
9708 (outline-next-heading)
9709 (setq end (point))
9710 (goto-char beg)
9711 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9712 end t)
9713 (progn
9714 (if (boundp 'org-blocked-by-checkboxes)
9715 (setq org-blocked-by-checkboxes t))
9716 (throw 'dont-block nil)))))
9717 t)) ; do not block
9719 (defun org-update-statistics-cookies (all)
9720 "Update the statistics cookie, either from TODO or from checkboxes.
9721 This should be called with the cursor in a line with a statistics cookie."
9722 (interactive "P")
9723 (if all
9724 (progn
9725 (org-update-checkbox-count 'all)
9726 (org-map-entries 'org-update-parent-todo-statistics))
9727 (if (not (org-on-heading-p))
9728 (org-update-checkbox-count)
9729 (let ((pos (move-marker (make-marker) (point)))
9730 end l1 l2)
9731 (ignore-errors (org-back-to-heading t))
9732 (if (not (org-on-heading-p))
9733 (org-update-checkbox-count)
9734 (setq l1 (org-outline-level))
9735 (setq end (save-excursion
9736 (outline-next-heading)
9737 (if (org-on-heading-p) (setq l2 (org-outline-level)))
9738 (point)))
9739 (if (and (save-excursion (re-search-forward
9740 "^[ \t]*[-+*] \\[[- X]\\]" end t))
9741 (not (save-excursion (re-search-forward
9742 ":COOKIE_DATA:.*\\<todo\\>" end t))))
9743 (org-update-checkbox-count)
9744 (if (and l2 (> l2 l1))
9745 (progn
9746 (goto-char end)
9747 (org-update-parent-todo-statistics))
9748 (error "No data for statistics cookie"))))
9749 (goto-char pos)
9750 (move-marker pos nil)))))
9752 (defvar org-entry-property-inherited-from) ;; defined below
9753 (defun org-update-parent-todo-statistics ()
9754 "Update any statistics cookie in the parent of the current headline.
9755 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9756 the entire subtree and this will travel up the hierarchy and update
9757 statistics everywhere."
9758 (interactive)
9759 (let* ((lim 0) prop
9760 (recursive (or (not org-hierarchical-todo-statistics)
9761 (string-match
9762 "\\<recursive\\>"
9763 (or (setq prop (org-entry-get
9764 nil "COOKIE_DATA" 'inherit)) ""))))
9765 (lim (or (and prop (marker-position
9766 org-entry-property-inherited-from))
9767 lim))
9768 (first t)
9769 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9770 level ltoggle l1 new ndel
9771 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9772 (catch 'exit
9773 (save-excursion
9774 (beginning-of-line 1)
9775 (if (org-at-heading-p)
9776 (setq ltoggle (funcall outline-level))
9777 (error "This should not happen"))
9778 (while (and (setq level (org-up-heading-safe))
9779 (or recursive first)
9780 (>= (point) lim))
9781 (setq first nil)
9782 (unless (and level
9783 (not (string-match
9784 "\\<checkbox\\>"
9785 (downcase
9786 (or (org-entry-get
9787 nil "COOKIE_DATA")
9788 "")))))
9789 (throw 'exit nil))
9790 (while (re-search-forward box-re (point-at-eol) t)
9791 (setq cnt-all 0 cnt-done 0 cookie-present t)
9792 (setq is-percent (match-end 2))
9793 (save-match-data
9794 (unless (outline-next-heading) (throw 'exit nil))
9795 (while (and (looking-at org-complex-heading-regexp)
9796 (> (setq l1 (length (match-string 1))) level))
9797 (setq kwd (and (or recursive (= l1 ltoggle))
9798 (match-string 2)))
9799 (if (or (eq org-provide-todo-statistics 'all-headlines)
9800 (and (listp org-provide-todo-statistics)
9801 (or (member kwd org-provide-todo-statistics)
9802 (member kwd org-done-keywords))))
9803 (setq cnt-all (1+ cnt-all))
9804 (if (eq org-provide-todo-statistics t)
9805 (and kwd (setq cnt-all (1+ cnt-all)))))
9806 (and (member kwd org-done-keywords)
9807 (setq cnt-done (1+ cnt-done)))
9808 (outline-next-heading)))
9809 (setq new
9810 (if is-percent
9811 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9812 (format "[%d/%d]" cnt-done cnt-all))
9813 ndel (- (match-end 0) (match-beginning 0)))
9814 (goto-char (match-beginning 0))
9815 (insert new)
9816 (delete-region (point) (+ (point) ndel))))
9817 (when cookie-present
9818 (run-hook-with-args 'org-after-todo-statistics-hook
9819 cnt-done (- cnt-all cnt-done)))))
9820 (run-hooks 'org-todo-statistics-hook)))
9822 (defvar org-after-todo-statistics-hook nil
9823 "Hook that is called after a TODO statistics cookie has been updated.
9824 Each function is called with two arguments: the number of not-done entries
9825 and the number of done entries.
9827 For example, the following function, when added to this hook, will switch
9828 an entry to DONE when all children are done, and back to TODO when new
9829 entries are set to a TODO status. Note that this hook is only called
9830 when there is a statistics cookie in the headline!
9832 (defun org-summary-todo (n-done n-not-done)
9833 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9834 (let (org-log-done org-log-states) ; turn off logging
9835 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9838 (defvar org-todo-statistics-hook nil
9839 "Hook that is run whenever Org thinks TODO statistics should be updated.
9840 This hook runs even if there is no statisics cookie present, in which case
9841 `org-after-todo-statistics-hook' would not run.")
9843 (defun org-todo-trigger-tag-changes (state)
9844 "Apply the changes defined in `org-todo-state-tags-triggers'."
9845 (let ((l org-todo-state-tags-triggers)
9846 changes)
9847 (when (or (not state) (equal state ""))
9848 (setq changes (append changes (cdr (assoc "" l)))))
9849 (when (and (stringp state) (> (length state) 0))
9850 (setq changes (append changes (cdr (assoc state l)))))
9851 (when (member state org-not-done-keywords)
9852 (setq changes (append changes (cdr (assoc 'todo l)))))
9853 (when (member state org-done-keywords)
9854 (setq changes (append changes (cdr (assoc 'done l)))))
9855 (dolist (c changes)
9856 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9858 (defun org-local-logging (value)
9859 "Get logging settings from a property VALUE."
9860 (let* (words w a)
9861 ;; directly set the variables, they are already local.
9862 (setq org-log-done nil
9863 org-log-repeat nil
9864 org-todo-log-states nil)
9865 (setq words (org-split-string value))
9866 (while (setq w (pop words))
9867 (cond
9868 ((setq a (assoc w org-startup-options))
9869 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9870 (set (nth 1 a) (nth 2 a))))
9871 ((setq a (org-extract-log-state-settings w))
9872 (and (member (car a) org-todo-keywords-1)
9873 (push a org-todo-log-states)))))))
9875 (defun org-get-todo-sequence-head (kwd)
9876 "Return the head of the TODO sequence to which KWD belongs.
9877 If KWD is not set, check if there is a text property remembering the
9878 right sequence."
9879 (let (p)
9880 (cond
9881 ((not kwd)
9882 (or (get-text-property (point-at-bol) 'org-todo-head)
9883 (progn
9884 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9885 nil (point-at-eol)))
9886 (get-text-property p 'org-todo-head))))
9887 ((not (member kwd org-todo-keywords-1))
9888 (car org-todo-keywords-1))
9889 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9891 (defun org-fast-todo-selection ()
9892 "Fast TODO keyword selection with single keys.
9893 Returns the new TODO keyword, or nil if no state change should occur."
9894 (let* ((fulltable org-todo-key-alist)
9895 (done-keywords org-done-keywords) ;; needed for the faces.
9896 (maxlen (apply 'max (mapcar
9897 (lambda (x)
9898 (if (stringp (car x)) (string-width (car x)) 0))
9899 fulltable)))
9900 (expert nil)
9901 (fwidth (+ maxlen 3 1 3))
9902 (ncol (/ (- (window-width) 4) fwidth))
9903 tg cnt e c tbl
9904 groups ingroup)
9905 (save-excursion
9906 (save-window-excursion
9907 (if expert
9908 (set-buffer (get-buffer-create " *Org todo*"))
9909 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9910 (erase-buffer)
9911 (org-set-local 'org-done-keywords done-keywords)
9912 (setq tbl fulltable cnt 0)
9913 (while (setq e (pop tbl))
9914 (cond
9915 ((equal e '(:startgroup))
9916 (push '() groups) (setq ingroup t)
9917 (when (not (= cnt 0))
9918 (setq cnt 0)
9919 (insert "\n"))
9920 (insert "{ "))
9921 ((equal e '(:endgroup))
9922 (setq ingroup nil cnt 0)
9923 (insert "}\n"))
9924 ((equal e '(:newline))
9925 (when (not (= cnt 0))
9926 (setq cnt 0)
9927 (insert "\n")
9928 (setq e (car tbl))
9929 (while (equal (car tbl) '(:newline))
9930 (insert "\n")
9931 (setq tbl (cdr tbl)))))
9933 (setq tg (car e) c (cdr e))
9934 (if ingroup (push tg (car groups)))
9935 (setq tg (org-add-props tg nil 'face
9936 (org-get-todo-face tg)))
9937 (if (and (= cnt 0) (not ingroup)) (insert " "))
9938 (insert "[" c "] " tg (make-string
9939 (- fwidth 4 (length tg)) ?\ ))
9940 (when (= (setq cnt (1+ cnt)) ncol)
9941 (insert "\n")
9942 (if ingroup (insert " "))
9943 (setq cnt 0)))))
9944 (insert "\n")
9945 (goto-char (point-min))
9946 (if (not expert) (org-fit-window-to-buffer))
9947 (message "[a-z..]:Set [SPC]:clear")
9948 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9949 (cond
9950 ((or (= c ?\C-g)
9951 (and (= c ?q) (not (rassoc c fulltable))))
9952 (setq quit-flag t))
9953 ((= c ?\ ) nil)
9954 ((setq e (rassoc c fulltable) tg (car e))
9956 (t (setq quit-flag t)))))))
9958 (defun org-entry-is-todo-p ()
9959 (member (org-get-todo-state) org-not-done-keywords))
9961 (defun org-entry-is-done-p ()
9962 (member (org-get-todo-state) org-done-keywords))
9964 (defun org-get-todo-state ()
9965 (save-excursion
9966 (org-back-to-heading t)
9967 (and (looking-at org-todo-line-regexp)
9968 (match-end 2)
9969 (match-string 2))))
9971 (defun org-at-date-range-p (&optional inactive-ok)
9972 "Is the cursor inside a date range?"
9973 (interactive)
9974 (save-excursion
9975 (catch 'exit
9976 (let ((pos (point)))
9977 (skip-chars-backward "^[<\r\n")
9978 (skip-chars-backward "<[")
9979 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9980 (>= (match-end 0) pos)
9981 (throw 'exit t))
9982 (skip-chars-backward "^<[\r\n")
9983 (skip-chars-backward "<[")
9984 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9985 (>= (match-end 0) pos)
9986 (throw 'exit t)))
9987 nil)))
9989 (defun org-get-repeat ()
9990 "Check if there is a deadline/schedule with repeater in this entry."
9991 (save-match-data
9992 (save-excursion
9993 (org-back-to-heading t)
9994 (if (re-search-forward
9995 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9996 (match-string 1)))))
9998 (defvar org-last-changed-timestamp)
9999 (defvar org-last-inserted-timestamp)
10000 (defvar org-log-post-message)
10001 (defvar org-log-note-purpose)
10002 (defvar org-log-note-how)
10003 (defvar org-log-note-extra)
10004 (defun org-auto-repeat-maybe (done-word)
10005 "Check if the current headline contains a repeated deadline/schedule.
10006 If yes, set TODO state back to what it was and change the base date
10007 of repeating deadline/scheduled time stamps to new date.
10008 This function is run automatically after each state change to a DONE state."
10009 ;; last-state is dynamically scoped into this function
10010 (let* ((repeat (org-get-repeat))
10011 (aa (assoc last-state org-todo-kwd-alist))
10012 (interpret (nth 1 aa))
10013 (head (nth 2 aa))
10014 (whata '(("d" . day) ("m" . month) ("y" . year)))
10015 (msg "Entry repeats: ")
10016 (org-log-done nil)
10017 (org-todo-log-states nil)
10018 (nshiftmax 10) (nshift 0)
10019 re type n what ts time)
10020 (when repeat
10021 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10022 (org-todo (if (eq interpret 'type) last-state head))
10023 (org-entry-put nil "LAST_REPEAT" (format-time-string
10024 (org-time-stamp-format t t)))
10025 (when org-log-repeat
10026 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10027 (memq 'org-add-log-note post-command-hook))
10028 ;; OK, we are already setup for some record
10029 (if (eq org-log-repeat 'note)
10030 ;; make sure we take a note, not only a time stamp
10031 (setq org-log-note-how 'note))
10032 ;; Set up for taking a record
10033 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10034 last-state
10035 'findpos org-log-repeat)))
10036 (org-back-to-heading t)
10037 (org-add-planning-info nil nil 'closed)
10038 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10039 org-deadline-time-regexp "\\)\\|\\("
10040 org-ts-regexp "\\)"))
10041 (while (re-search-forward
10042 re (save-excursion (outline-next-heading) (point)) t)
10043 (setq type (if (match-end 1) org-scheduled-string
10044 (if (match-end 3) org-deadline-string "Plain:"))
10045 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10046 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10047 (setq n (string-to-number (match-string 2 ts))
10048 what (match-string 3 ts))
10049 (if (equal what "w") (setq n (* n 7) what "d"))
10050 ;; Preparation, see if we need to modify the start date for the change
10051 (when (match-end 1)
10052 (setq time (save-match-data (org-time-string-to-time ts)))
10053 (cond
10054 ((equal (match-string 1 ts) ".")
10055 ;; Shift starting date to today
10056 (org-timestamp-change
10057 (- (time-to-days (current-time)) (time-to-days time))
10058 'day))
10059 ((equal (match-string 1 ts) "+")
10060 (while (or (= nshift 0)
10061 (<= (time-to-days time) (time-to-days (current-time))))
10062 (when (= (incf nshift) nshiftmax)
10063 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10064 (error "Abort")))
10065 (org-timestamp-change n (cdr (assoc what whata)))
10066 (org-at-timestamp-p t)
10067 (setq ts (match-string 1))
10068 (setq time (save-match-data (org-time-string-to-time ts))))
10069 (org-timestamp-change (- n) (cdr (assoc what whata)))
10070 ;; rematch, so that we have everything in place for the real shift
10071 (org-at-timestamp-p t)
10072 (setq ts (match-string 1))
10073 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10074 (org-timestamp-change n (cdr (assoc what whata)))
10075 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10076 (setq org-log-post-message msg)
10077 (message "%s" msg))))
10079 (defun org-show-todo-tree (arg)
10080 "Make a compact tree which shows all headlines marked with TODO.
10081 The tree will show the lines where the regexp matches, and all higher
10082 headlines above the match.
10083 With a \\[universal-argument] prefix, prompt for a regexp to match.
10084 With a numeric prefix N, construct a sparse tree for the Nth element
10085 of `org-todo-keywords-1'."
10086 (interactive "P")
10087 (let ((case-fold-search nil)
10088 (kwd-re
10089 (cond ((null arg) org-not-done-regexp)
10090 ((equal arg '(4))
10091 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10092 (mapcar 'list org-todo-keywords-1))))
10093 (concat "\\("
10094 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10095 "\\)\\>")))
10096 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10097 (regexp-quote (nth (1- (prefix-numeric-value arg))
10098 org-todo-keywords-1)))
10099 (t (error "Invalid prefix argument: %s" arg)))))
10100 (message "%d TODO entries found"
10101 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10103 (defun org-deadline (&optional remove time)
10104 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10105 With argument REMOVE, remove any deadline from the item.
10106 When TIME is set, it should be an internal time specification, and the
10107 scheduling will use the corresponding date."
10108 (interactive "P")
10109 (if remove
10110 (progn
10111 (org-remove-timestamp-with-keyword org-deadline-string)
10112 (message "Item no longer has a deadline."))
10113 (if (org-get-repeat)
10114 (error "Cannot change deadline on task with repeater, please do that by hand")
10115 (org-add-planning-info 'deadline time 'closed)
10116 (message "Deadline on %s" org-last-inserted-timestamp))))
10118 (defun org-schedule (&optional remove time)
10119 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10120 With argument REMOVE, remove any scheduling date from the item.
10121 When TIME is set, it should be an internal time specification, and the
10122 scheduling will use the corresponding date."
10123 (interactive "P")
10124 (if remove
10125 (progn
10126 (org-remove-timestamp-with-keyword org-scheduled-string)
10127 (message "Item is no longer scheduled."))
10128 (if (org-get-repeat)
10129 (error "Cannot reschedule task with repeater, please do that by hand")
10130 (org-add-planning-info 'scheduled time 'closed)
10131 (message "Scheduled to %s" org-last-inserted-timestamp))))
10133 (defun org-get-scheduled-time (pom &optional inherit)
10134 "Get the scheduled time as a time tuple, of a format suitable
10135 for calling org-schedule with, or if there is no scheduling,
10136 returns nil."
10137 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10138 (when time
10139 (apply 'encode-time (org-parse-time-string time)))))
10141 (defun org-get-deadline-time (pom &optional inherit)
10142 "Get the deadine as a time tuple, of a format suitable for
10143 calling org-deadlin with, or if there is no scheduling, returns
10144 nil."
10145 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10146 (when time
10147 (apply 'encode-time (org-parse-time-string time)))))
10149 (defun org-remove-timestamp-with-keyword (keyword)
10150 "Remove all time stamps with KEYWORD in the current entry."
10151 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10152 beg)
10153 (save-excursion
10154 (org-back-to-heading t)
10155 (setq beg (point))
10156 (outline-next-heading)
10157 (while (re-search-backward re beg t)
10158 (replace-match "")
10159 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10160 (equal (char-before) ?\ ))
10161 (backward-delete-char 1)
10162 (if (string-match "^[ \t]*$" (buffer-substring
10163 (point-at-bol) (point-at-eol)))
10164 (delete-region (point-at-bol)
10165 (min (point-max) (1+ (point-at-eol))))))))))
10167 (defun org-add-planning-info (what &optional time &rest remove)
10168 "Insert new timestamp with keyword in the line directly after the headline.
10169 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10170 If non is given, the user is prompted for a date.
10171 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10172 be removed."
10173 (interactive)
10174 (let (org-time-was-given org-end-time-was-given ts
10175 end default-time default-input)
10177 (catch 'exit
10178 (when (and (not time) (memq what '(scheduled deadline)))
10179 ;; Try to get a default date/time from existing timestamp
10180 (save-excursion
10181 (org-back-to-heading t)
10182 (setq end (save-excursion (outline-next-heading) (point)))
10183 (when (re-search-forward (if (eq what 'scheduled)
10184 org-scheduled-time-regexp
10185 org-deadline-time-regexp)
10186 end t)
10187 (setq ts (match-string 1)
10188 default-time
10189 (apply 'encode-time (org-parse-time-string ts))
10190 default-input (and ts (org-get-compact-tod ts))))))
10191 (when what
10192 ;; If necessary, get the time from the user
10193 (setq time (or time (org-read-date nil 'to-time nil nil
10194 default-time default-input))))
10196 (when (and org-insert-labeled-timestamps-at-point
10197 (member what '(scheduled deadline)))
10198 (insert
10199 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10200 (org-insert-time-stamp time org-time-was-given
10201 nil nil nil (list org-end-time-was-given))
10202 (setq what nil))
10203 (save-excursion
10204 (save-restriction
10205 (let (col list elt ts buffer-invisibility-spec)
10206 (org-back-to-heading t)
10207 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10208 (goto-char (match-end 1))
10209 (setq col (current-column))
10210 (goto-char (match-end 0))
10211 (if (eobp) (insert "\n") (forward-char 1))
10212 (when (and (not what)
10213 (not (looking-at
10214 (concat "[ \t]*"
10215 org-keyword-time-not-clock-regexp))))
10216 ;; Nothing to add, nothing to remove...... :-)
10217 (throw 'exit nil))
10218 (if (and (not (looking-at outline-regexp))
10219 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10220 "[^\r\n]*"))
10221 (not (equal (match-string 1) org-clock-string)))
10222 (narrow-to-region (match-beginning 0) (match-end 0))
10223 (insert-before-markers "\n")
10224 (backward-char 1)
10225 (narrow-to-region (point) (point))
10226 (and org-adapt-indentation (org-indent-to-column col)))
10227 ;; Check if we have to remove something.
10228 (setq list (cons what remove))
10229 (while list
10230 (setq elt (pop list))
10231 (goto-char (point-min))
10232 (when (or (and (eq elt 'scheduled)
10233 (re-search-forward org-scheduled-time-regexp nil t))
10234 (and (eq elt 'deadline)
10235 (re-search-forward org-deadline-time-regexp nil t))
10236 (and (eq elt 'closed)
10237 (re-search-forward org-closed-time-regexp nil t)))
10238 (replace-match "")
10239 (if (looking-at "--+<[^>]+>") (replace-match ""))
10240 (skip-chars-backward " ")
10241 (if (looking-at " +") (replace-match ""))))
10242 (goto-char (point-max))
10243 (when what
10244 (insert
10245 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10246 (cond ((eq what 'scheduled) org-scheduled-string)
10247 ((eq what 'deadline) org-deadline-string)
10248 ((eq what 'closed) org-closed-string))
10249 " ")
10250 (setq ts (org-insert-time-stamp
10251 time
10252 (or org-time-was-given
10253 (and (eq what 'closed) org-log-done-with-time))
10254 (eq what 'closed)
10255 nil nil (list org-end-time-was-given)))
10256 (end-of-line 1))
10257 (goto-char (point-min))
10258 (widen)
10259 (if (and (looking-at "[ \t]+\n")
10260 (equal (char-before) ?\n))
10261 (delete-region (1- (point)) (point-at-eol)))
10262 ts))))))
10264 (defvar org-log-note-marker (make-marker))
10265 (defvar org-log-note-purpose nil)
10266 (defvar org-log-note-state nil)
10267 (defvar org-log-note-previous-state nil)
10268 (defvar org-log-note-how nil)
10269 (defvar org-log-note-extra nil)
10270 (defvar org-log-note-window-configuration nil)
10271 (defvar org-log-note-return-to (make-marker))
10272 (defvar org-log-post-message nil
10273 "Message to be displayed after a log note has been stored.
10274 The auto-repeater uses this.")
10276 (defun org-add-note ()
10277 "Add a note to the current entry.
10278 This is done in the same way as adding a state change note."
10279 (interactive)
10280 (org-add-log-setup 'note nil nil 'findpos nil))
10282 (defvar org-property-end-re)
10283 (defun org-add-log-setup (&optional purpose state prev-state
10284 findpos how &optional extra)
10285 "Set up the post command hook to take a note.
10286 If this is about to TODO state change, the new state is expected in STATE.
10287 When FINDPOS is non-nil, find the correct position for the note in
10288 the current entry. If not, assume that it can be inserted at point.
10289 HOW is an indicator what kind of note should be created.
10290 EXTRA is additional text that will be inserted into the notes buffer."
10291 (let* ((org-log-into-drawer (org-log-into-drawer))
10292 (drawer (cond ((stringp org-log-into-drawer)
10293 org-log-into-drawer)
10294 (org-log-into-drawer "LOGBOOK")
10295 (t nil))))
10296 (save-restriction
10297 (save-excursion
10298 (when findpos
10299 (org-back-to-heading t)
10300 (narrow-to-region (point) (save-excursion
10301 (outline-next-heading) (point)))
10302 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10303 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10304 "[^\r\n]*\\)?"))
10305 (goto-char (match-end 0))
10306 (cond
10307 (drawer
10308 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10309 nil t)
10310 (progn
10311 (goto-char (match-end 0))
10312 (or org-log-states-order-reversed
10313 (and (re-search-forward org-property-end-re nil t)
10314 (goto-char (1- (match-beginning 0))))))
10315 (insert "\n:" drawer ":\n:END:")
10316 (beginning-of-line 0)
10317 (org-indent-line-function)
10318 (beginning-of-line 2)
10319 (org-indent-line-function)
10320 (end-of-line 0)))
10321 ((and org-log-state-notes-insert-after-drawers
10322 (save-excursion
10323 (forward-line) (looking-at org-drawer-regexp)))
10324 (forward-line)
10325 (while (looking-at org-drawer-regexp)
10326 (goto-char (match-end 0))
10327 (re-search-forward org-property-end-re (point-max) t)
10328 (forward-line))
10329 (forward-line -1)))
10330 (unless org-log-states-order-reversed
10331 (and (= (char-after) ?\n) (forward-char 1))
10332 (org-skip-over-state-notes)
10333 (skip-chars-backward " \t\n\r")))
10334 (move-marker org-log-note-marker (point))
10335 (setq org-log-note-purpose purpose
10336 org-log-note-state state
10337 org-log-note-previous-state prev-state
10338 org-log-note-how how
10339 org-log-note-extra extra)
10340 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10342 (defun org-skip-over-state-notes ()
10343 "Skip past the list of State notes in an entry."
10344 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10345 (while (looking-at "[ \t]*- State")
10346 (condition-case nil
10347 (org-next-item)
10348 (error (org-end-of-item)))))
10350 (defun org-add-log-note (&optional purpose)
10351 "Pop up a window for taking a note, and add this note later at point."
10352 (remove-hook 'post-command-hook 'org-add-log-note)
10353 (setq org-log-note-window-configuration (current-window-configuration))
10354 (delete-other-windows)
10355 (move-marker org-log-note-return-to (point))
10356 (switch-to-buffer (marker-buffer org-log-note-marker))
10357 (goto-char org-log-note-marker)
10358 (org-switch-to-buffer-other-window "*Org Note*")
10359 (erase-buffer)
10360 (if (memq org-log-note-how '(time state))
10361 (let (current-prefix-arg) (org-store-log-note))
10362 (let ((org-inhibit-startup t)) (org-mode))
10363 (insert (format "# Insert note for %s.
10364 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10365 (cond
10366 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10367 ((eq org-log-note-purpose 'done) "closed todo item")
10368 ((eq org-log-note-purpose 'state)
10369 (format "state change from \"%s\" to \"%s\""
10370 (or org-log-note-previous-state "")
10371 (or org-log-note-state "")))
10372 ((eq org-log-note-purpose 'note)
10373 "this entry")
10374 (t (error "This should not happen")))))
10375 (if org-log-note-extra (insert org-log-note-extra))
10376 (org-set-local 'org-finish-function 'org-store-log-note)))
10378 (defvar org-note-abort nil) ; dynamically scoped
10379 (defun org-store-log-note ()
10380 "Finish taking a log note, and insert it to where it belongs."
10381 (let ((txt (buffer-string))
10382 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10383 lines ind)
10384 (kill-buffer (current-buffer))
10385 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10386 (setq txt (replace-match "" t t txt)))
10387 (if (string-match "\\s-+\\'" txt)
10388 (setq txt (replace-match "" t t txt)))
10389 (setq lines (org-split-string txt "\n"))
10390 (when (and note (string-match "\\S-" note))
10391 (setq note
10392 (org-replace-escapes
10393 note
10394 (list (cons "%u" (user-login-name))
10395 (cons "%U" user-full-name)
10396 (cons "%t" (format-time-string
10397 (org-time-stamp-format 'long 'inactive)
10398 (current-time)))
10399 (cons "%s" (if org-log-note-state
10400 (concat "\"" org-log-note-state "\"")
10401 ""))
10402 (cons "%S" (if org-log-note-previous-state
10403 (concat "\"" org-log-note-previous-state "\"")
10404 "\"\"")))))
10405 (if lines (setq note (concat note " \\\\")))
10406 (push note lines))
10407 (when (or current-prefix-arg org-note-abort)
10408 (when org-log-into-drawer
10409 (org-remove-empty-drawer-at
10410 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10411 org-log-note-marker))
10412 (setq lines nil))
10413 (when lines
10414 (save-excursion
10415 (set-buffer (marker-buffer org-log-note-marker))
10416 (save-excursion
10417 (goto-char org-log-note-marker)
10418 (move-marker org-log-note-marker nil)
10419 (end-of-line 1)
10420 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10421 (insert "- " (pop lines))
10422 (org-indent-line-function)
10423 (beginning-of-line 1)
10424 (looking-at "[ \t]*")
10425 (setq ind (concat (match-string 0) " "))
10426 (end-of-line 1)
10427 (while lines (insert "\n" ind (pop lines)))
10428 (message "Note stored")
10429 (org-back-to-heading t)
10430 (org-cycle-hide-drawers 'children)))))
10431 (set-window-configuration org-log-note-window-configuration)
10432 (with-current-buffer (marker-buffer org-log-note-return-to)
10433 (goto-char org-log-note-return-to))
10434 (move-marker org-log-note-return-to nil)
10435 (and org-log-post-message (message "%s" org-log-post-message)))
10437 (defun org-remove-empty-drawer-at (drawer pos)
10438 "Remove an emptyr DARWER drawer at position POS.
10439 POS may also be a marker."
10440 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10441 (save-excursion
10442 (save-restriction
10443 (widen)
10444 (goto-char pos)
10445 (if (org-in-regexp
10446 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10447 (replace-match ""))))))
10449 (defun org-sparse-tree (&optional arg)
10450 "Create a sparse tree, prompt for the details.
10451 This command can create sparse trees. You first need to select the type
10452 of match used to create the tree:
10454 t Show entries with a specific TODO keyword.
10455 m Show entries selected by a tags/property match.
10456 p Enter a property name and its value (both with completion on existing
10457 names/values) and show entries with that property.
10458 r Show entries matching a regular expression.
10459 d Show deadlines due within `org-deadline-warning-days'.
10460 b Show deadlines and scheduled items before a date.
10461 a Show deadlines and scheduled items after a date."
10462 (interactive "P")
10463 (let (ans kwd value)
10464 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10465 (setq ans (read-char-exclusive))
10466 (cond
10467 ((equal ans ?d)
10468 (call-interactively 'org-check-deadlines))
10469 ((equal ans ?b)
10470 (call-interactively 'org-check-before-date))
10471 ((equal ans ?a)
10472 (call-interactively 'org-check-after-date))
10473 ((equal ans ?t)
10474 (org-show-todo-tree '(4)))
10475 ((member ans '(?T ?m))
10476 (call-interactively 'org-match-sparse-tree))
10477 ((member ans '(?p ?P))
10478 (setq kwd (org-icompleting-read "Property: "
10479 (mapcar 'list (org-buffer-property-keys))))
10480 (setq value (org-icompleting-read "Value: "
10481 (mapcar 'list (org-property-values kwd))))
10482 (unless (string-match "\\`{.*}\\'" value)
10483 (setq value (concat "\"" value "\"")))
10484 (org-match-sparse-tree arg (concat kwd "=" value)))
10485 ((member ans '(?r ?R ?/))
10486 (call-interactively 'org-occur))
10487 (t (error "No such sparse tree command \"%c\"" ans)))))
10489 (defvar org-occur-highlights nil
10490 "List of overlays used for occur matches.")
10491 (make-variable-buffer-local 'org-occur-highlights)
10492 (defvar org-occur-parameters nil
10493 "Parameters of the active org-occur calls.
10494 This is a list, each call to org-occur pushes as cons cell,
10495 containing the regular expression and the callback, onto the list.
10496 The list can contain several entries if `org-occur' has been called
10497 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10498 will only contain one set of parameters. When the highlights are
10499 removed (for example with `C-c C-c', or with the next edit (depending
10500 on `org-remove-highlights-with-change'), this variable is emptied
10501 as well.")
10502 (make-variable-buffer-local 'org-occur-parameters)
10504 (defun org-occur (regexp &optional keep-previous callback)
10505 "Make a compact tree which shows all matches of REGEXP.
10506 The tree will show the lines where the regexp matches, and all higher
10507 headlines above the match. It will also show the heading after the match,
10508 to make sure editing the matching entry is easy.
10509 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10510 call to `org-occur' will be kept, to allow stacking of calls to this
10511 command.
10512 If CALLBACK is non-nil, it is a function which is called to confirm
10513 that the match should indeed be shown."
10514 (interactive "sRegexp: \nP")
10515 (when (equal regexp "")
10516 (error "Regexp cannot be empty"))
10517 (unless keep-previous
10518 (org-remove-occur-highlights nil nil t))
10519 (push (cons regexp callback) org-occur-parameters)
10520 (let ((cnt 0))
10521 (save-excursion
10522 (goto-char (point-min))
10523 (if (or (not keep-previous) ; do not want to keep
10524 (not org-occur-highlights)) ; no previous matches
10525 ;; hide everything
10526 (org-overview))
10527 (while (re-search-forward regexp nil t)
10528 (when (or (not callback)
10529 (save-match-data (funcall callback)))
10530 (setq cnt (1+ cnt))
10531 (when org-highlight-sparse-tree-matches
10532 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10533 (org-show-context 'occur-tree))))
10534 (when org-remove-highlights-with-change
10535 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10536 nil 'local))
10537 (unless org-sparse-tree-open-archived-trees
10538 (org-hide-archived-subtrees (point-min) (point-max)))
10539 (run-hooks 'org-occur-hook)
10540 (if (interactive-p)
10541 (message "%d match(es) for regexp %s" cnt regexp))
10542 cnt))
10544 (defun org-show-context (&optional key)
10545 "Make sure point and context and visible.
10546 How much context is shown depends upon the variables
10547 `org-show-hierarchy-above', `org-show-following-heading'. and
10548 `org-show-siblings'."
10549 (let ((heading-p (org-on-heading-p t))
10550 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10551 (following-p (org-get-alist-option org-show-following-heading key))
10552 (entry-p (org-get-alist-option org-show-entry-below key))
10553 (siblings-p (org-get-alist-option org-show-siblings key)))
10554 (catch 'exit
10555 ;; Show heading or entry text
10556 (if (and heading-p (not entry-p))
10557 (org-flag-heading nil) ; only show the heading
10558 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10559 (org-show-hidden-entry))) ; show entire entry
10560 (when following-p
10561 ;; Show next sibling, or heading below text
10562 (save-excursion
10563 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10564 (org-flag-heading nil))))
10565 (when siblings-p (org-show-siblings))
10566 (when hierarchy-p
10567 ;; show all higher headings, possibly with siblings
10568 (save-excursion
10569 (while (and (condition-case nil
10570 (progn (org-up-heading-all 1) t)
10571 (error nil))
10572 (not (bobp)))
10573 (org-flag-heading nil)
10574 (when siblings-p (org-show-siblings))))))))
10576 (defun org-reveal (&optional siblings)
10577 "Show current entry, hierarchy above it, and the following headline.
10578 This can be used to show a consistent set of context around locations
10579 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10580 not t for the search context.
10582 With optional argument SIBLINGS, on each level of the hierarchy all
10583 siblings are shown. This repairs the tree structure to what it would
10584 look like when opened with hierarchical calls to `org-cycle'."
10585 (interactive "P")
10586 (let ((org-show-hierarchy-above t)
10587 (org-show-following-heading t)
10588 (org-show-siblings (if siblings t org-show-siblings)))
10589 (org-show-context nil)))
10591 (defun org-highlight-new-match (beg end)
10592 "Highlight from BEG to END and mark the highlight is an occur headline."
10593 (let ((ov (org-make-overlay beg end)))
10594 (org-overlay-put ov 'face 'secondary-selection)
10595 (push ov org-occur-highlights)))
10597 (defun org-remove-occur-highlights (&optional beg end noremove)
10598 "Remove the occur highlights from the buffer.
10599 BEG and END are ignored. If NOREMOVE is nil, remove this function
10600 from the `before-change-functions' in the current buffer."
10601 (interactive)
10602 (unless org-inhibit-highlight-removal
10603 (mapc 'org-delete-overlay org-occur-highlights)
10604 (setq org-occur-highlights nil)
10605 (setq org-occur-parameters nil)
10606 (unless noremove
10607 (remove-hook 'before-change-functions
10608 'org-remove-occur-highlights 'local))))
10610 ;;;; Priorities
10612 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10613 "Regular expression matching the priority indicator.")
10615 (defvar org-remove-priority-next-time nil)
10617 (defun org-priority-up ()
10618 "Increase the priority of the current item."
10619 (interactive)
10620 (org-priority 'up))
10622 (defun org-priority-down ()
10623 "Decrease the priority of the current item."
10624 (interactive)
10625 (org-priority 'down))
10627 (defun org-priority (&optional action)
10628 "Change the priority of an item by ARG.
10629 ACTION can be `set', `up', `down', or a character."
10630 (interactive)
10631 (unless org-enable-priority-commands
10632 (error "Priority commands are disabled"))
10633 (setq action (or action 'set))
10634 (let (current new news have remove)
10635 (save-excursion
10636 (org-back-to-heading t)
10637 (if (looking-at org-priority-regexp)
10638 (setq current (string-to-char (match-string 2))
10639 have t)
10640 (setq current org-default-priority))
10641 (cond
10642 ((or (eq action 'set)
10643 (if (featurep 'xemacs) (characterp action) (integerp action)))
10644 (if (not (eq action 'set))
10645 (setq new action)
10646 (message "Priority %c-%c, SPC to remove: "
10647 org-highest-priority org-lowest-priority)
10648 (setq new (read-char-exclusive)))
10649 (if (and (= (upcase org-highest-priority) org-highest-priority)
10650 (= (upcase org-lowest-priority) org-lowest-priority))
10651 (setq new (upcase new)))
10652 (cond ((equal new ?\ ) (setq remove t))
10653 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10654 (error "Priority must be between `%c' and `%c'"
10655 org-highest-priority org-lowest-priority))))
10656 ((eq action 'up)
10657 (if (and (not have) (eq last-command this-command))
10658 (setq new org-lowest-priority)
10659 (setq new (if (and org-priority-start-cycle-with-default (not have))
10660 org-default-priority (1- current)))))
10661 ((eq action 'down)
10662 (if (and (not have) (eq last-command this-command))
10663 (setq new org-highest-priority)
10664 (setq new (if (and org-priority-start-cycle-with-default (not have))
10665 org-default-priority (1+ current)))))
10666 (t (error "Invalid action")))
10667 (if (or (< (upcase new) org-highest-priority)
10668 (> (upcase new) org-lowest-priority))
10669 (setq remove t))
10670 (setq news (format "%c" new))
10671 (if have
10672 (if remove
10673 (replace-match "" t t nil 1)
10674 (replace-match news t t nil 2))
10675 (if remove
10676 (error "No priority cookie found in line")
10677 (let ((case-fold-search nil))
10678 (looking-at org-todo-line-regexp))
10679 (if (match-end 2)
10680 (progn
10681 (goto-char (match-end 2))
10682 (insert " [#" news "]"))
10683 (goto-char (match-beginning 3))
10684 (insert "[#" news "] "))))
10685 (org-preserve-lc (org-set-tags nil 'align)))
10686 (if remove
10687 (message "Priority removed")
10688 (message "Priority of current item set to %s" news))))
10690 (defun org-get-priority (s)
10691 "Find priority cookie and return priority."
10692 (save-match-data
10693 (if (not (string-match org-priority-regexp s))
10694 (* 1000 (- org-lowest-priority org-default-priority))
10695 (* 1000 (- org-lowest-priority
10696 (string-to-char (match-string 2 s)))))))
10698 ;;;; Tags
10700 (defvar org-agenda-archives-mode)
10701 (defvar org-map-continue-from nil
10702 "Position from where mapping should continue.
10703 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10705 (defvar org-scanner-tags nil
10706 "The current tag list while the tags scanner is running.")
10707 (defvar org-trust-scanner-tags nil
10708 "Should `org-get-tags-at' use the tags fro the scanner.
10709 This is for internal dynamical scoping only.
10710 When this is non-nil, the function `org-get-tags-at' will return the value
10711 of `org-scanner-tags' instead of building the list by itself. This
10712 can lead to large speed-ups when the tags scanner is used in a file with
10713 many entries, and when the list of tags is retrieved, for example to
10714 obtain a list of properties. Building the tags list for each entry in such
10715 a file becomes an N^2 operation - but with this variable set, it scales
10716 as N.")
10718 (defun org-scan-tags (action matcher &optional todo-only)
10719 "Scan headline tags with inheritance and produce output ACTION.
10721 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10722 or `agenda' to produce an entry list for an agenda view. It can also be
10723 a Lisp form or a function that should be called at each matched headline, in
10724 this case the return value is a list of all return values from these calls.
10726 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10727 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10728 only lines with a TODO keyword are included in the output."
10729 (require 'org-agenda)
10730 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10731 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10732 (org-re
10733 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10734 (props (list 'face 'default
10735 'done-face 'org-agenda-done
10736 'undone-face 'default
10737 'mouse-face 'highlight
10738 'org-not-done-regexp org-not-done-regexp
10739 'org-todo-regexp org-todo-regexp
10740 'keymap org-agenda-keymap
10741 'help-echo
10742 (format "mouse-2 or RET jump to org file %s"
10743 (abbreviate-file-name
10744 (or (buffer-file-name (buffer-base-buffer))
10745 (buffer-name (buffer-base-buffer)))))))
10746 (case-fold-search nil)
10747 (org-map-continue-from nil)
10748 lspos tags tags-list
10749 (tags-alist (list (cons 0 org-file-tags)))
10750 (llast 0) rtn rtn1 level category i txt
10751 todo marker entry priority)
10752 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10753 (setq action (list 'lambda nil action)))
10754 (save-excursion
10755 (goto-char (point-min))
10756 (when (eq action 'sparse-tree)
10757 (org-overview)
10758 (org-remove-occur-highlights))
10759 (while (re-search-forward re nil t)
10760 (catch :skip
10761 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10762 tags (if (match-end 4) (org-match-string-no-properties 4)))
10763 (goto-char (setq lspos (match-beginning 0)))
10764 (setq level (org-reduced-level (funcall outline-level))
10765 category (org-get-category))
10766 (setq i llast llast level)
10767 ;; remove tag lists from same and sublevels
10768 (while (>= i level)
10769 (when (setq entry (assoc i tags-alist))
10770 (setq tags-alist (delete entry tags-alist)))
10771 (setq i (1- i)))
10772 ;; add the next tags
10773 (when tags
10774 (setq tags (org-split-string tags ":")
10775 tags-alist
10776 (cons (cons level tags) tags-alist)))
10777 ;; compile tags for current headline
10778 (setq tags-list
10779 (if org-use-tag-inheritance
10780 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10781 tags)
10782 org-scanner-tags tags-list)
10783 (when org-use-tag-inheritance
10784 (setcdr (car tags-alist)
10785 (mapcar (lambda (x)
10786 (setq x (copy-sequence x))
10787 (org-add-prop-inherited x))
10788 (cdar tags-alist))))
10789 (when (and tags org-use-tag-inheritance
10790 (or (not (eq t org-use-tag-inheritance))
10791 org-tags-exclude-from-inheritance))
10792 ;; selective inheritance, remove uninherited ones
10793 (setcdr (car tags-alist)
10794 (org-remove-uniherited-tags (cdar tags-alist))))
10795 (when (and (or (not todo-only)
10796 (and (member todo org-not-done-keywords)
10797 (or (not org-agenda-tags-todo-honor-ignore-options)
10798 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10799 (let ((case-fold-search t)) (eval matcher))
10801 (not (member org-archive-tag tags-list))
10802 ;; we have an archive tag, should we use this anyway?
10803 (or (not org-agenda-skip-archived-trees)
10804 (and (eq action 'agenda) org-agenda-archives-mode))))
10805 (unless (eq action 'sparse-tree) (org-agenda-skip))
10807 ;; select this headline
10809 (cond
10810 ((eq action 'sparse-tree)
10811 (and org-highlight-sparse-tree-matches
10812 (org-get-heading) (match-end 0)
10813 (org-highlight-new-match
10814 (match-beginning 0) (match-beginning 1)))
10815 (org-show-context 'tags-tree))
10816 ((eq action 'agenda)
10817 (setq txt (org-format-agenda-item
10819 (concat
10820 (if (eq org-tags-match-list-sublevels 'indented)
10821 (make-string (1- level) ?.) "")
10822 (org-get-heading))
10823 category
10824 tags-list
10826 priority (org-get-priority txt))
10827 (goto-char lspos)
10828 (setq marker (org-agenda-new-marker))
10829 (org-add-props txt props
10830 'org-marker marker 'org-hd-marker marker 'org-category category
10831 'todo-state todo
10832 'priority priority 'type "tagsmatch")
10833 (push txt rtn))
10834 ((functionp action)
10835 (setq org-map-continue-from nil)
10836 (save-excursion
10837 (setq rtn1 (funcall action))
10838 (push rtn1 rtn)))
10839 (t (error "Invalid action")))
10841 ;; if we are to skip sublevels, jump to end of subtree
10842 (unless org-tags-match-list-sublevels
10843 (org-end-of-subtree t)
10844 (backward-char 1))))
10845 ;; Get the correct position from where to continue
10846 (if org-map-continue-from
10847 (goto-char org-map-continue-from)
10848 (and (= (point) lspos) (end-of-line 1)))))
10849 (when (and (eq action 'sparse-tree)
10850 (not org-sparse-tree-open-archived-trees))
10851 (org-hide-archived-subtrees (point-min) (point-max)))
10852 (nreverse rtn)))
10854 (defun org-remove-uniherited-tags (tags)
10855 "Remove all tags that are not inherited from the list TAGS."
10856 (cond
10857 ((eq org-use-tag-inheritance t)
10858 (if org-tags-exclude-from-inheritance
10859 (org-delete-all org-tags-exclude-from-inheritance tags)
10860 tags))
10861 ((not org-use-tag-inheritance) nil)
10862 ((stringp org-use-tag-inheritance)
10863 (delq nil (mapcar
10864 (lambda (x)
10865 (if (and (string-match org-use-tag-inheritance x)
10866 (not (member x org-tags-exclude-from-inheritance)))
10867 x nil))
10868 tags)))
10869 ((listp org-use-tag-inheritance)
10870 (delq nil (mapcar
10871 (lambda (x)
10872 (if (member x org-use-tag-inheritance) x nil))
10873 tags)))))
10875 (defvar todo-only) ;; dynamically scoped
10877 (defun org-match-sparse-tree (&optional todo-only match)
10878 "Create a sparse tree according to tags string MATCH.
10879 MATCH can contain positive and negative selection of tags, like
10880 \"+WORK+URGENT-WITHBOSS\".
10881 If optional argument TODO-ONLY is non-nil, only select lines that are
10882 also TODO lines."
10883 (interactive "P")
10884 (org-prepare-agenda-buffers (list (current-buffer)))
10885 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10887 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10889 (defvar org-cached-props nil)
10890 (defun org-cached-entry-get (pom property)
10891 (if (or (eq t org-use-property-inheritance)
10892 (and (stringp org-use-property-inheritance)
10893 (string-match org-use-property-inheritance property))
10894 (and (listp org-use-property-inheritance)
10895 (member property org-use-property-inheritance)))
10896 ;; Caching is not possible, check it directly
10897 (org-entry-get pom property 'inherit)
10898 ;; Get all properties, so that we can do complicated checks easily
10899 (cdr (assoc property (or org-cached-props
10900 (setq org-cached-props
10901 (org-entry-properties pom)))))))
10903 (defun org-global-tags-completion-table (&optional files)
10904 "Return the list of all tags in all agenda buffer/files."
10905 (save-excursion
10906 (org-uniquify
10907 (delq nil
10908 (apply 'append
10909 (mapcar
10910 (lambda (file)
10911 (set-buffer (find-file-noselect file))
10912 (append (org-get-buffer-tags)
10913 (mapcar (lambda (x) (if (stringp (car-safe x))
10914 (list (car-safe x)) nil))
10915 org-tag-alist)))
10916 (if (and files (car files))
10917 files
10918 (org-agenda-files))))))))
10920 (defun org-make-tags-matcher (match)
10921 "Create the TAGS//TODO matcher form for the selection string MATCH."
10922 ;; todo-only is scoped dynamically into this function, and the function
10923 ;; may change it if the matcher asks for it.
10924 (unless match
10925 ;; Get a new match request, with completion
10926 (let ((org-last-tags-completion-table
10927 (org-global-tags-completion-table)))
10928 (setq match (org-completing-read-no-i
10929 "Match: " 'org-tags-completion-function nil nil nil
10930 'org-tags-history))))
10932 ;; Parse the string and create a lisp form
10933 (let ((match0 match)
10934 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10935 minus tag mm
10936 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10937 orterms term orlist re-p str-p level-p level-op time-p
10938 prop-p pn pv po cat-p gv rest)
10939 (if (string-match "/+" match)
10940 ;; match contains also a todo-matching request
10941 (progn
10942 (setq tagsmatch (substring match 0 (match-beginning 0))
10943 todomatch (substring match (match-end 0)))
10944 (if (string-match "^!" todomatch)
10945 (setq todo-only t todomatch (substring todomatch 1)))
10946 (if (string-match "^\\s-*$" todomatch)
10947 (setq todomatch nil)))
10948 ;; only matching tags
10949 (setq tagsmatch match todomatch nil))
10951 ;; Make the tags matcher
10952 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10953 (setq tagsmatcher t)
10954 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10955 (while (setq term (pop orterms))
10956 (while (and (equal (substring term -1) "\\") orterms)
10957 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10958 (while (string-match re term)
10959 (setq rest (substring term (match-end 0))
10960 minus (and (match-end 1)
10961 (equal (match-string 1 term) "-"))
10962 tag (match-string 2 term)
10963 re-p (equal (string-to-char tag) ?{)
10964 level-p (match-end 4)
10965 prop-p (match-end 5)
10966 mm (cond
10967 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10968 (level-p
10969 (setq level-op (org-op-to-function (match-string 3 term)))
10970 `(,level-op level ,(string-to-number
10971 (match-string 4 term))))
10972 (prop-p
10973 (setq pn (match-string 5 term)
10974 po (match-string 6 term)
10975 pv (match-string 7 term)
10976 cat-p (equal pn "CATEGORY")
10977 re-p (equal (string-to-char pv) ?{)
10978 str-p (equal (string-to-char pv) ?\")
10979 time-p (save-match-data
10980 (string-match "^\"[[<].*[]>]\"$" pv))
10981 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10982 (if time-p (setq pv (org-matcher-time pv)))
10983 (setq po (org-op-to-function po (if time-p 'time str-p)))
10984 (cond
10985 ((equal pn "CATEGORY")
10986 (setq gv '(get-text-property (point) 'org-category)))
10987 ((equal pn "TODO")
10988 (setq gv 'todo))
10990 (setq gv `(org-cached-entry-get nil ,pn))))
10991 (if re-p
10992 (if (eq po 'org<>)
10993 `(not (string-match ,pv (or ,gv "")))
10994 `(string-match ,pv (or ,gv "")))
10995 (if str-p
10996 `(,po (or ,gv "") ,pv)
10997 `(,po (string-to-number (or ,gv ""))
10998 ,(string-to-number pv) ))))
10999 (t `(member ,tag tags-list)))
11000 mm (if minus (list 'not mm) mm)
11001 term rest)
11002 (push mm tagsmatcher))
11003 (push (if (> (length tagsmatcher) 1)
11004 (cons 'and tagsmatcher)
11005 (car tagsmatcher))
11006 orlist)
11007 (setq tagsmatcher nil))
11008 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11009 (setq tagsmatcher
11010 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11011 ;; Make the todo matcher
11012 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11013 (setq todomatcher t)
11014 (setq orterms (org-split-string todomatch "|") orlist nil)
11015 (while (setq term (pop orterms))
11016 (while (string-match re term)
11017 (setq minus (and (match-end 1)
11018 (equal (match-string 1 term) "-"))
11019 kwd (match-string 2 term)
11020 re-p (equal (string-to-char kwd) ?{)
11021 term (substring term (match-end 0))
11022 mm (if re-p
11023 `(string-match ,(substring kwd 1 -1) todo)
11024 (list 'equal 'todo kwd))
11025 mm (if minus (list 'not mm) mm))
11026 (push mm todomatcher))
11027 (push (if (> (length todomatcher) 1)
11028 (cons 'and todomatcher)
11029 (car todomatcher))
11030 orlist)
11031 (setq todomatcher nil))
11032 (setq todomatcher (if (> (length orlist) 1)
11033 (cons 'or orlist) (car orlist))))
11035 ;; Return the string and lisp forms of the matcher
11036 (setq matcher (if todomatcher
11037 (list 'and tagsmatcher todomatcher)
11038 tagsmatcher))
11039 (cons match0 matcher)))
11041 (defun org-op-to-function (op &optional stringp)
11042 "Turn an operator into the appropriate function."
11043 (setq op
11044 (cond
11045 ((equal op "<" ) '(< string< org-time<))
11046 ((equal op ">" ) '(> org-string> org-time>))
11047 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11048 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11049 ((member op '("=" "==")) '(= string= org-time=))
11050 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11051 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11053 (defun org<> (a b) (not (= a b)))
11054 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11055 (defun org-string>= (a b) (not (string< a b)))
11056 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11057 (defun org-string<> (a b) (not (string= a b)))
11058 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11059 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11060 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11061 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11062 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11063 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11064 (defun org-2ft (s)
11065 "Convert S to a floating point time.
11066 If S is already a number, just return it. If it is a string, parse
11067 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11068 (cond
11069 ((numberp s) s)
11070 ((stringp s)
11071 (condition-case nil
11072 (float-time (apply 'encode-time (org-parse-time-string s)))
11073 (error 0.)))
11074 (t 0.)))
11076 (defun org-time-today ()
11077 "Time in seconds today at 0:00.
11078 Returns the float number of seconds since the beginning of the
11079 epoch to the beginning of today (00:00)."
11080 (float-time (apply 'encode-time
11081 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11083 (defun org-matcher-time (s)
11084 "Interpret a time comparison value."
11085 (save-match-data
11086 (cond
11087 ((string= s "<now>") (float-time))
11088 ((string= s "<today>") (org-time-today))
11089 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11090 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11091 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11092 (+ (org-time-today)
11093 (* (string-to-number (match-string 1 s))
11094 (cdr (assoc (match-string 2 s)
11095 '(("d" . 86400.0) ("w" . 604800.0)
11096 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11097 (t (org-2ft s)))))
11099 (defun org-match-any-p (re list)
11100 "Does re match any element of list?"
11101 (setq list (mapcar (lambda (x) (string-match re x)) list))
11102 (delq nil list))
11104 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11105 (defvar org-tags-overlay (org-make-overlay 1 1))
11106 (org-detach-overlay org-tags-overlay)
11108 (defun org-get-local-tags-at (&optional pos)
11109 "Get a list of tags defined in the current headline."
11110 (org-get-tags-at pos 'local))
11112 (defun org-get-local-tags ()
11113 "Get a list of tags defined in the current headline."
11114 (org-get-tags-at nil 'local))
11116 (defun org-get-tags-at (&optional pos local)
11117 "Get a list of all headline tags applicable at POS.
11118 POS defaults to point. If tags are inherited, the list contains
11119 the targets in the same sequence as the headlines appear, i.e.
11120 the tags of the current headline come last.
11121 When LOCAL is non-nil, only return tags from the current headline,
11122 ignore inherited ones."
11123 (interactive)
11124 (if (and org-trust-scanner-tags
11125 (or (not pos) (equal pos (point)))
11126 (not local))
11127 org-scanner-tags
11128 (let (tags ltags lastpos parent)
11129 (save-excursion
11130 (save-restriction
11131 (widen)
11132 (goto-char (or pos (point)))
11133 (save-match-data
11134 (catch 'done
11135 (condition-case nil
11136 (progn
11137 (org-back-to-heading t)
11138 (while (not (equal lastpos (point)))
11139 (setq lastpos (point))
11140 (when (looking-at
11141 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11142 (setq ltags (org-split-string
11143 (org-match-string-no-properties 1) ":"))
11144 (when parent
11145 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11146 (setq tags (append
11147 (if parent
11148 (org-remove-uniherited-tags ltags)
11149 ltags)
11150 tags)))
11151 (or org-use-tag-inheritance (throw 'done t))
11152 (if local (throw 'done t))
11153 (or (org-up-heading-safe) (error nil))
11154 (setq parent t)))
11155 (error nil)))))
11156 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11158 (defun org-add-prop-inherited (s)
11159 (add-text-properties 0 (length s) '(inherited t) s)
11162 (defun org-toggle-tag (tag &optional onoff)
11163 "Toggle the tag TAG for the current line.
11164 If ONOFF is `on' or `off', don't toggle but set to this state."
11165 (let (res current)
11166 (save-excursion
11167 (org-back-to-heading t)
11168 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11169 (point-at-eol) t)
11170 (progn
11171 (setq current (match-string 1))
11172 (replace-match ""))
11173 (setq current ""))
11174 (setq current (nreverse (org-split-string current ":")))
11175 (cond
11176 ((eq onoff 'on)
11177 (setq res t)
11178 (or (member tag current) (push tag current)))
11179 ((eq onoff 'off)
11180 (or (not (member tag current)) (setq current (delete tag current))))
11181 (t (if (member tag current)
11182 (setq current (delete tag current))
11183 (setq res t)
11184 (push tag current))))
11185 (end-of-line 1)
11186 (if current
11187 (progn
11188 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11189 (org-set-tags nil t))
11190 (delete-horizontal-space))
11191 (run-hooks 'org-after-tags-change-hook))
11192 res))
11194 (defun org-align-tags-here (to-col)
11195 ;; Assumes that this is a headline
11196 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11197 (beginning-of-line 1)
11198 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11199 (< pos (match-beginning 2)))
11200 (progn
11201 (setq tags-l (- (match-end 2) (match-beginning 2)))
11202 (goto-char (match-beginning 1))
11203 (insert " ")
11204 (delete-region (point) (1+ (match-beginning 2)))
11205 (setq ncol (max (1+ (current-column))
11206 (1+ col)
11207 (if (> to-col 0)
11208 to-col
11209 (- (abs to-col) tags-l))))
11210 (setq p (point))
11211 (insert (make-string (- ncol (current-column)) ?\ ))
11212 (setq ncol (current-column))
11213 (when indent-tabs-mode (tabify p (point-at-eol)))
11214 (org-move-to-column (min ncol col) t))
11215 (goto-char pos))))
11217 (defun org-set-tags-command (&optional arg just-align)
11218 "Call the set-tags command for the current entry."
11219 (interactive "P")
11220 (if (org-on-heading-p)
11221 (org-set-tags arg just-align)
11222 (save-excursion
11223 (org-back-to-heading t)
11224 (org-set-tags arg just-align))))
11226 (defun org-set-tags (&optional arg just-align)
11227 "Set the tags for the current headline.
11228 With prefix ARG, realign all tags in headings in the current buffer."
11229 (interactive "P")
11230 (let* ((re (concat "^" outline-regexp))
11231 (current (org-get-tags-string))
11232 (col (current-column))
11233 (org-setting-tags t)
11234 table current-tags inherited-tags ; computed below when needed
11235 tags p0 c0 c1 rpl)
11236 (if arg
11237 (save-excursion
11238 (goto-char (point-min))
11239 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11240 (while (re-search-forward re nil t)
11241 (org-set-tags nil t)
11242 (end-of-line 1)))
11243 (message "All tags realigned to column %d" org-tags-column))
11244 (if just-align
11245 (setq tags current)
11246 ;; Get a new set of tags from the user
11247 (save-excursion
11248 (setq table (append org-tag-persistent-alist
11249 (or org-tag-alist (org-get-buffer-tags)))
11250 org-last-tags-completion-table table
11251 current-tags (org-split-string current ":")
11252 inherited-tags (nreverse
11253 (nthcdr (length current-tags)
11254 (nreverse (org-get-tags-at))))
11255 tags
11256 (if (or (eq t org-use-fast-tag-selection)
11257 (and org-use-fast-tag-selection
11258 (delq nil (mapcar 'cdr table))))
11259 (org-fast-tag-selection
11260 current-tags inherited-tags table
11261 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11262 (let ((org-add-colon-after-tag-completion t))
11263 (org-trim
11264 (org-without-partial-completion
11265 (org-icompleting-read "Tags: " 'org-tags-completion-function
11266 nil nil current 'org-tags-history)))))))
11267 (while (string-match "[-+&]+" tags)
11268 ;; No boolean logic, just a list
11269 (setq tags (replace-match ":" t t tags))))
11271 (if org-tags-sort-function
11272 (setq tags (mapconcat 'identity
11273 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11274 org-tags-sort-function) ":")))
11276 (if (string-match "\\`[\t ]*\\'" tags)
11277 (setq tags "")
11278 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11279 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11281 ;; Insert new tags at the correct column
11282 (beginning-of-line 1)
11283 (cond
11284 ((and (equal current "") (equal tags "")))
11285 ((re-search-forward
11286 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11287 (point-at-eol) t)
11288 (if (equal tags "")
11289 (setq rpl "")
11290 (goto-char (match-beginning 0))
11291 (setq c0 (current-column) p0 (point)
11292 c1 (max (1+ c0) (if (> org-tags-column 0)
11293 org-tags-column
11294 (- (- org-tags-column) (length tags))))
11295 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11296 (replace-match rpl t t)
11297 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11298 tags)
11299 (t (error "Tags alignment failed")))
11300 (org-move-to-column col)
11301 (unless just-align
11302 (run-hooks 'org-after-tags-change-hook)))))
11304 (defun org-change-tag-in-region (beg end tag off)
11305 "Add or remove TAG for each entry in the region.
11306 This works in the agenda, and also in an org-mode buffer."
11307 (interactive
11308 (list (region-beginning) (region-end)
11309 (let ((org-last-tags-completion-table
11310 (if (org-mode-p)
11311 (org-get-buffer-tags)
11312 (org-global-tags-completion-table))))
11313 (org-icompleting-read
11314 "Tag: " 'org-tags-completion-function nil nil nil
11315 'org-tags-history))
11316 (progn
11317 (message "[s]et or [r]emove? ")
11318 (equal (read-char-exclusive) ?r))))
11319 (if (fboundp 'deactivate-mark) (deactivate-mark))
11320 (let ((agendap (equal major-mode 'org-agenda-mode))
11321 l1 l2 m buf pos newhead (cnt 0))
11322 (goto-char end)
11323 (setq l2 (1- (org-current-line)))
11324 (goto-char beg)
11325 (setq l1 (org-current-line))
11326 (loop for l from l1 to l2 do
11327 (org-goto-line l)
11328 (setq m (get-text-property (point) 'org-hd-marker))
11329 (when (or (and (org-mode-p) (org-on-heading-p))
11330 (and agendap m))
11331 (setq buf (if agendap (marker-buffer m) (current-buffer))
11332 pos (if agendap m (point)))
11333 (with-current-buffer buf
11334 (save-excursion
11335 (save-restriction
11336 (goto-char pos)
11337 (setq cnt (1+ cnt))
11338 (org-toggle-tag tag (if off 'off 'on))
11339 (setq newhead (org-get-heading)))))
11340 (and agendap (org-agenda-change-all-lines newhead m))))
11341 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11343 (defun org-tags-completion-function (string predicate &optional flag)
11344 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11345 (confirm (lambda (x) (stringp (car x)))))
11346 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11347 (setq s1 (match-string 1 string)
11348 s2 (match-string 2 string))
11349 (setq s1 "" s2 string))
11350 (cond
11351 ((eq flag nil)
11352 ;; try completion
11353 (setq rtn (try-completion s2 ctable confirm))
11354 (if (stringp rtn)
11355 (setq rtn
11356 (concat s1 s2 (substring rtn (length s2))
11357 (if (and org-add-colon-after-tag-completion
11358 (assoc rtn ctable))
11359 ":" ""))))
11360 rtn)
11361 ((eq flag t)
11362 ;; all-completions
11363 (all-completions s2 ctable confirm)
11365 ((eq flag 'lambda)
11366 ;; exact match?
11367 (assoc s2 ctable)))
11370 (defun org-fast-tag-insert (kwd tags face &optional end)
11371 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11372 (insert (format "%-12s" (concat kwd ":"))
11373 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11374 (or end "")))
11376 (defun org-fast-tag-show-exit (flag)
11377 (save-excursion
11378 (org-goto-line 3)
11379 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11380 (replace-match ""))
11381 (when flag
11382 (end-of-line 1)
11383 (org-move-to-column (- (window-width) 19) t)
11384 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11386 (defun org-set-current-tags-overlay (current prefix)
11387 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11388 (if (featurep 'xemacs)
11389 (org-overlay-display org-tags-overlay (concat prefix s)
11390 'secondary-selection)
11391 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11392 (org-overlay-display org-tags-overlay (concat prefix s)))))
11394 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11395 "Fast tag selection with single keys.
11396 CURRENT is the current list of tags in the headline, INHERITED is the
11397 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11398 possibly with grouping information. TODO-TABLE is a similar table with
11399 TODO keywords, should these have keys assigned to them.
11400 If the keys are nil, a-z are automatically assigned.
11401 Returns the new tags string, or nil to not change the current settings."
11402 (let* ((fulltable (append table todo-table))
11403 (maxlen (apply 'max (mapcar
11404 (lambda (x)
11405 (if (stringp (car x)) (string-width (car x)) 0))
11406 fulltable)))
11407 (buf (current-buffer))
11408 (expert (eq org-fast-tag-selection-single-key 'expert))
11409 (buffer-tags nil)
11410 (fwidth (+ maxlen 3 1 3))
11411 (ncol (/ (- (window-width) 4) fwidth))
11412 (i-face 'org-done)
11413 (c-face 'org-todo)
11414 tg cnt e c char c1 c2 ntable tbl rtn
11415 ov-start ov-end ov-prefix
11416 (exit-after-next org-fast-tag-selection-single-key)
11417 (done-keywords org-done-keywords)
11418 groups ingroup)
11419 (save-excursion
11420 (beginning-of-line 1)
11421 (if (looking-at
11422 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11423 (setq ov-start (match-beginning 1)
11424 ov-end (match-end 1)
11425 ov-prefix "")
11426 (setq ov-start (1- (point-at-eol))
11427 ov-end (1+ ov-start))
11428 (skip-chars-forward "^\n\r")
11429 (setq ov-prefix
11430 (concat
11431 (buffer-substring (1- (point)) (point))
11432 (if (> (current-column) org-tags-column)
11434 (make-string (- org-tags-column (current-column)) ?\ ))))))
11435 (org-move-overlay org-tags-overlay ov-start ov-end)
11436 (save-window-excursion
11437 (if expert
11438 (set-buffer (get-buffer-create " *Org tags*"))
11439 (delete-other-windows)
11440 (split-window-vertically)
11441 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11442 (erase-buffer)
11443 (org-set-local 'org-done-keywords done-keywords)
11444 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11445 (org-fast-tag-insert "Current" current c-face "\n\n")
11446 (org-fast-tag-show-exit exit-after-next)
11447 (org-set-current-tags-overlay current ov-prefix)
11448 (setq tbl fulltable char ?a cnt 0)
11449 (while (setq e (pop tbl))
11450 (cond
11451 ((equal e '(:startgroup))
11452 (push '() groups) (setq ingroup t)
11453 (when (not (= cnt 0))
11454 (setq cnt 0)
11455 (insert "\n"))
11456 (insert "{ "))
11457 ((equal e '(:endgroup))
11458 (setq ingroup nil cnt 0)
11459 (insert "}\n"))
11460 ((equal e '(:newline))
11461 (when (not (= cnt 0))
11462 (setq cnt 0)
11463 (insert "\n")
11464 (setq e (car tbl))
11465 (while (equal (car tbl) '(:newline))
11466 (insert "\n")
11467 (setq tbl (cdr tbl)))))
11469 (setq tg (copy-sequence (car e)) c2 nil)
11470 (if (cdr e)
11471 (setq c (cdr e))
11472 ;; automatically assign a character.
11473 (setq c1 (string-to-char
11474 (downcase (substring
11475 tg (if (= (string-to-char tg) ?@) 1 0)))))
11476 (if (or (rassoc c1 ntable) (rassoc c1 table))
11477 (while (or (rassoc char ntable) (rassoc char table))
11478 (setq char (1+ char)))
11479 (setq c2 c1))
11480 (setq c (or c2 char)))
11481 (if ingroup (push tg (car groups)))
11482 (setq tg (org-add-props tg nil 'face
11483 (cond
11484 ((not (assoc tg table))
11485 (org-get-todo-face tg))
11486 ((member tg current) c-face)
11487 ((member tg inherited) i-face)
11488 (t nil))))
11489 (if (and (= cnt 0) (not ingroup)) (insert " "))
11490 (insert "[" c "] " tg (make-string
11491 (- fwidth 4 (length tg)) ?\ ))
11492 (push (cons tg c) ntable)
11493 (when (= (setq cnt (1+ cnt)) ncol)
11494 (insert "\n")
11495 (if ingroup (insert " "))
11496 (setq cnt 0)))))
11497 (setq ntable (nreverse ntable))
11498 (insert "\n")
11499 (goto-char (point-min))
11500 (if (not expert) (org-fit-window-to-buffer))
11501 (setq rtn
11502 (catch 'exit
11503 (while t
11504 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11505 (if groups " [!] no groups" " [!]groups")
11506 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11507 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11508 (cond
11509 ((= c ?\r) (throw 'exit t))
11510 ((= c ?!)
11511 (setq groups (not groups))
11512 (goto-char (point-min))
11513 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11514 ((= c ?\C-c)
11515 (if (not expert)
11516 (org-fast-tag-show-exit
11517 (setq exit-after-next (not exit-after-next)))
11518 (setq expert nil)
11519 (delete-other-windows)
11520 (split-window-vertically)
11521 (org-switch-to-buffer-other-window " *Org tags*")
11522 (org-fit-window-to-buffer)))
11523 ((or (= c ?\C-g)
11524 (and (= c ?q) (not (rassoc c ntable))))
11525 (org-detach-overlay org-tags-overlay)
11526 (setq quit-flag t))
11527 ((= c ?\ )
11528 (setq current nil)
11529 (if exit-after-next (setq exit-after-next 'now)))
11530 ((= c ?\t)
11531 (condition-case nil
11532 (setq tg (org-icompleting-read
11533 "Tag: "
11534 (or buffer-tags
11535 (with-current-buffer buf
11536 (org-get-buffer-tags)))))
11537 (quit (setq tg "")))
11538 (when (string-match "\\S-" tg)
11539 (add-to-list 'buffer-tags (list tg))
11540 (if (member tg current)
11541 (setq current (delete tg current))
11542 (push tg current)))
11543 (if exit-after-next (setq exit-after-next 'now)))
11544 ((setq e (rassoc c todo-table) tg (car e))
11545 (with-current-buffer buf
11546 (save-excursion (org-todo tg)))
11547 (if exit-after-next (setq exit-after-next 'now)))
11548 ((setq e (rassoc c ntable) tg (car e))
11549 (if (member tg current)
11550 (setq current (delete tg current))
11551 (loop for g in groups do
11552 (if (member tg g)
11553 (mapc (lambda (x)
11554 (setq current (delete x current)))
11555 g)))
11556 (push tg current))
11557 (if exit-after-next (setq exit-after-next 'now))))
11559 ;; Create a sorted list
11560 (setq current
11561 (sort current
11562 (lambda (a b)
11563 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11564 (if (eq exit-after-next 'now) (throw 'exit t))
11565 (goto-char (point-min))
11566 (beginning-of-line 2)
11567 (delete-region (point) (point-at-eol))
11568 (org-fast-tag-insert "Current" current c-face)
11569 (org-set-current-tags-overlay current ov-prefix)
11570 (while (re-search-forward
11571 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11572 (setq tg (match-string 1))
11573 (add-text-properties
11574 (match-beginning 1) (match-end 1)
11575 (list 'face
11576 (cond
11577 ((member tg current) c-face)
11578 ((member tg inherited) i-face)
11579 (t (get-text-property (match-beginning 1) 'face))))))
11580 (goto-char (point-min)))))
11581 (org-detach-overlay org-tags-overlay)
11582 (if rtn
11583 (mapconcat 'identity current ":")
11584 nil))))
11586 (defun org-get-tags-string ()
11587 "Get the TAGS string in the current headline."
11588 (unless (org-on-heading-p t)
11589 (error "Not on a heading"))
11590 (save-excursion
11591 (beginning-of-line 1)
11592 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11593 (org-match-string-no-properties 1)
11594 "")))
11596 (defun org-get-tags ()
11597 "Get the list of tags specified in the current headline."
11598 (org-split-string (org-get-tags-string) ":"))
11600 (defun org-get-buffer-tags ()
11601 "Get a table of all tags used in the buffer, for completion."
11602 (let (tags)
11603 (save-excursion
11604 (goto-char (point-min))
11605 (while (re-search-forward
11606 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11607 (when (equal (char-after (point-at-bol 0)) ?*)
11608 (mapc (lambda (x) (add-to-list 'tags x))
11609 (org-split-string (org-match-string-no-properties 1) ":")))))
11610 (mapcar 'list tags)))
11612 ;;;; The mapping API
11614 ;;;###autoload
11615 (defun org-map-entries (func &optional match scope &rest skip)
11616 "Call FUNC at each headline selected by MATCH in SCOPE.
11618 FUNC is a function or a lisp form. The function will be called without
11619 arguments, with the cursor positioned at the beginning of the headline.
11620 The return values of all calls to the function will be collected and
11621 returned as a list.
11623 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11624 does not need to preserve point. After evaluation, the cursor will be
11625 moved to the end of the line (presumably of the headline of the
11626 processed entry) and search continues from there. Under some
11627 circumstances, this may not produce the wanted results. For example,
11628 if you have removed (e.g. archived) the current (sub)tree it could
11629 mean that the next entry will be skipped entirely. In such cases, you
11630 can specify the position from where search should continue by making
11631 FUNC set the variable `org-map-continue-from' to the desired buffer
11632 position.
11634 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11635 Only headlines that are matched by this query will be considered during
11636 the iteration. When MATCH is nil or t, all headlines will be
11637 visited by the iteration.
11639 SCOPE determines the scope of this command. It can be any of:
11641 nil The current buffer, respecting the restriction if any
11642 tree The subtree started with the entry at point
11643 file The current buffer, without restriction
11644 file-with-archives
11645 The current buffer, and any archives associated with it
11646 agenda All agenda files
11647 agenda-with-archives
11648 All agenda files with any archive files associated with them
11649 \(file1 file2 ...)
11650 If this is a list, all files in the list will be scanned
11652 The remaining args are treated as settings for the skipping facilities of
11653 the scanner. The following items can be given here:
11655 archive skip trees with the archive tag.
11656 comment skip trees with the COMMENT keyword
11657 function or Emacs Lisp form:
11658 will be used as value for `org-agenda-skip-function', so whenever
11659 the the function returns t, FUNC will not be called for that
11660 entry and search will continue from the point where the
11661 function leaves it.
11663 If your function needs to retrieve the tags including inherited tags
11664 at the *current* entry, you can use the value of the variable
11665 `org-scanner-tags' which will be much faster than getting the value
11666 with `org-get-tags-at'. If your function gets properties with
11667 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11668 to t around the call to `org-entry-properties' to get the same speedup.
11669 Note that if your function moves around to retrieve tags and properties at
11670 a *different* entry, you cannot use these techniques."
11671 (let* ((org-agenda-archives-mode nil) ; just to make sure
11672 (org-agenda-skip-archived-trees (memq 'archive skip))
11673 (org-agenda-skip-comment-trees (memq 'comment skip))
11674 (org-agenda-skip-function
11675 (car (org-delete-all '(comment archive) skip)))
11676 (org-tags-match-list-sublevels t)
11677 matcher file res
11678 org-todo-keywords-for-agenda
11679 org-done-keywords-for-agenda
11680 org-todo-keyword-alist-for-agenda
11681 org-tag-alist-for-agenda)
11683 (cond
11684 ((eq match t) (setq matcher t))
11685 ((eq match nil) (setq matcher t))
11686 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11688 (save-excursion
11689 (save-restriction
11690 (when (eq scope 'tree)
11691 (org-back-to-heading t)
11692 (org-narrow-to-subtree)
11693 (setq scope nil))
11695 (if (not scope)
11696 (progn
11697 (org-prepare-agenda-buffers
11698 (list (buffer-file-name (current-buffer))))
11699 (setq res (org-scan-tags func matcher)))
11700 ;; Get the right scope
11701 (cond
11702 ((and scope (listp scope) (symbolp (car scope)))
11703 (setq scope (eval scope)))
11704 ((eq scope 'agenda)
11705 (setq scope (org-agenda-files t)))
11706 ((eq scope 'agenda-with-archives)
11707 (setq scope (org-agenda-files t))
11708 (setq scope (org-add-archive-files scope)))
11709 ((eq scope 'file)
11710 (setq scope (list (buffer-file-name))))
11711 ((eq scope 'file-with-archives)
11712 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11713 (org-prepare-agenda-buffers scope)
11714 (while (setq file (pop scope))
11715 (with-current-buffer (org-find-base-buffer-visiting file)
11716 (save-excursion
11717 (save-restriction
11718 (widen)
11719 (goto-char (point-min))
11720 (setq res (append res (org-scan-tags func matcher))))))))))
11721 res))
11723 ;;;; Properties
11725 ;;; Setting and retrieving properties
11727 (defconst org-special-properties
11728 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11729 "TIMESTAMP" "TIMESTAMP_IA")
11730 "The special properties valid in Org-mode.
11732 These are properties that are not defined in the property drawer,
11733 but in some other way.")
11735 (defconst org-default-properties
11736 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11737 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11738 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11739 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11740 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11741 "CLOCK_MODELINE_TOTAL")
11742 "Some properties that are used by Org-mode for various purposes.
11743 Being in this list makes sure that they are offered for completion.")
11745 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11746 "Regular expression matching the first line of a property drawer.")
11748 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11749 "Regular expression matching the first line of a property drawer.")
11751 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11752 "Regular expression matching the first line of a property drawer.")
11754 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11755 "Regular expression matching the first line of a property drawer.")
11757 (defconst org-property-drawer-re
11758 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11759 org-property-end-re "\\)\n?")
11760 "Matches an entire property drawer.")
11762 (defconst org-clock-drawer-re
11763 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11764 org-property-end-re "\\)\n?")
11765 "Matches an entire clock drawer.")
11767 (defun org-property-action ()
11768 "Do an action on properties."
11769 (interactive)
11770 (let (c)
11771 (org-at-property-p)
11772 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11773 (setq c (read-char-exclusive))
11774 (cond
11775 ((equal c ?s)
11776 (call-interactively 'org-set-property))
11777 ((equal c ?d)
11778 (call-interactively 'org-delete-property))
11779 ((equal c ?D)
11780 (call-interactively 'org-delete-property-globally))
11781 ((equal c ?c)
11782 (call-interactively 'org-compute-property-at-point))
11783 (t (error "No such property action %c" c)))))
11785 (defun org-set-effort (&optional value)
11786 "Set the effort property of the current entry.
11787 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
11788 allowed value."
11789 (interactive "P")
11790 (if (equal value 0) (setq value 10))
11791 (let* ((completion-ignore-case t)
11792 (prop org-effort-property)
11793 (cur (org-entry-get nil prop))
11794 (allowed (org-property-get-allowed-values nil prop 'table))
11795 (existing (mapcar 'list (org-property-values prop)))
11796 (val (cond
11797 ((stringp value) value)
11798 ((and allowed (integerp value))
11799 (or (car (nth (1- value) allowed))
11800 (car (org-last allowed))))
11801 (allowed
11802 (org-completing-read "Value: " allowed nil 'req-match))
11804 (let (org-completion-use-ido org-completion-use-iswitchb)
11805 (org-completing-read
11806 (concat "Value " (if (and cur (string-match "\\S-" cur))
11807 (concat "[" cur "]") "")
11808 ": ")
11809 existing nil nil "" nil cur))))))
11810 (unless (equal (org-entry-get nil prop) val)
11811 (org-entry-put nil prop val))
11812 (message "%s is now %s" prop val)))
11814 (defun org-at-property-p ()
11815 "Is the cursor in a property line?"
11816 ;; FIXME: Does not check if we are actually in the drawer.
11817 ;; FIXME: also returns true on any drawers.....
11818 ;; This is used by C-c C-c for property action.
11819 (save-excursion
11820 (beginning-of-line 1)
11821 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11823 (defun org-get-property-block (&optional beg end force)
11824 "Return the (beg . end) range of the body of the property drawer.
11825 BEG and END can be beginning and end of subtree, if not given
11826 they will be found.
11827 If the drawer does not exist and FORCE is non-nil, create the drawer."
11828 (catch 'exit
11829 (save-excursion
11830 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11831 (end (or end (progn (outline-next-heading) (point)))))
11832 (goto-char beg)
11833 (if (re-search-forward org-property-start-re end t)
11834 (setq beg (1+ (match-end 0)))
11835 (if force
11836 (save-excursion
11837 (org-insert-property-drawer)
11838 (setq end (progn (outline-next-heading) (point))))
11839 (throw 'exit nil))
11840 (goto-char beg)
11841 (if (re-search-forward org-property-start-re end t)
11842 (setq beg (1+ (match-end 0)))))
11843 (if (re-search-forward org-property-end-re end t)
11844 (setq end (match-beginning 0))
11845 (or force (throw 'exit nil))
11846 (goto-char beg)
11847 (setq end beg)
11848 (org-indent-line-function)
11849 (insert ":END:\n"))
11850 (cons beg end)))))
11852 (defun org-entry-properties (&optional pom which)
11853 "Get all properties of the entry at point-or-marker POM.
11854 This includes the TODO keyword, the tags, time strings for deadline,
11855 scheduled, and clocking, and any additional properties defined in the
11856 entry. The return value is an alist, keys may occur multiple times
11857 if the property key was used several times.
11858 POM may also be nil, in which case the current entry is used.
11859 If WHICH is nil or `all', get all properties. If WHICH is
11860 `special' or `standard', only get that subclass."
11861 (setq which (or which 'all))
11862 (org-with-point-at pom
11863 (let ((clockstr (substring org-clock-string 0 -1))
11864 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11865 beg end range props sum-props key value string clocksum)
11866 (save-excursion
11867 (when (condition-case nil
11868 (and (org-mode-p) (org-back-to-heading t))
11869 (error nil))
11870 (setq beg (point))
11871 (setq sum-props (get-text-property (point) 'org-summaries))
11872 (setq clocksum (get-text-property (point) :org-clock-minutes))
11873 (outline-next-heading)
11874 (setq end (point))
11875 (when (memq which '(all special))
11876 ;; Get the special properties, like TODO and tags
11877 (goto-char beg)
11878 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11879 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11880 (when (looking-at org-priority-regexp)
11881 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11882 (when (and (setq value (org-get-tags-string))
11883 (string-match "\\S-" value))
11884 (push (cons "TAGS" value) props))
11885 (when (setq value (org-get-tags-at))
11886 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11887 props))
11888 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11889 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11890 string (if (equal key clockstr)
11891 (org-no-properties
11892 (org-trim
11893 (buffer-substring
11894 (match-beginning 3) (goto-char (point-at-eol)))))
11895 (substring (org-match-string-no-properties 3) 1 -1)))
11896 (unless key
11897 (if (= (char-after (match-beginning 3)) ?\[)
11898 (setq key "TIMESTAMP_IA")
11899 (setq key "TIMESTAMP")))
11900 (when (or (equal key clockstr) (not (assoc key props)))
11901 (push (cons key string) props)))
11905 (when (memq which '(all standard))
11906 ;; Get the standard properties, like :PROP: ...
11907 (setq range (org-get-property-block beg end))
11908 (when range
11909 (goto-char (car range))
11910 (while (re-search-forward
11911 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11912 (cdr range) t)
11913 (setq key (org-match-string-no-properties 1)
11914 value (org-trim (or (org-match-string-no-properties 2) "")))
11915 (unless (member key excluded)
11916 (push (cons key (or value "")) props)))))
11917 (if clocksum
11918 (push (cons "CLOCKSUM"
11919 (org-columns-number-to-string (/ (float clocksum) 60.)
11920 'add_times))
11921 props))
11922 (unless (assoc "CATEGORY" props)
11923 (setq value (or (org-get-category)
11924 (progn (org-refresh-category-properties)
11925 (org-get-category))))
11926 (push (cons "CATEGORY" value) props))
11927 (append sum-props (nreverse props)))))))
11929 (defun org-entry-get (pom property &optional inherit)
11930 "Get value of PROPERTY for entry at point-or-marker POM.
11931 If INHERIT is non-nil and the entry does not have the property,
11932 then also check higher levels of the hierarchy.
11933 If INHERIT is the symbol `selective', use inheritance only if the setting
11934 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11935 If the property is present but empty, the return value is the empty string.
11936 If the property is not present at all, nil is returned."
11937 (org-with-point-at pom
11938 (if (and inherit (if (eq inherit 'selective)
11939 (org-property-inherit-p property)
11941 (org-entry-get-with-inheritance property)
11942 (if (member property org-special-properties)
11943 ;; We need a special property. Use brute force, get all properties.
11944 (cdr (assoc property (org-entry-properties nil 'special)))
11945 (let ((range (org-get-property-block)))
11946 (if (and range
11947 (goto-char (car range))
11948 (re-search-forward
11949 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11950 (cdr range) t))
11951 ;; Found the property, return it.
11952 (if (match-end 1)
11953 (org-match-string-no-properties 1)
11954 "")))))))
11956 (defun org-property-or-variable-value (var &optional inherit)
11957 "Check if there is a property fixing the value of VAR.
11958 If yes, return this value. If not, return the current value of the variable."
11959 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11960 (if (and prop (stringp prop) (string-match "\\S-" prop))
11961 (read prop)
11962 (symbol-value var))))
11964 (defun org-entry-delete (pom property)
11965 "Delete the property PROPERTY from entry at point-or-marker POM."
11966 (org-with-point-at pom
11967 (if (member property org-special-properties)
11968 nil ; cannot delete these properties.
11969 (let ((range (org-get-property-block)))
11970 (if (and range
11971 (goto-char (car range))
11972 (re-search-forward
11973 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11974 (cdr range) t))
11975 (progn
11976 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11978 nil)))))
11980 ;; Multi-values properties are properties that contain multiple values
11981 ;; These values are assumed to be single words, separated by whitespace.
11982 (defun org-entry-add-to-multivalued-property (pom property value)
11983 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11984 (let* ((old (org-entry-get pom property))
11985 (values (and old (org-split-string old "[ \t]"))))
11986 (setq value (org-entry-protect-space value))
11987 (unless (member value values)
11988 (setq values (cons value values))
11989 (org-entry-put pom property
11990 (mapconcat 'identity values " ")))))
11992 (defun org-entry-remove-from-multivalued-property (pom property value)
11993 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11994 (let* ((old (org-entry-get pom property))
11995 (values (and old (org-split-string old "[ \t]"))))
11996 (setq value (org-entry-protect-space value))
11997 (when (member value values)
11998 (setq values (delete value values))
11999 (org-entry-put pom property
12000 (mapconcat 'identity values " ")))))
12002 (defun org-entry-member-in-multivalued-property (pom property value)
12003 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12004 (let* ((old (org-entry-get pom property))
12005 (values (and old (org-split-string old "[ \t]"))))
12006 (setq value (org-entry-protect-space value))
12007 (member value values)))
12009 (defun org-entry-get-multivalued-property (pom property)
12010 "Return a list of values in a multivalued property."
12011 (let* ((value (org-entry-get pom property))
12012 (values (and value (org-split-string value "[ \t]"))))
12013 (mapcar 'org-entry-restore-space values)))
12015 (defun org-entry-put-multivalued-property (pom property &rest values)
12016 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12017 VALUES should be a list of strings. Spaces will be protected."
12018 (org-entry-put pom property
12019 (mapconcat 'org-entry-protect-space values " "))
12020 (let* ((value (org-entry-get pom property))
12021 (values (and value (org-split-string value "[ \t]"))))
12022 (mapcar 'org-entry-restore-space values)))
12024 (defun org-entry-protect-space (s)
12025 "Protect spaces and newline in string S."
12026 (while (string-match " " s)
12027 (setq s (replace-match "%20" t t s)))
12028 (while (string-match "\n" s)
12029 (setq s (replace-match "%0A" t t s)))
12032 (defun org-entry-restore-space (s)
12033 "Restore spaces and newline in string S."
12034 (while (string-match "%20" s)
12035 (setq s (replace-match " " t t s)))
12036 (while (string-match "%0A" s)
12037 (setq s (replace-match "\n" t t s)))
12040 (defvar org-entry-property-inherited-from (make-marker)
12041 "Marker pointing to the entry from where a property was inherited.
12042 Each call to `org-entry-get-with-inheritance' will set this marker to the
12043 location of the entry where the inheritance search matched. If there was
12044 no match, the marker will point nowhere.
12045 Note that also `org-entry-get' calls this function, if the INHERIT flag
12046 is set.")
12048 (defun org-entry-get-with-inheritance (property)
12049 "Get entry property, and search higher levels if not present."
12050 (move-marker org-entry-property-inherited-from nil)
12051 (let (tmp)
12052 (save-excursion
12053 (save-restriction
12054 (widen)
12055 (catch 'ex
12056 (while t
12057 (when (setq tmp (org-entry-get nil property))
12058 (org-back-to-heading t)
12059 (move-marker org-entry-property-inherited-from (point))
12060 (throw 'ex tmp))
12061 (or (org-up-heading-safe) (throw 'ex nil)))))
12062 (or tmp
12063 (cdr (assoc property org-file-properties))
12064 (cdr (assoc property org-global-properties))
12065 (cdr (assoc property org-global-properties-fixed))))))
12067 (defun org-entry-put (pom property value)
12068 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12069 (org-with-point-at pom
12070 (org-back-to-heading t)
12071 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12072 range)
12073 (cond
12074 ((equal property "TODO")
12075 (when (and (stringp value) (string-match "\\S-" value)
12076 (not (member value org-todo-keywords-1)))
12077 (error "\"%s\" is not a valid TODO state" value))
12078 (if (or (not value)
12079 (not (string-match "\\S-" value)))
12080 (setq value 'none))
12081 (org-todo value)
12082 (org-set-tags nil 'align))
12083 ((equal property "PRIORITY")
12084 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12085 (string-to-char value) ?\ ))
12086 (org-set-tags nil 'align))
12087 ((equal property "SCHEDULED")
12088 (if (re-search-forward org-scheduled-time-regexp end t)
12089 (cond
12090 ((eq value 'earlier) (org-timestamp-change -1 'day))
12091 ((eq value 'later) (org-timestamp-change 1 'day))
12092 (t (call-interactively 'org-schedule)))
12093 (call-interactively 'org-schedule)))
12094 ((equal property "DEADLINE")
12095 (if (re-search-forward org-deadline-time-regexp end t)
12096 (cond
12097 ((eq value 'earlier) (org-timestamp-change -1 'day))
12098 ((eq value 'later) (org-timestamp-change 1 'day))
12099 (t (call-interactively 'org-deadline)))
12100 (call-interactively 'org-deadline)))
12101 ((member property org-special-properties)
12102 (error "The %s property can not yet be set with `org-entry-put'"
12103 property))
12104 (t ; a non-special property
12105 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12106 (setq range (org-get-property-block beg end 'force))
12107 (goto-char (car range))
12108 (if (re-search-forward
12109 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12110 (progn
12111 (delete-region (match-beginning 1) (match-end 1))
12112 (goto-char (match-beginning 1)))
12113 (goto-char (cdr range))
12114 (insert "\n")
12115 (backward-char 1)
12116 (org-indent-line-function)
12117 (insert ":" property ":"))
12118 (and value (insert " " value))
12119 (org-indent-line-function)))))))
12121 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12122 "Get all property keys in the current buffer.
12123 With INCLUDE-SPECIALS, also list the special properties that reflect things
12124 like tags and TODO state.
12125 With INCLUDE-DEFAULTS, also include properties that has special meaning
12126 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12127 With INCLUDE-COLUMNS, also include property names given in COLUMN
12128 formats in the current buffer."
12129 (let (rtn range cfmt s p)
12130 (save-excursion
12131 (save-restriction
12132 (widen)
12133 (goto-char (point-min))
12134 (while (re-search-forward org-property-start-re nil t)
12135 (setq range (org-get-property-block))
12136 (goto-char (car range))
12137 (while (re-search-forward
12138 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12139 (cdr range) t)
12140 (add-to-list 'rtn (org-match-string-no-properties 1)))
12141 (outline-next-heading))))
12143 (when include-specials
12144 (setq rtn (append org-special-properties rtn)))
12146 (when include-defaults
12147 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12148 (add-to-list 'rtn org-effort-property))
12150 (when include-columns
12151 (save-excursion
12152 (save-restriction
12153 (widen)
12154 (goto-char (point-min))
12155 (while (re-search-forward
12156 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12157 nil t)
12158 (setq cfmt (match-string 2) s 0)
12159 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12160 cfmt s)
12161 (setq s (match-end 0)
12162 p (match-string 1 cfmt))
12163 (unless (or (equal p "ITEM")
12164 (member p org-special-properties))
12165 (add-to-list 'rtn (match-string 1 cfmt))))))))
12167 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12169 (defun org-property-values (key)
12170 "Return a list of all values of property KEY."
12171 (save-excursion
12172 (save-restriction
12173 (widen)
12174 (goto-char (point-min))
12175 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12176 values)
12177 (while (re-search-forward re nil t)
12178 (add-to-list 'values (org-trim (match-string 1))))
12179 (delete "" values)))))
12181 (defun org-insert-property-drawer ()
12182 "Insert a property drawer into the current entry."
12183 (interactive)
12184 (org-back-to-heading t)
12185 (looking-at outline-regexp)
12186 (let ((indent (if org-adapt-indentation
12187 (- (match-end 0)(match-beginning 0))
12189 (beg (point))
12190 (re (concat "^[ \t]*" org-keyword-time-regexp))
12191 end hiddenp)
12192 (outline-next-heading)
12193 (setq end (point))
12194 (goto-char beg)
12195 (while (re-search-forward re end t))
12196 (setq hiddenp (org-invisible-p))
12197 (end-of-line 1)
12198 (and (equal (char-after) ?\n) (forward-char 1))
12199 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12200 (if (member (match-string 1) '("CLOCK:" ":END:"))
12201 ;; just skip this line
12202 (beginning-of-line 2)
12203 ;; Drawer start, find the end
12204 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12205 (beginning-of-line 1)))
12206 (org-skip-over-state-notes)
12207 (skip-chars-backward " \t\n\r")
12208 (if (eq (char-before) ?*) (forward-char 1))
12209 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12210 (beginning-of-line 0)
12211 (org-indent-to-column indent)
12212 (beginning-of-line 2)
12213 (org-indent-to-column indent)
12214 (beginning-of-line 0)
12215 (if hiddenp
12216 (save-excursion
12217 (org-back-to-heading t)
12218 (hide-entry))
12219 (org-flag-drawer t))))
12221 (defun org-set-property (property value)
12222 "In the current entry, set PROPERTY to VALUE.
12223 When called interactively, this will prompt for a property name, offering
12224 completion on existing and default properties. And then it will prompt
12225 for a value, offering completion either on allowed values (via an inherited
12226 xxx_ALL property) or on existing values in other instances of this property
12227 in the current file."
12228 (interactive
12229 (let* ((completion-ignore-case t)
12230 (keys (org-buffer-property-keys nil t t))
12231 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12232 (prop (if (member prop0 keys)
12233 prop0
12234 (or (cdr (assoc (downcase prop0)
12235 (mapcar (lambda (x) (cons (downcase x) x))
12236 keys)))
12237 prop0)))
12238 (cur (org-entry-get nil prop))
12239 (allowed (org-property-get-allowed-values nil prop 'table))
12240 (existing (mapcar 'list (org-property-values prop)))
12241 (val (if allowed
12242 (org-completing-read "Value: " allowed nil 'req-match)
12243 (let (org-completion-use-ido org-completion-use-iswitchb)
12244 (org-completing-read
12245 (concat "Value " (if (and cur (string-match "\\S-" cur))
12246 (concat "[" cur "]") "")
12247 ": ")
12248 existing nil nil "" nil cur)))))
12249 (list prop (if (equal val "") cur val))))
12250 (unless (equal (org-entry-get nil property) value)
12251 (org-entry-put nil property value)))
12253 (defun org-delete-property (property)
12254 "In the current entry, delete PROPERTY."
12255 (interactive
12256 (let* ((completion-ignore-case t)
12257 (prop (org-icompleting-read
12258 "Property: " (org-entry-properties nil 'standard))))
12259 (list prop)))
12260 (message "Property %s %s" property
12261 (if (org-entry-delete nil property)
12262 "deleted"
12263 "was not present in the entry")))
12265 (defun org-delete-property-globally (property)
12266 "Remove PROPERTY globally, from all entries."
12267 (interactive
12268 (let* ((completion-ignore-case t)
12269 (prop (org-icompleting-read
12270 "Globally remove property: "
12271 (mapcar 'list (org-buffer-property-keys)))))
12272 (list prop)))
12273 (save-excursion
12274 (save-restriction
12275 (widen)
12276 (goto-char (point-min))
12277 (let ((cnt 0))
12278 (while (re-search-forward
12279 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12280 nil t)
12281 (setq cnt (1+ cnt))
12282 (replace-match ""))
12283 (message "Property \"%s\" removed from %d entries" property cnt)))))
12285 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12287 (defun org-compute-property-at-point ()
12288 "Compute the property at point.
12289 This looks for an enclosing column format, extracts the operator and
12290 then applies it to the property in the column format's scope."
12291 (interactive)
12292 (unless (org-at-property-p)
12293 (error "Not at a property"))
12294 (let ((prop (org-match-string-no-properties 2)))
12295 (org-columns-get-format-and-top-level)
12296 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12297 (error "No operator defined for property %s" prop))
12298 (org-columns-compute prop)))
12300 (defun org-property-get-allowed-values (pom property &optional table)
12301 "Get allowed values for the property PROPERTY.
12302 When TABLE is non-nil, return an alist that can directly be used for
12303 completion."
12304 (let (vals)
12305 (cond
12306 ((equal property "TODO")
12307 (setq vals (org-with-point-at pom
12308 (append org-todo-keywords-1 '("")))))
12309 ((equal property "PRIORITY")
12310 (let ((n org-lowest-priority))
12311 (while (>= n org-highest-priority)
12312 (push (char-to-string n) vals)
12313 (setq n (1- n)))))
12314 ((member property org-special-properties))
12316 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12318 (when (and vals (string-match "\\S-" vals))
12319 (setq vals (car (read-from-string (concat "(" vals ")"))))
12320 (setq vals (mapcar (lambda (x)
12321 (cond ((stringp x) x)
12322 ((numberp x) (number-to-string x))
12323 ((symbolp x) (symbol-name x))
12324 (t "???")))
12325 vals)))))
12326 (if table (mapcar 'list vals) vals)))
12328 (defun org-property-previous-allowed-value (&optional previous)
12329 "Switch to the next allowed value for this property."
12330 (interactive)
12331 (org-property-next-allowed-value t))
12333 (defun org-property-next-allowed-value (&optional previous)
12334 "Switch to the next allowed value for this property."
12335 (interactive)
12336 (unless (org-at-property-p)
12337 (error "Not at a property"))
12338 (let* ((key (match-string 2))
12339 (value (match-string 3))
12340 (allowed (or (org-property-get-allowed-values (point) key)
12341 (and (member value '("[ ]" "[-]" "[X]"))
12342 '("[ ]" "[X]"))))
12343 nval)
12344 (unless allowed
12345 (error "Allowed values for this property have not been defined"))
12346 (if previous (setq allowed (reverse allowed)))
12347 (if (member value allowed)
12348 (setq nval (car (cdr (member value allowed)))))
12349 (setq nval (or nval (car allowed)))
12350 (if (equal nval value)
12351 (error "Only one allowed value for this property"))
12352 (org-at-property-p)
12353 (replace-match (concat " :" key ": " nval) t t)
12354 (org-indent-line-function)
12355 (beginning-of-line 1)
12356 (skip-chars-forward " \t")))
12358 (defun org-find-entry-with-id (ident)
12359 "Locate the entry that contains the ID property with exact value IDENT.
12360 IDENT can be a string, a symbol or a number, this function will search for
12361 the string representation of it.
12362 Return the position where this entry starts, or nil if there is no such entry."
12363 (interactive "sID: ")
12364 (let ((id (cond
12365 ((stringp ident) ident)
12366 ((symbol-name ident) (symbol-name ident))
12367 ((numberp ident) (number-to-string ident))
12368 (t (error "IDENT %s must be a string, symbol or number" ident))))
12369 (case-fold-search nil))
12370 (save-excursion
12371 (save-restriction
12372 (widen)
12373 (goto-char (point-min))
12374 (when (re-search-forward
12375 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12376 nil t)
12377 (org-back-to-heading t)
12378 (point))))))
12380 ;;;; Timestamps
12382 (defvar org-last-changed-timestamp nil)
12383 (defvar org-last-inserted-timestamp nil
12384 "The last time stamp inserted with `org-insert-time-stamp'.")
12385 (defvar org-time-was-given) ; dynamically scoped parameter
12386 (defvar org-end-time-was-given) ; dynamically scoped parameter
12387 (defvar org-ts-what) ; dynamically scoped parameter
12389 (defun org-time-stamp (arg &optional inactive)
12390 "Prompt for a date/time and insert a time stamp.
12391 If the user specifies a time like HH:MM, or if this command is called
12392 with a prefix argument, the time stamp will contain date and time.
12393 Otherwise, only the date will be included. All parts of a date not
12394 specified by the user will be filled in from the current date/time.
12395 So if you press just return without typing anything, the time stamp
12396 will represent the current date/time. If there is already a timestamp
12397 at the cursor, it will be modified."
12398 (interactive "P")
12399 (let* ((ts nil)
12400 (default-time
12401 ;; Default time is either today, or, when entering a range,
12402 ;; the range start.
12403 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12404 (save-excursion
12405 (re-search-backward
12406 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12407 (- (point) 20) t)))
12408 (apply 'encode-time (org-parse-time-string (match-string 1)))
12409 (current-time)))
12410 (default-input (and ts (org-get-compact-tod ts)))
12411 org-time-was-given org-end-time-was-given time)
12412 (cond
12413 ((and (org-at-timestamp-p t)
12414 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12415 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12416 (insert "--")
12417 (setq time (let ((this-command this-command))
12418 (org-read-date arg 'totime nil nil
12419 default-time default-input)))
12420 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12421 ((org-at-timestamp-p t)
12422 (setq time (let ((this-command this-command))
12423 (org-read-date arg 'totime nil nil default-time default-input)))
12424 (when (org-at-timestamp-p t) ; just to get the match data
12425 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12426 (replace-match "")
12427 (setq org-last-changed-timestamp
12428 (org-insert-time-stamp
12429 time (or org-time-was-given arg)
12430 inactive nil nil (list org-end-time-was-given))))
12431 (message "Timestamp updated"))
12433 (setq time (let ((this-command this-command))
12434 (org-read-date arg 'totime nil nil default-time default-input)))
12435 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12436 nil nil (list org-end-time-was-given))))))
12438 ;; FIXME: can we use this for something else, like computing time differences?
12439 (defun org-get-compact-tod (s)
12440 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12441 (let* ((t1 (match-string 1 s))
12442 (h1 (string-to-number (match-string 2 s)))
12443 (m1 (string-to-number (match-string 3 s)))
12444 (t2 (and (match-end 4) (match-string 5 s)))
12445 (h2 (and t2 (string-to-number (match-string 6 s))))
12446 (m2 (and t2 (string-to-number (match-string 7 s))))
12447 dh dm)
12448 (if (not t2)
12450 (setq dh (- h2 h1) dm (- m2 m1))
12451 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12452 (concat t1 "+" (number-to-string dh)
12453 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12455 (defun org-time-stamp-inactive (&optional arg)
12456 "Insert an inactive time stamp.
12457 An inactive time stamp is enclosed in square brackets instead of angle
12458 brackets. It is inactive in the sense that it does not trigger agenda entries,
12459 does not link to the calendar and cannot be changed with the S-cursor keys.
12460 So these are more for recording a certain time/date."
12461 (interactive "P")
12462 (org-time-stamp arg 'inactive))
12464 (defvar org-date-ovl (org-make-overlay 1 1))
12465 (org-overlay-put org-date-ovl 'face 'org-warning)
12466 (org-detach-overlay org-date-ovl)
12468 (defvar org-ans1) ; dynamically scoped parameter
12469 (defvar org-ans2) ; dynamically scoped parameter
12471 (defvar org-plain-time-of-day-regexp) ; defined below
12473 (defvar org-overriding-default-time nil) ; dynamically scoped
12474 (defvar org-read-date-overlay nil)
12475 (defvar org-dcst nil) ; dynamically scoped
12476 (defvar org-read-date-history nil)
12477 (defvar org-read-date-final-answer nil)
12479 (defun org-read-date (&optional with-time to-time from-string prompt
12480 default-time default-input)
12481 "Read a date, possibly a time, and make things smooth for the user.
12482 The prompt will suggest to enter an ISO date, but you can also enter anything
12483 which will at least partially be understood by `parse-time-string'.
12484 Unrecognized parts of the date will default to the current day, month, year,
12485 hour and minute. If this command is called to replace a timestamp at point,
12486 of to enter the second timestamp of a range, the default time is taken from the
12487 existing stamp. For example,
12488 3-2-5 --> 2003-02-05
12489 feb 15 --> currentyear-02-15
12490 sep 12 9 --> 2009-09-12
12491 12:45 --> today 12:45
12492 22 sept 0:34 --> currentyear-09-22 0:34
12493 12 --> currentyear-currentmonth-12
12494 Fri --> nearest Friday (today or later)
12495 etc.
12497 Furthermore you can specify a relative date by giving, as the *first* thing
12498 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12499 change in days weeks, months, years.
12500 With a single plus or minus, the date is relative to today. With a double
12501 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12502 +4d --> four days from today
12503 +4 --> same as above
12504 +2w --> two weeks from today
12505 ++5 --> five days from default date
12507 The function understands only English month and weekday abbreviations,
12508 but this can be configured with the variables `parse-time-months' and
12509 `parse-time-weekdays'.
12511 While prompting, a calendar is popped up - you can also select the
12512 date with the mouse (button 1). The calendar shows a period of three
12513 months. To scroll it to other months, use the keys `>' and `<'.
12514 If you don't like the calendar, turn it off with
12515 \(setq org-read-date-popup-calendar nil)
12517 With optional argument TO-TIME, the date will immediately be converted
12518 to an internal time.
12519 With an optional argument WITH-TIME, the prompt will suggest to also
12520 insert a time. Note that when WITH-TIME is not set, you can still
12521 enter a time, and this function will inform the calling routine about
12522 this change. The calling routine may then choose to change the format
12523 used to insert the time stamp into the buffer to include the time.
12524 With optional argument FROM-STRING, read from this string instead from
12525 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12526 the time/date that is used for everything that is not specified by the
12527 user."
12528 (require 'parse-time)
12529 (let* ((org-time-stamp-rounding-minutes
12530 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12531 (org-dcst org-display-custom-times)
12532 (ct (org-current-time))
12533 (def (or org-overriding-default-time default-time ct))
12534 (defdecode (decode-time def))
12535 (dummy (progn
12536 (when (< (nth 2 defdecode) org-extend-today-until)
12537 (setcar (nthcdr 2 defdecode) -1)
12538 (setcar (nthcdr 1 defdecode) 59)
12539 (setq def (apply 'encode-time defdecode)
12540 defdecode (decode-time def)))))
12541 (calendar-frame-setup nil)
12542 (calendar-move-hook nil)
12543 (calendar-view-diary-initially-flag nil)
12544 (view-diary-entries-initially nil)
12545 (calendar-view-holidays-initially-flag nil)
12546 (view-calendar-holidays-initially nil)
12547 (timestr (format-time-string
12548 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12549 (prompt (concat (if prompt (concat prompt " ") "")
12550 (format "Date+time [%s]: " timestr)))
12551 ans (org-ans0 "") org-ans1 org-ans2 final)
12553 (cond
12554 (from-string (setq ans from-string))
12555 (org-read-date-popup-calendar
12556 (save-excursion
12557 (save-window-excursion
12558 (calendar)
12559 (calendar-forward-day (- (time-to-days def)
12560 (calendar-absolute-from-gregorian
12561 (calendar-current-date))))
12562 (org-eval-in-calendar nil t)
12563 (let* ((old-map (current-local-map))
12564 (map (copy-keymap calendar-mode-map))
12565 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12566 (org-defkey map (kbd "RET") 'org-calendar-select)
12567 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12568 'org-calendar-select-mouse)
12569 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12570 'org-calendar-select-mouse)
12571 (org-defkey minibuffer-local-map [(meta shift left)]
12572 (lambda () (interactive)
12573 (org-eval-in-calendar '(calendar-backward-month 1))))
12574 (org-defkey minibuffer-local-map [(meta shift right)]
12575 (lambda () (interactive)
12576 (org-eval-in-calendar '(calendar-forward-month 1))))
12577 (org-defkey minibuffer-local-map [(meta shift up)]
12578 (lambda () (interactive)
12579 (org-eval-in-calendar '(calendar-backward-year 1))))
12580 (org-defkey minibuffer-local-map [(meta shift down)]
12581 (lambda () (interactive)
12582 (org-eval-in-calendar '(calendar-forward-year 1))))
12583 (org-defkey minibuffer-local-map [?\e (shift left)]
12584 (lambda () (interactive)
12585 (org-eval-in-calendar '(calendar-backward-month 1))))
12586 (org-defkey minibuffer-local-map [?\e (shift right)]
12587 (lambda () (interactive)
12588 (org-eval-in-calendar '(calendar-forward-month 1))))
12589 (org-defkey minibuffer-local-map [?\e (shift up)]
12590 (lambda () (interactive)
12591 (org-eval-in-calendar '(calendar-backward-year 1))))
12592 (org-defkey minibuffer-local-map [?\e (shift down)]
12593 (lambda () (interactive)
12594 (org-eval-in-calendar '(calendar-forward-year 1))))
12595 (org-defkey minibuffer-local-map [(shift up)]
12596 (lambda () (interactive)
12597 (org-eval-in-calendar '(calendar-backward-week 1))))
12598 (org-defkey minibuffer-local-map [(shift down)]
12599 (lambda () (interactive)
12600 (org-eval-in-calendar '(calendar-forward-week 1))))
12601 (org-defkey minibuffer-local-map [(shift left)]
12602 (lambda () (interactive)
12603 (org-eval-in-calendar '(calendar-backward-day 1))))
12604 (org-defkey minibuffer-local-map [(shift right)]
12605 (lambda () (interactive)
12606 (org-eval-in-calendar '(calendar-forward-day 1))))
12607 (org-defkey minibuffer-local-map ">"
12608 (lambda () (interactive)
12609 (org-eval-in-calendar '(scroll-calendar-left 1))))
12610 (org-defkey minibuffer-local-map "<"
12611 (lambda () (interactive)
12612 (org-eval-in-calendar '(scroll-calendar-right 1))))
12613 (run-hooks 'org-read-date-minibuffer-setup-hook)
12614 (unwind-protect
12615 (progn
12616 (use-local-map map)
12617 (add-hook 'post-command-hook 'org-read-date-display)
12618 (setq org-ans0 (read-string prompt default-input
12619 'org-read-date-history nil))
12620 ;; org-ans0: from prompt
12621 ;; org-ans1: from mouse click
12622 ;; org-ans2: from calendar motion
12623 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12624 (remove-hook 'post-command-hook 'org-read-date-display)
12625 (use-local-map old-map)
12626 (when org-read-date-overlay
12627 (org-delete-overlay org-read-date-overlay)
12628 (setq org-read-date-overlay nil)))))))
12630 (t ; Naked prompt only
12631 (unwind-protect
12632 (setq ans (read-string prompt default-input
12633 'org-read-date-history timestr))
12634 (when org-read-date-overlay
12635 (org-delete-overlay org-read-date-overlay)
12636 (setq org-read-date-overlay nil)))))
12638 (setq final (org-read-date-analyze ans def defdecode))
12639 (setq org-read-date-final-answer ans)
12641 (if to-time
12642 (apply 'encode-time final)
12643 (if (and (boundp 'org-time-was-given) org-time-was-given)
12644 (format "%04d-%02d-%02d %02d:%02d"
12645 (nth 5 final) (nth 4 final) (nth 3 final)
12646 (nth 2 final) (nth 1 final))
12647 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12649 (defvar def)
12650 (defvar defdecode)
12651 (defvar with-time)
12652 (defun org-read-date-display ()
12653 "Display the current date prompt interpretation in the minibuffer."
12654 (when org-read-date-display-live
12655 (when org-read-date-overlay
12656 (org-delete-overlay org-read-date-overlay))
12657 (let ((p (point)))
12658 (end-of-line 1)
12659 (while (not (equal (buffer-substring
12660 (max (point-min) (- (point) 4)) (point))
12661 " "))
12662 (insert " "))
12663 (goto-char p))
12664 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12665 " " (or org-ans1 org-ans2)))
12666 (org-end-time-was-given nil)
12667 (f (org-read-date-analyze ans def defdecode))
12668 (fmts (if org-dcst
12669 org-time-stamp-custom-formats
12670 org-time-stamp-formats))
12671 (fmt (if (or with-time
12672 (and (boundp 'org-time-was-given) org-time-was-given))
12673 (cdr fmts)
12674 (car fmts)))
12675 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12676 (when (and org-end-time-was-given
12677 (string-match org-plain-time-of-day-regexp txt))
12678 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12679 org-end-time-was-given
12680 (substring txt (match-end 0)))))
12681 (setq org-read-date-overlay
12682 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12683 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12685 (defun org-read-date-analyze (ans def defdecode)
12686 "Analyse the combined answer of the date prompt."
12687 ;; FIXME: cleanup and comment
12688 (let (delta deltan deltaw deltadef year month day
12689 hour minute second wday pm h2 m2 tl wday1
12690 iso-year iso-weekday iso-week iso-year iso-date)
12692 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12693 (setq ans "+0"))
12695 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12696 (setq ans (replace-match "" t t ans)
12697 deltan (car delta)
12698 deltaw (nth 1 delta)
12699 deltadef (nth 2 delta)))
12701 ;; Check if there is an iso week date in there
12702 ;; If yes, sore the info and postpone interpreting it until the rest
12703 ;; of the parsing is done
12704 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12705 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12706 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12707 iso-week (string-to-number (match-string 2 ans)))
12708 (setq ans (replace-match "" t t ans)))
12710 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12711 (when (string-match
12712 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12713 (setq year (if (match-end 2)
12714 (string-to-number (match-string 2 ans))
12715 (string-to-number (format-time-string "%Y")))
12716 month (string-to-number (match-string 3 ans))
12717 day (string-to-number (match-string 4 ans)))
12718 (if (< year 100) (setq year (+ 2000 year)))
12719 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12720 t nil ans)))
12721 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12722 ;; If there is a time with am/pm, and *no* time without it, we convert
12723 ;; so that matching will be successful.
12724 (loop for i from 1 to 2 do ; twice, for end time as well
12725 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12726 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12727 (setq hour (string-to-number (match-string 1 ans))
12728 minute (if (match-end 3)
12729 (string-to-number (match-string 3 ans))
12731 pm (equal ?p
12732 (string-to-char (downcase (match-string 4 ans)))))
12733 (if (and (= hour 12) (not pm))
12734 (setq hour 0)
12735 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12736 (setq ans (replace-match (format "%02d:%02d" hour minute)
12737 t t ans))))
12739 ;; Check if a time range is given as a duration
12740 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12741 (setq hour (string-to-number (match-string 1 ans))
12742 h2 (+ hour (string-to-number (match-string 3 ans)))
12743 minute (string-to-number (match-string 2 ans))
12744 m2 (+ minute (if (match-end 5) (string-to-number
12745 (match-string 5 ans))0)))
12746 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12747 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12748 t t ans)))
12750 ;; Check if there is a time range
12751 (when (boundp 'org-end-time-was-given)
12752 (setq org-time-was-given nil)
12753 (when (and (string-match org-plain-time-of-day-regexp ans)
12754 (match-end 8))
12755 (setq org-end-time-was-given (match-string 8 ans))
12756 (setq ans (concat (substring ans 0 (match-beginning 7))
12757 (substring ans (match-end 7))))))
12759 (setq tl (parse-time-string ans)
12760 day (or (nth 3 tl) (nth 3 defdecode))
12761 month (or (nth 4 tl)
12762 (if (and org-read-date-prefer-future
12763 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12764 (1+ (nth 4 defdecode))
12765 (nth 4 defdecode)))
12766 year (or (nth 5 tl)
12767 (if (and org-read-date-prefer-future
12768 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12769 (1+ (nth 5 defdecode))
12770 (nth 5 defdecode)))
12771 hour (or (nth 2 tl) (nth 2 defdecode))
12772 minute (or (nth 1 tl) (nth 1 defdecode))
12773 second (or (nth 0 tl) 0)
12774 wday (nth 6 tl))
12776 ;; Special date definitions below
12777 (cond
12778 (iso-week
12779 ;; There was an iso week
12780 (setq year (or iso-year year)
12781 day (or iso-weekday wday 1)
12782 wday nil ; to make sure that the trigger below does not match
12783 iso-date (calendar-gregorian-from-absolute
12784 (calendar-absolute-from-iso
12785 (list iso-week day year))))
12786 ; FIXME: Should we also push ISO weeks into the future?
12787 ; (when (and org-read-date-prefer-future
12788 ; (not iso-year)
12789 ; (< (calendar-absolute-from-gregorian iso-date)
12790 ; (time-to-days (current-time))))
12791 ; (setq year (1+ year)
12792 ; iso-date (calendar-gregorian-from-absolute
12793 ; (calendar-absolute-from-iso
12794 ; (list iso-week day year)))))
12795 (setq month (car iso-date)
12796 year (nth 2 iso-date)
12797 day (nth 1 iso-date)))
12798 (deltan
12799 (unless deltadef
12800 (let ((now (decode-time (current-time))))
12801 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12802 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12803 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12804 ((equal deltaw "m") (setq month (+ month deltan)))
12805 ((equal deltaw "y") (setq year (+ year deltan)))))
12806 ((and wday (not (nth 3 tl)))
12807 ;; Weekday was given, but no day, so pick that day in the week
12808 ;; on or after the derived date.
12809 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12810 (unless (equal wday wday1)
12811 (setq day (+ day (% (- wday wday1 -7) 7))))))
12812 (if (and (boundp 'org-time-was-given)
12813 (nth 2 tl))
12814 (setq org-time-was-given t))
12815 (if (< year 100) (setq year (+ 2000 year)))
12816 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12817 (list second minute hour day month year)))
12819 (defvar parse-time-weekdays)
12821 (defun org-read-date-get-relative (s today default)
12822 "Check string S for special relative date string.
12823 TODAY and DEFAULT are internal times, for today and for a default.
12824 Return shift list (N what def-flag)
12825 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12826 N is the number of WHATs to shift.
12827 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12828 the DEFAULT date rather than TODAY."
12829 (when (and
12830 (string-match
12831 (concat
12832 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12833 "\\([0-9]+\\)?"
12834 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12835 "\\([ \t]\\|$\\)") s)
12836 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12837 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12838 (string-to-char (substring (match-string 1 s) -1))
12839 ?+))
12840 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12841 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12842 (what (if (match-end 3) (match-string 3 s) "d"))
12843 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12844 (date (if rel default today))
12845 (wday (nth 6 (decode-time date)))
12846 delta)
12847 (if wday1
12848 (progn
12849 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12850 (if (= dir ?-) (setq delta (- delta 7)))
12851 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12852 (list delta "d" rel))
12853 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12855 (defun org-eval-in-calendar (form &optional keepdate)
12856 "Eval FORM in the calendar window and return to current window.
12857 Also, store the cursor date in variable org-ans2."
12858 (let ((sf (selected-frame))
12859 (sw (selected-window)))
12860 (select-window (get-buffer-window "*Calendar*" t))
12861 (eval form)
12862 (when (and (not keepdate) (calendar-cursor-to-date))
12863 (let* ((date (calendar-cursor-to-date))
12864 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12865 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12866 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12867 (select-window sw)
12868 (org-select-frame-set-input-focus sf)))
12870 (defun org-calendar-select ()
12871 "Return to `org-read-date' with the date currently selected.
12872 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12873 (interactive)
12874 (when (calendar-cursor-to-date)
12875 (let* ((date (calendar-cursor-to-date))
12876 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12877 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12878 (if (active-minibuffer-window) (exit-minibuffer))))
12880 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12881 "Insert a date stamp for the date given by the internal TIME.
12882 WITH-HM means, use the stamp format that includes the time of the day.
12883 INACTIVE means use square brackets instead of angular ones, so that the
12884 stamp will not contribute to the agenda.
12885 PRE and POST are optional strings to be inserted before and after the
12886 stamp.
12887 The command returns the inserted time stamp."
12888 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12889 stamp)
12890 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12891 (insert-before-markers (or pre ""))
12892 (insert-before-markers (setq stamp (format-time-string fmt time)))
12893 (when (listp extra)
12894 (setq extra (car extra))
12895 (if (and (stringp extra)
12896 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12897 (setq extra (format "-%02d:%02d"
12898 (string-to-number (match-string 1 extra))
12899 (string-to-number (match-string 2 extra))))
12900 (setq extra nil)))
12901 (when extra
12902 (backward-char 1)
12903 (insert-before-markers extra)
12904 (forward-char 1))
12905 (insert-before-markers (or post ""))
12906 (setq org-last-inserted-timestamp stamp)))
12908 (defun org-toggle-time-stamp-overlays ()
12909 "Toggle the use of custom time stamp formats."
12910 (interactive)
12911 (setq org-display-custom-times (not org-display-custom-times))
12912 (unless org-display-custom-times
12913 (let ((p (point-min)) (bmp (buffer-modified-p)))
12914 (while (setq p (next-single-property-change p 'display))
12915 (if (and (get-text-property p 'display)
12916 (eq (get-text-property p 'face) 'org-date))
12917 (remove-text-properties
12918 p (setq p (next-single-property-change p 'display))
12919 '(display t))))
12920 (set-buffer-modified-p bmp)))
12921 (if (featurep 'xemacs)
12922 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12923 (org-restart-font-lock)
12924 (setq org-table-may-need-update t)
12925 (if org-display-custom-times
12926 (message "Time stamps are overlayed with custom format")
12927 (message "Time stamp overlays removed")))
12929 (defun org-display-custom-time (beg end)
12930 "Overlay modified time stamp format over timestamp between BEG and END."
12931 (let* ((ts (buffer-substring beg end))
12932 t1 w1 with-hm tf time str w2 (off 0))
12933 (save-match-data
12934 (setq t1 (org-parse-time-string ts t))
12935 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12936 (setq off (- (match-end 0) (match-beginning 0)))))
12937 (setq end (- end off))
12938 (setq w1 (- end beg)
12939 with-hm (and (nth 1 t1) (nth 2 t1))
12940 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12941 time (org-fix-decoded-time t1)
12942 str (org-add-props
12943 (format-time-string
12944 (substring tf 1 -1) (apply 'encode-time time))
12945 nil 'mouse-face 'highlight)
12946 w2 (length str))
12947 (if (not (= w2 w1))
12948 (add-text-properties (1+ beg) (+ 2 beg)
12949 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12950 (if (featurep 'xemacs)
12951 (progn
12952 (put-text-property beg end 'invisible t)
12953 (put-text-property beg end 'end-glyph (make-glyph str)))
12954 (put-text-property beg end 'display str))))
12956 (defun org-translate-time (string)
12957 "Translate all timestamps in STRING to custom format.
12958 But do this only if the variable `org-display-custom-times' is set."
12959 (when org-display-custom-times
12960 (save-match-data
12961 (let* ((start 0)
12962 (re org-ts-regexp-both)
12963 t1 with-hm inactive tf time str beg end)
12964 (while (setq start (string-match re string start))
12965 (setq beg (match-beginning 0)
12966 end (match-end 0)
12967 t1 (save-match-data
12968 (org-parse-time-string (substring string beg end) t))
12969 with-hm (and (nth 1 t1) (nth 2 t1))
12970 inactive (equal (substring string beg (1+ beg)) "[")
12971 tf (funcall (if with-hm 'cdr 'car)
12972 org-time-stamp-custom-formats)
12973 time (org-fix-decoded-time t1)
12974 str (format-time-string
12975 (concat
12976 (if inactive "[" "<") (substring tf 1 -1)
12977 (if inactive "]" ">"))
12978 (apply 'encode-time time))
12979 string (replace-match str t t string)
12980 start (+ start (length str)))))))
12981 string)
12983 (defun org-fix-decoded-time (time)
12984 "Set 0 instead of nil for the first 6 elements of time.
12985 Don't touch the rest."
12986 (let ((n 0))
12987 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12989 (defun org-days-to-time (timestamp-string)
12990 "Difference between TIMESTAMP-STRING and now in days."
12991 (- (time-to-days (org-time-string-to-time timestamp-string))
12992 (time-to-days (current-time))))
12994 (defun org-deadline-close (timestamp-string &optional ndays)
12995 "Is the time in TIMESTAMP-STRING close to the current date?"
12996 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12997 (and (< (org-days-to-time timestamp-string) ndays)
12998 (not (org-entry-is-done-p))))
13000 (defun org-get-wdays (ts)
13001 "Get the deadline lead time appropriate for timestring TS."
13002 (cond
13003 ((<= org-deadline-warning-days 0)
13004 ;; 0 or negative, enforce this value no matter what
13005 (- org-deadline-warning-days))
13006 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13007 ;; lead time is specified.
13008 (floor (* (string-to-number (match-string 1 ts))
13009 (cdr (assoc (match-string 2 ts)
13010 '(("d" . 1) ("w" . 7)
13011 ("m" . 30.4) ("y" . 365.25)))))))
13012 ;; go for the default.
13013 (t org-deadline-warning-days)))
13015 (defun org-calendar-select-mouse (ev)
13016 "Return to `org-read-date' with the date currently selected.
13017 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13018 (interactive "e")
13019 (mouse-set-point ev)
13020 (when (calendar-cursor-to-date)
13021 (let* ((date (calendar-cursor-to-date))
13022 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13023 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13024 (if (active-minibuffer-window) (exit-minibuffer))))
13026 (defun org-check-deadlines (ndays)
13027 "Check if there are any deadlines due or past due.
13028 A deadline is considered due if it happens within `org-deadline-warning-days'
13029 days from today's date. If the deadline appears in an entry marked DONE,
13030 it is not shown. The prefix arg NDAYS can be used to test that many
13031 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13032 (interactive "P")
13033 (let* ((org-warn-days
13034 (cond
13035 ((equal ndays '(4)) 100000)
13036 (ndays (prefix-numeric-value ndays))
13037 (t (abs org-deadline-warning-days))))
13038 (case-fold-search nil)
13039 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13040 (callback
13041 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13043 (message "%d deadlines past-due or due within %d days"
13044 (org-occur regexp nil callback)
13045 org-warn-days)))
13047 (defun org-check-before-date (date)
13048 "Check if there are deadlines or scheduled entries before DATE."
13049 (interactive (list (org-read-date)))
13050 (let ((case-fold-search nil)
13051 (regexp (concat "\\<\\(" org-deadline-string
13052 "\\|" org-scheduled-string
13053 "\\) *<\\([^>]+\\)>"))
13054 (callback
13055 (lambda () (time-less-p
13056 (org-time-string-to-time (match-string 2))
13057 (org-time-string-to-time date)))))
13058 (message "%d entries before %s"
13059 (org-occur regexp nil callback) date)))
13061 (defun org-check-after-date (date)
13062 "Check if there are deadlines or scheduled entries after DATE."
13063 (interactive (list (org-read-date)))
13064 (let ((case-fold-search nil)
13065 (regexp (concat "\\<\\(" org-deadline-string
13066 "\\|" org-scheduled-string
13067 "\\) *<\\([^>]+\\)>"))
13068 (callback
13069 (lambda () (not
13070 (time-less-p
13071 (org-time-string-to-time (match-string 2))
13072 (org-time-string-to-time date))))))
13073 (message "%d entries after %s"
13074 (org-occur regexp nil callback) date)))
13076 (defun org-evaluate-time-range (&optional to-buffer)
13077 "Evaluate a time range by computing the difference between start and end.
13078 Normally the result is just printed in the echo area, but with prefix arg
13079 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13080 If the time range is actually in a table, the result is inserted into the
13081 next column.
13082 For time difference computation, a year is assumed to be exactly 365
13083 days in order to avoid rounding problems."
13084 (interactive "P")
13086 (org-clock-update-time-maybe)
13087 (save-excursion
13088 (unless (org-at-date-range-p t)
13089 (goto-char (point-at-bol))
13090 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13091 (if (not (org-at-date-range-p t))
13092 (error "Not at a time-stamp range, and none found in current line")))
13093 (let* ((ts1 (match-string 1))
13094 (ts2 (match-string 2))
13095 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13096 (match-end (match-end 0))
13097 (time1 (org-time-string-to-time ts1))
13098 (time2 (org-time-string-to-time ts2))
13099 (t1 (org-float-time time1))
13100 (t2 (org-float-time time2))
13101 (diff (abs (- t2 t1)))
13102 (negative (< (- t2 t1) 0))
13103 ;; (ys (floor (* 365 24 60 60)))
13104 (ds (* 24 60 60))
13105 (hs (* 60 60))
13106 (fy "%dy %dd %02d:%02d")
13107 (fy1 "%dy %dd")
13108 (fd "%dd %02d:%02d")
13109 (fd1 "%dd")
13110 (fh "%02d:%02d")
13111 y d h m align)
13112 (if havetime
13113 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13115 d (floor (/ diff ds)) diff (mod diff ds)
13116 h (floor (/ diff hs)) diff (mod diff hs)
13117 m (floor (/ diff 60)))
13118 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13120 d (floor (+ (/ diff ds) 0.5))
13121 h 0 m 0))
13122 (if (not to-buffer)
13123 (message "%s" (org-make-tdiff-string y d h m))
13124 (if (org-at-table-p)
13125 (progn
13126 (goto-char match-end)
13127 (setq align t)
13128 (and (looking-at " *|") (goto-char (match-end 0))))
13129 (goto-char match-end))
13130 (if (looking-at
13131 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13132 (replace-match ""))
13133 (if negative (insert " -"))
13134 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13135 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13136 (insert " " (format fh h m))))
13137 (if align (org-table-align))
13138 (message "Time difference inserted")))))
13140 (defun org-make-tdiff-string (y d h m)
13141 (let ((fmt "")
13142 (l nil))
13143 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13144 l (push y l)))
13145 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13146 l (push d l)))
13147 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13148 l (push h l)))
13149 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13150 l (push m l)))
13151 (apply 'format fmt (nreverse l))))
13153 (defun org-time-string-to-time (s)
13154 (apply 'encode-time (org-parse-time-string s)))
13155 (defun org-time-string-to-seconds (s)
13156 (org-float-time (org-time-string-to-time s)))
13158 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13159 "Convert a time stamp to an absolute day number.
13160 If there is a specifyer for a cyclic time stamp, get the closest date to
13161 DAYNR.
13162 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13163 the variable date is bound by the calendar when this is called."
13164 (cond
13165 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13166 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13167 daynr
13168 (+ daynr 1000)))
13169 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13170 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13171 (time-to-days (current-time))) (match-string 0 s)
13172 prefer show-all))
13173 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13175 (defun org-days-to-iso-week (days)
13176 "Return the iso week number."
13177 (require 'cal-iso)
13178 (car (calendar-iso-from-absolute days)))
13180 (defun org-small-year-to-year (year)
13181 "Convert 2-digit years into 4-digit years.
13182 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13183 The year 2000 cannot be abbreviated. Any year larger than 99
13184 is returned unchanged."
13185 (if (< year 38)
13186 (setq year (+ 2000 year))
13187 (if (< year 100)
13188 (setq year (+ 1900 year))))
13189 year)
13191 (defun org-time-from-absolute (d)
13192 "Return the time corresponding to date D.
13193 D may be an absolute day number, or a calendar-type list (month day year)."
13194 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13195 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13197 (defun org-calendar-holiday ()
13198 "List of holidays, for Diary display in Org-mode."
13199 (require 'holidays)
13200 (let ((hl (funcall
13201 (if (fboundp 'calendar-check-holidays)
13202 'calendar-check-holidays 'check-calendar-holidays) date)))
13203 (if hl (mapconcat 'identity hl "; "))))
13205 (defun org-diary-sexp-entry (sexp entry date)
13206 "Process a SEXP diary ENTRY for DATE."
13207 (require 'diary-lib)
13208 (let ((result (if calendar-debug-sexp
13209 (let ((stack-trace-on-error t))
13210 (eval (car (read-from-string sexp))))
13211 (condition-case nil
13212 (eval (car (read-from-string sexp)))
13213 (error
13214 (beep)
13215 (message "Bad sexp at line %d in %s: %s"
13216 (org-current-line)
13217 (buffer-file-name) sexp)
13218 (sleep-for 2))))))
13219 (cond ((stringp result) result)
13220 ((and (consp result)
13221 (stringp (cdr result))) (cdr result))
13222 (result entry)
13223 (t nil))))
13225 (defun org-diary-to-ical-string (frombuf)
13226 "Get iCalendar entries from diary entries in buffer FROMBUF.
13227 This uses the icalendar.el library."
13228 (let* ((tmpdir (if (featurep 'xemacs)
13229 (temp-directory)
13230 temporary-file-directory))
13231 (tmpfile (make-temp-name
13232 (expand-file-name "orgics" tmpdir)))
13233 buf rtn b e)
13234 (save-excursion
13235 (set-buffer frombuf)
13236 (icalendar-export-region (point-min) (point-max) tmpfile)
13237 (setq buf (find-buffer-visiting tmpfile))
13238 (set-buffer buf)
13239 (goto-char (point-min))
13240 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13241 (setq b (match-beginning 0)))
13242 (goto-char (point-max))
13243 (if (re-search-backward "^END:VEVENT" nil t)
13244 (setq e (match-end 0)))
13245 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13246 (kill-buffer buf)
13247 (delete-file tmpfile)
13248 rtn))
13250 (defun org-closest-date (start current change prefer show-all)
13251 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13252 When PREFER is `past' return a date that is either CURRENT or past.
13253 When PREFER is `future', return a date that is either CURRENT or future.
13254 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13255 ;; Make the proper lists from the dates
13256 (catch 'exit
13257 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13258 dn dw sday cday n1 n2 n0
13259 d m y y1 y2 date1 date2 nmonths nm ny m2)
13261 (setq start (org-date-to-gregorian start)
13262 current (org-date-to-gregorian
13263 (if show-all
13264 current
13265 (time-to-days (current-time))))
13266 sday (calendar-absolute-from-gregorian start)
13267 cday (calendar-absolute-from-gregorian current))
13269 (if (<= cday sday) (throw 'exit sday))
13271 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13272 (setq dn (string-to-number (match-string 1 change))
13273 dw (cdr (assoc (match-string 2 change) a1)))
13274 (error "Invalid change specifyer: %s" change))
13275 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13276 (cond
13277 ((eq dw 'day)
13278 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13279 n2 (+ n1 dn)))
13280 ((eq dw 'year)
13281 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13282 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13283 (setq date1 (list m d y1)
13284 n1 (calendar-absolute-from-gregorian date1)
13285 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13286 n2 (calendar-absolute-from-gregorian date2)))
13287 ((eq dw 'month)
13288 ;; approx number of month between the two dates
13289 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13290 ;; How often does dn fit in there?
13291 (setq d (nth 1 start) m (car start) y (nth 2 start)
13292 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13293 m (+ m nm)
13294 ny (floor (/ m 12))
13295 y (+ y ny)
13296 m (- m (* ny 12)))
13297 (while (> m 12) (setq m (- m 12) y (1+ y)))
13298 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13299 (setq m2 (+ m dn) y2 y)
13300 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13301 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13302 (while (<= n2 cday)
13303 (setq n1 n2 m m2 y y2)
13304 (setq m2 (+ m dn) y2 y)
13305 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13306 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13307 ;; Make sure n1 is the earlier date
13308 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13309 (if show-all
13310 (cond
13311 ((eq prefer 'past) (if (= cday n2) n2 n1))
13312 ((eq prefer 'future) (if (= cday n1) n1 n2))
13313 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13314 (cond
13315 ((eq prefer 'past) (if (= cday n2) n2 n1))
13316 ((eq prefer 'future) (if (= cday n1) n1 n2))
13317 (t (if (= cday n1) n1 n2)))))))
13319 (defun org-date-to-gregorian (date)
13320 "Turn any specification of DATE into a gregorian date for the calendar."
13321 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13322 ((and (listp date) (= (length date) 3)) date)
13323 ((stringp date)
13324 (setq date (org-parse-time-string date))
13325 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13326 ((listp date)
13327 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13329 (defun org-parse-time-string (s &optional nodefault)
13330 "Parse the standard Org-mode time string.
13331 This should be a lot faster than the normal `parse-time-string'.
13332 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13333 hour and minute fields will be nil if not given."
13334 (if (string-match org-ts-regexp0 s)
13335 (list 0
13336 (if (or (match-beginning 8) (not nodefault))
13337 (string-to-number (or (match-string 8 s) "0")))
13338 (if (or (match-beginning 7) (not nodefault))
13339 (string-to-number (or (match-string 7 s) "0")))
13340 (string-to-number (match-string 4 s))
13341 (string-to-number (match-string 3 s))
13342 (string-to-number (match-string 2 s))
13343 nil nil nil)
13344 (error "Not a standard Org-mode time string: %s" s)))
13346 (defun org-timestamp-up (&optional arg)
13347 "Increase the date item at the cursor by one.
13348 If the cursor is on the year, change the year. If it is on the month or
13349 the day, change that.
13350 With prefix ARG, change by that many units."
13351 (interactive "p")
13352 (org-timestamp-change (prefix-numeric-value arg)))
13354 (defun org-timestamp-down (&optional arg)
13355 "Decrease the date item at the cursor by one.
13356 If the cursor is on the year, change the year. If it is on the month or
13357 the day, change that.
13358 With prefix ARG, change by that many units."
13359 (interactive "p")
13360 (org-timestamp-change (- (prefix-numeric-value arg))))
13362 (defun org-timestamp-up-day (&optional arg)
13363 "Increase the date in the time stamp by one day.
13364 With prefix ARG, change that many days."
13365 (interactive "p")
13366 (if (and (not (org-at-timestamp-p t))
13367 (org-on-heading-p))
13368 (org-todo 'up)
13369 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13371 (defun org-timestamp-down-day (&optional arg)
13372 "Decrease the date in the time stamp by one day.
13373 With prefix ARG, change that many days."
13374 (interactive "p")
13375 (if (and (not (org-at-timestamp-p t))
13376 (org-on-heading-p))
13377 (org-todo 'down)
13378 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13380 (defun org-at-timestamp-p (&optional inactive-ok)
13381 "Determine if the cursor is in or at a timestamp."
13382 (interactive)
13383 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13384 (pos (point))
13385 (ans (or (looking-at tsr)
13386 (save-excursion
13387 (skip-chars-backward "^[<\n\r\t")
13388 (if (> (point) (point-min)) (backward-char 1))
13389 (and (looking-at tsr)
13390 (> (- (match-end 0) pos) -1))))))
13391 (and ans
13392 (boundp 'org-ts-what)
13393 (setq org-ts-what
13394 (cond
13395 ((= pos (match-beginning 0)) 'bracket)
13396 ((= pos (1- (match-end 0))) 'bracket)
13397 ((org-pos-in-match-range pos 2) 'year)
13398 ((org-pos-in-match-range pos 3) 'month)
13399 ((org-pos-in-match-range pos 7) 'hour)
13400 ((org-pos-in-match-range pos 8) 'minute)
13401 ((or (org-pos-in-match-range pos 4)
13402 (org-pos-in-match-range pos 5)) 'day)
13403 ((and (> pos (or (match-end 8) (match-end 5)))
13404 (< pos (match-end 0)))
13405 (- pos (or (match-end 8) (match-end 5))))
13406 (t 'day))))
13407 ans))
13409 (defun org-toggle-timestamp-type ()
13410 "Toggle the type (<active> or [inactive]) of a time stamp."
13411 (interactive)
13412 (when (org-at-timestamp-p t)
13413 (let ((beg (match-beginning 0)) (end (match-end 0))
13414 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13415 (save-excursion
13416 (goto-char beg)
13417 (while (re-search-forward "[][<>]" end t)
13418 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13419 t t)))
13420 (message "Timestamp is now %sactive"
13421 (if (equal (char-after beg) ?<) "" "in")))))
13423 (defun org-timestamp-change (n &optional what)
13424 "Change the date in the time stamp at point.
13425 The date will be changed by N times WHAT. WHAT can be `day', `month',
13426 `year', `minute', `second'. If WHAT is not given, the cursor position
13427 in the timestamp determines what will be changed."
13428 (let ((pos (point))
13429 with-hm inactive
13430 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13431 org-ts-what
13432 extra rem
13433 ts time time0)
13434 (if (not (org-at-timestamp-p t))
13435 (error "Not at a timestamp"))
13436 (if (and (not what) (eq org-ts-what 'bracket))
13437 (org-toggle-timestamp-type)
13438 (if (and (not what) (not (eq org-ts-what 'day))
13439 org-display-custom-times
13440 (get-text-property (point) 'display)
13441 (not (get-text-property (1- (point)) 'display)))
13442 (setq org-ts-what 'day))
13443 (setq org-ts-what (or what org-ts-what)
13444 inactive (= (char-after (match-beginning 0)) ?\[)
13445 ts (match-string 0))
13446 (replace-match "")
13447 (if (string-match
13448 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13450 (setq extra (match-string 1 ts)))
13451 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13452 (setq with-hm t))
13453 (setq time0 (org-parse-time-string ts))
13454 (when (and (eq org-ts-what 'minute)
13455 (eq current-prefix-arg nil))
13456 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13457 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13458 (setcar (cdr time0) (+ (nth 1 time0)
13459 (if (> n 0) (- rem) (- dm rem))))))
13460 (setq time
13461 (encode-time (or (car time0) 0)
13462 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13463 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13464 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13465 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13466 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13467 (nthcdr 6 time0)))
13468 (when (and (member org-ts-what '(hour minute))
13469 extra
13470 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13471 (setq extra (org-modify-ts-extra
13472 extra
13473 (if (eq org-ts-what 'hour) 2 5)
13474 n dm)))
13475 (when (integerp org-ts-what)
13476 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13477 (if (eq what 'calendar)
13478 (let ((cal-date (org-get-date-from-calendar)))
13479 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13480 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13481 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13482 (setcar time0 (or (car time0) 0))
13483 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13484 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13485 (setq time (apply 'encode-time time0))))
13486 (setq org-last-changed-timestamp
13487 (org-insert-time-stamp time with-hm inactive nil nil extra))
13488 (org-clock-update-time-maybe)
13489 (goto-char pos)
13490 ;; Try to recenter the calendar window, if any
13491 (if (and org-calendar-follow-timestamp-change
13492 (get-buffer-window "*Calendar*" t)
13493 (memq org-ts-what '(day month year)))
13494 (org-recenter-calendar (time-to-days time))))))
13496 (defun org-modify-ts-extra (s pos n dm)
13497 "Change the different parts of the lead-time and repeat fields in timestamp."
13498 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13499 ng h m new rem)
13500 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13501 (cond
13502 ((or (org-pos-in-match-range pos 2)
13503 (org-pos-in-match-range pos 3))
13504 (setq m (string-to-number (match-string 3 s))
13505 h (string-to-number (match-string 2 s)))
13506 (if (org-pos-in-match-range pos 2)
13507 (setq h (+ h n))
13508 (setq n (* dm (org-no-warnings (signum n))))
13509 (when (not (= 0 (setq rem (% m dm))))
13510 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13511 (setq m (+ m n)))
13512 (if (< m 0) (setq m (+ m 60) h (1- h)))
13513 (if (> m 59) (setq m (- m 60) h (1+ h)))
13514 (setq h (min 24 (max 0 h)))
13515 (setq ng 1 new (format "-%02d:%02d" h m)))
13516 ((org-pos-in-match-range pos 6)
13517 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13518 ((org-pos-in-match-range pos 5)
13519 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13521 ((org-pos-in-match-range pos 9)
13522 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13523 ((org-pos-in-match-range pos 8)
13524 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13526 (when ng
13527 (setq s (concat
13528 (substring s 0 (match-beginning ng))
13530 (substring s (match-end ng))))))
13533 (defun org-recenter-calendar (date)
13534 "If the calendar is visible, recenter it to DATE."
13535 (let* ((win (selected-window))
13536 (cwin (get-buffer-window "*Calendar*" t))
13537 (calendar-move-hook nil))
13538 (when cwin
13539 (select-window cwin)
13540 (calendar-goto-date (if (listp date) date
13541 (calendar-gregorian-from-absolute date)))
13542 (select-window win))))
13544 (defun org-goto-calendar (&optional arg)
13545 "Go to the Emacs calendar at the current date.
13546 If there is a time stamp in the current line, go to that date.
13547 A prefix ARG can be used to force the current date."
13548 (interactive "P")
13549 (let ((tsr org-ts-regexp) diff
13550 (calendar-move-hook nil)
13551 (calendar-view-holidays-initially-flag nil)
13552 (view-calendar-holidays-initially nil)
13553 (calendar-view-diary-initially-flag nil)
13554 (view-diary-entries-initially nil))
13555 (if (or (org-at-timestamp-p)
13556 (save-excursion
13557 (beginning-of-line 1)
13558 (looking-at (concat ".*" tsr))))
13559 (let ((d1 (time-to-days (current-time)))
13560 (d2 (time-to-days
13561 (org-time-string-to-time (match-string 1)))))
13562 (setq diff (- d2 d1))))
13563 (calendar)
13564 (calendar-goto-today)
13565 (if (and diff (not arg)) (calendar-forward-day diff))))
13567 (defun org-get-date-from-calendar ()
13568 "Return a list (month day year) of date at point in calendar."
13569 (with-current-buffer "*Calendar*"
13570 (save-match-data
13571 (calendar-cursor-to-date))))
13573 (defun org-date-from-calendar ()
13574 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13575 If there is already a time stamp at the cursor position, update it."
13576 (interactive)
13577 (if (org-at-timestamp-p t)
13578 (org-timestamp-change 0 'calendar)
13579 (let ((cal-date (org-get-date-from-calendar)))
13580 (org-insert-time-stamp
13581 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13583 (defun org-minutes-to-hh:mm-string (m)
13584 "Compute H:MM from a number of minutes."
13585 (let ((h (/ m 60)))
13586 (setq m (- m (* 60 h)))
13587 (format org-time-clocksum-format h m)))
13589 (defun org-hh:mm-string-to-minutes (s)
13590 "Convert a string H:MM to a number of minutes.
13591 If the string is just a number, interprete it as minutes.
13592 In fact, the first hh:mm or number in the string will be taken,
13593 there can be extra stuff in the string.
13594 If no number is found, the return value is 0."
13595 (cond
13596 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13597 (+ (* (string-to-number (match-string 1 s)) 60)
13598 (string-to-number (match-string 2 s))))
13599 ((string-match "\\([0-9]+\\)" s)
13600 (string-to-number (match-string 1 s)))
13601 (t 0)))
13603 ;;;; Files
13605 (defun org-save-all-org-buffers ()
13606 "Save all Org-mode buffers without user confirmation."
13607 (interactive)
13608 (message "Saving all Org-mode buffers...")
13609 (save-some-buffers t 'org-mode-p)
13610 (when (featurep 'org-id) (org-id-locations-save))
13611 (message "Saving all Org-mode buffers... done"))
13613 (defun org-revert-all-org-buffers ()
13614 "Revert all Org-mode buffers.
13615 Prompt for confirmation when there are unsaved changes.
13616 Be sure you know what you are doing before letting this function
13617 overwrite your changes.
13619 This function is useful in a setup where one tracks org files
13620 with a version control system, to revert on one machine after pulling
13621 changes from another. I believe the procedure must be like this:
13623 1. M-x org-save-all-org-buffers
13624 2. Pull changes from the other machine, resolve conflicts
13625 3. M-x org-revert-all-org-buffers"
13626 (interactive)
13627 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13628 (error "Abort"))
13629 (save-excursion
13630 (save-window-excursion
13631 (mapc
13632 (lambda (b)
13633 (when (and (with-current-buffer b (org-mode-p))
13634 (with-current-buffer b buffer-file-name))
13635 (switch-to-buffer b)
13636 (revert-buffer t 'no-confirm)))
13637 (buffer-list))
13638 (when (and (featurep 'org-id) org-id-track-globally)
13639 (org-id-locations-load)))))
13641 ;;;; Agenda files
13643 ;;;###autoload
13644 (defun org-iswitchb (&optional arg)
13645 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13646 With a prefix argument, restrict available to files.
13647 With two prefix arguments, restrict available buffers to agenda files."
13648 (interactive "P")
13649 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13650 ((equal arg '(16)) (org-buffer-list 'agenda))
13651 (t (org-buffer-list)))))
13652 (switch-to-buffer
13653 (org-icompleting-read "Org buffer: "
13654 (mapcar 'list (mapcar 'buffer-name blist))
13655 nil t))))
13657 ;;;###autoload
13658 (defalias 'org-ido-switchb 'org-iswitchb)
13660 (defun org-buffer-list (&optional predicate exclude-tmp)
13661 "Return a list of Org buffers.
13662 PREDICATE can be `export', `files' or `agenda'.
13664 export restrict the list to Export buffers.
13665 files restrict the list to buffers visiting Org files.
13666 agenda restrict the list to buffers visiting agenda files.
13668 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13669 (let* ((bfn nil)
13670 (agenda-files (and (eq predicate 'agenda)
13671 (mapcar 'file-truename (org-agenda-files t))))
13672 (filter
13673 (cond
13674 ((eq predicate 'files)
13675 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13676 ((eq predicate 'export)
13677 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13678 ((eq predicate 'agenda)
13679 (lambda (b)
13680 (with-current-buffer b
13681 (and (eq major-mode 'org-mode)
13682 (setq bfn (buffer-file-name b))
13683 (member (file-truename bfn) agenda-files)))))
13684 (t (lambda (b) (with-current-buffer b
13685 (or (eq major-mode 'org-mode)
13686 (string-match "\*Org .*Export"
13687 (buffer-name b)))))))))
13688 (delq nil
13689 (mapcar
13690 (lambda(b)
13691 (if (and (funcall filter b)
13692 (or (not exclude-tmp)
13693 (not (string-match "tmp" (buffer-name b)))))
13695 nil))
13696 (buffer-list)))))
13698 (defun org-agenda-files (&optional unrestricted archives)
13699 "Get the list of agenda files.
13700 Optional UNRESTRICTED means return the full list even if a restriction
13701 is currently in place.
13702 When ARCHIVES is t, include all archive files hat are really being
13703 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13704 `org-agenda-archives-mode' is t."
13705 (let ((files
13706 (cond
13707 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13708 ((stringp org-agenda-files) (org-read-agenda-file-list))
13709 ((listp org-agenda-files) org-agenda-files)
13710 (t (error "Invalid value of `org-agenda-files'")))))
13711 (setq files (apply 'append
13712 (mapcar (lambda (f)
13713 (if (file-directory-p f)
13714 (directory-files
13715 f t org-agenda-file-regexp)
13716 (list f)))
13717 files)))
13718 (when org-agenda-skip-unavailable-files
13719 (setq files (delq nil
13720 (mapcar (function
13721 (lambda (file)
13722 (and (file-readable-p file) file)))
13723 files))))
13724 (when (or (eq archives t)
13725 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13726 (setq files (org-add-archive-files files)))
13727 files))
13729 (defun org-edit-agenda-file-list ()
13730 "Edit the list of agenda files.
13731 Depending on setup, this either uses customize to edit the variable
13732 `org-agenda-files', or it visits the file that is holding the list. In the
13733 latter case, the buffer is set up in a way that saving it automatically kills
13734 the buffer and restores the previous window configuration."
13735 (interactive)
13736 (if (stringp org-agenda-files)
13737 (let ((cw (current-window-configuration)))
13738 (find-file org-agenda-files)
13739 (org-set-local 'org-window-configuration cw)
13740 (org-add-hook 'after-save-hook
13741 (lambda ()
13742 (set-window-configuration
13743 (prog1 org-window-configuration
13744 (kill-buffer (current-buffer))))
13745 (org-install-agenda-files-menu)
13746 (message "New agenda file list installed"))
13747 nil 'local)
13748 (message "%s" (substitute-command-keys
13749 "Edit list and finish with \\[save-buffer]")))
13750 (customize-variable 'org-agenda-files)))
13752 (defun org-store-new-agenda-file-list (list)
13753 "Set new value for the agenda file list and save it correctly."
13754 (if (stringp org-agenda-files)
13755 (let ((f org-agenda-files) b)
13756 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13757 (with-temp-file f
13758 (insert (mapconcat 'identity list "\n") "\n")))
13759 (let ((org-mode-hook nil) (org-inhibit-startup t)
13760 (org-insert-mode-line-in-empty-file nil))
13761 (setq org-agenda-files list)
13762 (customize-save-variable 'org-agenda-files org-agenda-files))))
13764 (defun org-read-agenda-file-list ()
13765 "Read the list of agenda files from a file."
13766 (when (file-directory-p org-agenda-files)
13767 (error "`org-agenda-files' cannot be a single directory"))
13768 (when (stringp org-agenda-files)
13769 (with-temp-buffer
13770 (insert-file-contents org-agenda-files)
13771 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13774 ;;;###autoload
13775 (defun org-cycle-agenda-files ()
13776 "Cycle through the files in `org-agenda-files'.
13777 If the current buffer visits an agenda file, find the next one in the list.
13778 If the current buffer does not, find the first agenda file."
13779 (interactive)
13780 (let* ((fs (org-agenda-files t))
13781 (files (append fs (list (car fs))))
13782 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13783 file)
13784 (unless files (error "No agenda files"))
13785 (catch 'exit
13786 (while (setq file (pop files))
13787 (if (equal (file-truename file) tcf)
13788 (when (car files)
13789 (find-file (car files))
13790 (throw 'exit t))))
13791 (find-file (car fs)))
13792 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13794 (defun org-agenda-file-to-front (&optional to-end)
13795 "Move/add the current file to the top of the agenda file list.
13796 If the file is not present in the list, it is added to the front. If it is
13797 present, it is moved there. With optional argument TO-END, add/move to the
13798 end of the list."
13799 (interactive "P")
13800 (let ((org-agenda-skip-unavailable-files nil)
13801 (file-alist (mapcar (lambda (x)
13802 (cons (file-truename x) x))
13803 (org-agenda-files t)))
13804 (ctf (file-truename buffer-file-name))
13805 x had)
13806 (setq x (assoc ctf file-alist) had x)
13808 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13809 (if to-end
13810 (setq file-alist (append (delq x file-alist) (list x)))
13811 (setq file-alist (cons x (delq x file-alist))))
13812 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13813 (org-install-agenda-files-menu)
13814 (message "File %s to %s of agenda file list"
13815 (if had "moved" "added") (if to-end "end" "front"))))
13817 (defun org-remove-file (&optional file)
13818 "Remove current file from the list of files in variable `org-agenda-files'.
13819 These are the files which are being checked for agenda entries.
13820 Optional argument FILE means, use this file instead of the current."
13821 (interactive)
13822 (let* ((org-agenda-skip-unavailable-files nil)
13823 (file (or file buffer-file-name))
13824 (true-file (file-truename file))
13825 (afile (abbreviate-file-name file))
13826 (files (delq nil (mapcar
13827 (lambda (x)
13828 (if (equal true-file
13829 (file-truename x))
13830 nil x))
13831 (org-agenda-files t)))))
13832 (if (not (= (length files) (length (org-agenda-files t))))
13833 (progn
13834 (org-store-new-agenda-file-list files)
13835 (org-install-agenda-files-menu)
13836 (message "Removed file: %s" afile))
13837 (message "File was not in list: %s (not removed)" afile))))
13839 (defun org-file-menu-entry (file)
13840 (vector file (list 'find-file file) t))
13842 (defun org-check-agenda-file (file)
13843 "Make sure FILE exists. If not, ask user what to do."
13844 (when (not (file-exists-p file))
13845 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
13846 (abbreviate-file-name file))
13847 (let ((r (downcase (read-char-exclusive))))
13848 (cond
13849 ((equal r ?r)
13850 (org-remove-file file)
13851 (throw 'nextfile t))
13852 (t (error "Abort"))))))
13854 (defun org-get-agenda-file-buffer (file)
13855 "Get a buffer visiting FILE. If the buffer needs to be created, add
13856 it to the list of buffers which might be released later."
13857 (let ((buf (org-find-base-buffer-visiting file)))
13858 (if buf
13859 buf ; just return it
13860 ;; Make a new buffer and remember it
13861 (setq buf (find-file-noselect file))
13862 (if buf (push buf org-agenda-new-buffers))
13863 buf)))
13865 (defun org-release-buffers (blist)
13866 "Release all buffers in list, asking the user for confirmation when needed.
13867 When a buffer is unmodified, it is just killed. When modified, it is saved
13868 \(if the user agrees) and then killed."
13869 (let (buf file)
13870 (while (setq buf (pop blist))
13871 (setq file (buffer-file-name buf))
13872 (when (and (buffer-modified-p buf)
13873 file
13874 (y-or-n-p (format "Save file %s? " file)))
13875 (with-current-buffer buf (save-buffer)))
13876 (kill-buffer buf))))
13878 (defun org-prepare-agenda-buffers (files)
13879 "Create buffers for all agenda files, protect archived trees and comments."
13880 (interactive)
13881 (let ((pa '(:org-archived t))
13882 (pc '(:org-comment t))
13883 (pall '(:org-archived t :org-comment t))
13884 (inhibit-read-only t)
13885 (rea (concat ":" org-archive-tag ":"))
13886 bmp file re)
13887 (save-excursion
13888 (save-restriction
13889 (while (setq file (pop files))
13890 (catch 'nextfile
13891 (if (bufferp file)
13892 (set-buffer file)
13893 (org-check-agenda-file file)
13894 (set-buffer (org-get-agenda-file-buffer file)))
13895 (widen)
13896 (setq bmp (buffer-modified-p))
13897 (org-refresh-category-properties)
13898 (setq org-todo-keywords-for-agenda
13899 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13900 (setq org-done-keywords-for-agenda
13901 (append org-done-keywords-for-agenda org-done-keywords))
13902 (setq org-todo-keyword-alist-for-agenda
13903 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13904 (setq org-tag-alist-for-agenda
13905 (append org-tag-alist-for-agenda org-tag-alist))
13907 (save-excursion
13908 (remove-text-properties (point-min) (point-max) pall)
13909 (when org-agenda-skip-archived-trees
13910 (goto-char (point-min))
13911 (while (re-search-forward rea nil t)
13912 (if (org-on-heading-p t)
13913 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13914 (goto-char (point-min))
13915 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13916 (while (re-search-forward re nil t)
13917 (add-text-properties
13918 (match-beginning 0) (org-end-of-subtree t) pc)))
13919 (set-buffer-modified-p bmp)))))
13920 (setq org-todo-keyword-alist-for-agenda
13921 (org-uniquify org-todo-keyword-alist-for-agenda)
13922 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13924 ;;;; Embedded LaTeX
13926 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13927 "Keymap for the minor `org-cdlatex-mode'.")
13929 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13930 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13931 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13932 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13933 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13935 (defvar org-cdlatex-texmathp-advice-is-done nil
13936 "Flag remembering if we have applied the advice to texmathp already.")
13938 (define-minor-mode org-cdlatex-mode
13939 "Toggle the minor `org-cdlatex-mode'.
13940 This mode supports entering LaTeX environment and math in LaTeX fragments
13941 in Org-mode.
13942 \\{org-cdlatex-mode-map}"
13943 nil " OCDL" nil
13944 (when org-cdlatex-mode (require 'cdlatex))
13945 (unless org-cdlatex-texmathp-advice-is-done
13946 (setq org-cdlatex-texmathp-advice-is-done t)
13947 (defadvice texmathp (around org-math-always-on activate)
13948 "Always return t in org-mode buffers.
13949 This is because we want to insert math symbols without dollars even outside
13950 the LaTeX math segments. If Orgmode thinks that point is actually inside
13951 an embedded LaTeX fragment, let texmathp do its job.
13952 \\[org-cdlatex-mode-map]"
13953 (interactive)
13954 (let (p)
13955 (cond
13956 ((not (org-mode-p)) ad-do-it)
13957 ((eq this-command 'cdlatex-math-symbol)
13958 (setq ad-return-value t
13959 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13961 (let ((p (org-inside-LaTeX-fragment-p)))
13962 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13963 (setq ad-return-value t
13964 texmathp-why '("Org-mode embedded math" . 0))
13965 (if p ad-do-it)))))))))
13967 (defun turn-on-org-cdlatex ()
13968 "Unconditionally turn on `org-cdlatex-mode'."
13969 (org-cdlatex-mode 1))
13971 (defun org-inside-LaTeX-fragment-p ()
13972 "Test if point is inside a LaTeX fragment.
13973 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13974 sequence appearing also before point.
13975 Even though the matchers for math are configurable, this function assumes
13976 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13977 delimiters are skipped when they have been removed by customization.
13978 The return value is nil, or a cons cell with the delimiter and
13979 and the position of this delimiter.
13981 This function does a reasonably good job, but can locally be fooled by
13982 for example currency specifications. For example it will assume being in
13983 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13984 fragments that are properly closed, but during editing, we have to live
13985 with the uncertainty caused by missing closing delimiters. This function
13986 looks only before point, not after."
13987 (catch 'exit
13988 (let ((pos (point))
13989 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13990 (lim (progn
13991 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13992 (point)))
13993 dd-on str (start 0) m re)
13994 (goto-char pos)
13995 (when dodollar
13996 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13997 re (nth 1 (assoc "$" org-latex-regexps)))
13998 (while (string-match re str start)
13999 (cond
14000 ((= (match-end 0) (length str))
14001 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14002 ((= (match-end 0) (- (length str) 5))
14003 (throw 'exit nil))
14004 (t (setq start (match-end 0))))))
14005 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14006 (goto-char pos)
14007 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14008 (and (match-beginning 2) (throw 'exit nil))
14009 ;; count $$
14010 (while (re-search-backward "\\$\\$" lim t)
14011 (setq dd-on (not dd-on)))
14012 (goto-char pos)
14013 (if dd-on (cons "$$" m))))))
14016 (defun org-try-cdlatex-tab ()
14017 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14018 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14019 - inside a LaTeX fragment, or
14020 - after the first word in a line, where an abbreviation expansion could
14021 insert a LaTeX environment."
14022 (when org-cdlatex-mode
14023 (cond
14024 ((save-excursion
14025 (skip-chars-backward "a-zA-Z0-9*")
14026 (skip-chars-backward " \t")
14027 (bolp))
14028 (cdlatex-tab) t)
14029 ((org-inside-LaTeX-fragment-p)
14030 (cdlatex-tab) t)
14031 (t nil))))
14033 (defun org-cdlatex-underscore-caret (&optional arg)
14034 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14035 Revert to the normal definition outside of these fragments."
14036 (interactive "P")
14037 (if (org-inside-LaTeX-fragment-p)
14038 (call-interactively 'cdlatex-sub-superscript)
14039 (let (org-cdlatex-mode)
14040 (call-interactively (key-binding (vector last-input-event))))))
14042 (defun org-cdlatex-math-modify (&optional arg)
14043 "Execute `cdlatex-math-modify' in LaTeX fragments.
14044 Revert to the normal definition outside of these fragments."
14045 (interactive "P")
14046 (if (org-inside-LaTeX-fragment-p)
14047 (call-interactively 'cdlatex-math-modify)
14048 (let (org-cdlatex-mode)
14049 (call-interactively (key-binding (vector last-input-event))))))
14051 (defvar org-latex-fragment-image-overlays nil
14052 "List of overlays carrying the images of latex fragments.")
14053 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14055 (defun org-remove-latex-fragment-image-overlays ()
14056 "Remove all overlays with LaTeX fragment images in current buffer."
14057 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14058 (setq org-latex-fragment-image-overlays nil))
14060 (defun org-preview-latex-fragment (&optional subtree)
14061 "Preview the LaTeX fragment at point, or all locally or globally.
14062 If the cursor is in a LaTeX fragment, create the image and overlay
14063 it over the source code. If there is no fragment at point, display
14064 all fragments in the current text, from one headline to the next. With
14065 prefix SUBTREE, display all fragments in the current subtree. With a
14066 double prefix `C-u C-u', or when the cursor is before the first headline,
14067 display all fragments in the buffer.
14068 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14069 (interactive "P")
14070 (org-remove-latex-fragment-image-overlays)
14071 (save-excursion
14072 (save-restriction
14073 (let (beg end at msg)
14074 (cond
14075 ((or (equal subtree '(16))
14076 (not (save-excursion
14077 (re-search-backward (concat "^" outline-regexp) nil t))))
14078 (setq beg (point-min) end (point-max)
14079 msg "Creating images for buffer...%s"))
14080 ((equal subtree '(4))
14081 (org-back-to-heading)
14082 (setq beg (point) end (org-end-of-subtree t)
14083 msg "Creating images for subtree...%s"))
14085 (if (setq at (org-inside-LaTeX-fragment-p))
14086 (goto-char (max (point-min) (- (cdr at) 2)))
14087 (org-back-to-heading))
14088 (setq beg (point) end (progn (outline-next-heading) (point))
14089 msg (if at "Creating image...%s"
14090 "Creating images for entry...%s"))))
14091 (message msg "")
14092 (narrow-to-region beg end)
14093 (goto-char beg)
14094 (org-format-latex
14095 (concat "ltxpng/" (file-name-sans-extension
14096 (file-name-nondirectory
14097 buffer-file-name)))
14098 default-directory 'overlays msg at 'forbuffer)
14099 (message msg "done. Use `C-c C-c' to remove images.")))))
14101 (defvar org-latex-regexps
14102 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14103 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14104 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14105 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14106 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14107 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14108 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14109 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14110 "Regular expressions for matching embedded LaTeX.")
14112 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14113 "Replace LaTeX fragments with links to an image, and produce images."
14114 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14115 (let* ((prefixnodir (file-name-nondirectory prefix))
14116 (absprefix (expand-file-name prefix dir))
14117 (todir (file-name-directory absprefix))
14118 (opt org-format-latex-options)
14119 (matchers (plist-get opt :matchers))
14120 (re-list org-latex-regexps)
14121 (cnt 0) txt link beg end re e checkdir
14122 executables-checked
14123 m n block linkfile movefile ov)
14124 ;; Check if there are old images files with this prefix, and remove them
14125 (when (file-directory-p todir)
14126 (mapc 'delete-file
14127 (directory-files
14128 todir 'full
14129 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14130 ;; Check the different regular expressions
14131 (while (setq e (pop re-list))
14132 (setq m (car e) re (nth 1 e) n (nth 2 e)
14133 block (if (nth 3 e) "\n\n" ""))
14134 (when (member m matchers)
14135 (goto-char (point-min))
14136 (while (re-search-forward re nil t)
14137 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14138 (not (get-text-property (match-beginning n)
14139 'org-protected))
14140 (or (not overlays)
14141 (not (eq (get-char-property (match-beginning n)
14142 'org-overlay-type)
14143 'org-latex-overlay))))
14144 (setq txt (match-string n)
14145 beg (match-beginning n) end (match-end n)
14146 cnt (1+ cnt)
14147 linkfile (format "%s_%04d.png" prefix cnt)
14148 movefile (format "%s_%04d.png" absprefix cnt)
14149 link (concat block "[[file:" linkfile "]]" block))
14150 (if msg (message msg cnt))
14151 (goto-char beg)
14152 (unless checkdir ; make sure the directory exists
14153 (setq checkdir t)
14154 (or (file-directory-p todir) (make-directory todir)))
14156 (unless executables-checked
14157 (org-check-external-command
14158 "latex" "needed to convert LaTeX fragments to images")
14159 (org-check-external-command
14160 "dvipng" "needed to convert LaTeX fragments to images")
14161 (setq executables-checked t))
14163 (org-create-formula-image
14164 txt movefile opt forbuffer)
14165 (if overlays
14166 (progn
14167 (mapc (lambda (o)
14168 (if (eq (org-overlay-get o 'org-overlay-type)
14169 'org-latex-overlay)
14170 (org-delete-overlay o)))
14171 (org-overlays-in beg end))
14172 (setq ov (org-make-overlay beg end))
14173 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14174 (if (featurep 'xemacs)
14175 (progn
14176 (org-overlay-put ov 'invisible t)
14177 (org-overlay-put
14178 ov 'end-glyph
14179 (make-glyph (vector 'png :file movefile))))
14180 (org-overlay-put
14181 ov 'display
14182 (list 'image :type 'png :file movefile :ascent 'center)))
14183 (push ov org-latex-fragment-image-overlays)
14184 (goto-char end))
14185 (delete-region beg end)
14186 (insert link))))))))
14188 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14189 ;; This function borrows from Ganesh Swami's latex2png.el
14190 (defun org-create-formula-image (string tofile options buffer)
14191 (require 'org-latex)
14192 (let* ((tmpdir (if (featurep 'xemacs)
14193 (temp-directory)
14194 temporary-file-directory))
14195 (texfilebase (make-temp-name
14196 (expand-file-name "orgtex" tmpdir)))
14197 (texfile (concat texfilebase ".tex"))
14198 (dvifile (concat texfilebase ".dvi"))
14199 (pngfile (concat texfilebase ".png"))
14200 (fnh (if (featurep 'xemacs)
14201 (font-height (get-face-font 'default))
14202 (face-attribute 'default :height nil)))
14203 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14204 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14205 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14206 "Black"))
14207 (bg (or (plist-get options (if buffer :background :html-background))
14208 "Transparent")))
14209 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14210 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14211 (with-temp-file texfile
14212 (insert org-format-latex-header
14213 (if org-export-latex-packages-alist
14214 (concat "\n"
14215 (mapconcat (lambda(p)
14216 (if (equal "" (car p))
14217 (format "\\usepackage{%s}" (cadr p))
14218 (format "\\usepackage[%s]{%s}"
14219 (car p) (cadr p))))
14220 org-export-latex-packages-alist "\n"))
14222 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14223 (let ((dir default-directory))
14224 (condition-case nil
14225 (progn
14226 (cd tmpdir)
14227 (call-process "latex" nil nil nil texfile))
14228 (error nil))
14229 (cd dir))
14230 (if (not (file-exists-p dvifile))
14231 (progn (message "Failed to create dvi file from %s" texfile) nil)
14232 (condition-case nil
14233 (call-process "dvipng" nil nil nil
14234 "-fg" fg "-bg" bg
14235 "-D" dpi
14236 ;;"-x" scale "-y" scale
14237 "-T" "tight"
14238 "-o" pngfile
14239 dvifile)
14240 (error nil))
14241 (if (not (file-exists-p pngfile))
14242 (progn (message "Failed to create png file from %s" texfile) nil)
14243 ;; Use the requested file name and clean up
14244 (copy-file pngfile tofile 'replace)
14245 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14246 (delete-file (concat texfilebase e)))
14247 pngfile))))
14249 (defun org-dvipng-color (attr)
14250 "Return an rgb color specification for dvipng."
14251 (apply 'format "rgb %s %s %s"
14252 (mapcar 'org-normalize-color
14253 (color-values (face-attribute 'default attr nil)))))
14255 (defun org-normalize-color (value)
14256 "Return string to be used as color value for an RGB component."
14257 (format "%g" (/ value 65535.0)))
14259 ;;;; Key bindings
14261 ;; Make `C-c C-x' a prefix key
14262 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14264 ;; TAB key with modifiers
14265 (org-defkey org-mode-map "\C-i" 'org-cycle)
14266 (org-defkey org-mode-map [(tab)] 'org-cycle)
14267 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14268 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14269 (org-defkey org-mode-map "\M-\t" 'org-complete)
14270 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14271 ;; The following line is necessary under Suse GNU/Linux
14272 (unless (featurep 'xemacs)
14273 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14274 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14275 (define-key org-mode-map [backtab] 'org-shifttab)
14277 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14278 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14279 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14281 ;; Cursor keys with modifiers
14282 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14283 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14284 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14285 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14287 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14288 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14289 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14290 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14292 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14293 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14294 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14295 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14297 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14298 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14300 ;;; Extra keys for tty access.
14301 ;; We only set them when really needed because otherwise the
14302 ;; menus don't show the simple keys
14304 (when (or org-use-extra-keys
14305 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14306 (not window-system))
14307 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14308 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14309 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14310 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14311 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14312 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14313 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14314 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14315 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14316 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14317 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14318 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14319 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14320 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14321 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14322 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14323 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14324 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14325 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14326 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14327 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14328 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14329 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14330 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14331 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14332 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14333 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14334 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14336 ;; All the other keys
14338 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14339 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14340 (if (boundp 'narrow-map)
14341 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14342 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14343 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14344 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14345 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14346 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14347 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14348 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14349 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14350 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14351 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14352 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14353 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14354 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14355 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14356 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14357 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14358 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14359 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14360 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14361 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14362 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14363 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14364 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14365 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14366 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14367 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14368 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14369 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14370 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14371 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14372 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14373 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14374 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14375 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14376 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14377 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14378 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14379 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14380 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14381 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14382 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14383 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14384 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14385 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14386 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14387 (org-defkey org-mode-map "\C-c^" 'org-sort)
14388 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14389 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14390 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14391 (org-defkey org-mode-map "\C-m" 'org-return)
14392 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14393 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14394 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14395 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14396 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14397 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14398 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14399 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14400 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14401 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14402 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14403 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14404 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14405 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14406 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14407 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14408 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14409 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14410 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14411 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14412 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14414 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14415 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14416 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14417 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14419 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14420 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14421 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14422 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14423 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14424 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14425 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14426 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14427 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14428 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14429 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14430 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14431 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14432 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14433 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14435 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14436 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14437 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14438 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14440 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14442 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14444 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14445 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14447 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14450 (when (featurep 'xemacs)
14451 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14454 (defvar org-self-insert-command-undo-counter 0)
14456 (defvar org-table-auto-blank-field) ; defined in org-table.el
14457 (defun org-self-insert-command (N)
14458 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14459 If the cursor is in a table looking at whitespace, the whitespace is
14460 overwritten, and the table is not marked as requiring realignment."
14461 (interactive "p")
14462 (if (and
14463 (org-table-p)
14464 (progn
14465 ;; check if we blank the field, and if that triggers align
14466 (and (featurep 'org-table) org-table-auto-blank-field
14467 (member last-command
14468 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14469 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14470 ;; got extra space, this field does not determine column width
14471 (let (org-table-may-need-update) (org-table-blank-field))
14472 ;; no extra space, this field may determine column width
14473 (org-table-blank-field)))
14475 (eq N 1)
14476 (looking-at "[^|\n]* |"))
14477 (let (org-table-may-need-update)
14478 (goto-char (1- (match-end 0)))
14479 (delete-backward-char 1)
14480 (goto-char (match-beginning 0))
14481 (self-insert-command N))
14482 (setq org-table-may-need-update t)
14483 (self-insert-command N)
14484 (org-fix-tags-on-the-fly)
14485 (if org-self-insert-cluster-for-undo
14486 (if (not (eq last-command 'org-self-insert-command))
14487 (setq org-self-insert-command-undo-counter 1)
14488 (if (>= org-self-insert-command-undo-counter 20)
14489 (setq org-self-insert-command-undo-counter 1)
14490 (and (> org-self-insert-command-undo-counter 0)
14491 buffer-undo-list
14492 (not (cadr buffer-undo-list)) ; remove nil entry
14493 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14494 (setq org-self-insert-command-undo-counter
14495 (1+ org-self-insert-command-undo-counter)))))))
14497 (defun org-fix-tags-on-the-fly ()
14498 (when (and (equal (char-after (point-at-bol)) ?*)
14499 (org-on-heading-p))
14500 (org-align-tags-here org-tags-column)))
14502 (defun org-delete-backward-char (N)
14503 "Like `delete-backward-char', insert whitespace at field end in tables.
14504 When deleting backwards, in tables this function will insert whitespace in
14505 front of the next \"|\" separator, to keep the table aligned. The table will
14506 still be marked for re-alignment if the field did fill the entire column,
14507 because, in this case the deletion might narrow the column."
14508 (interactive "p")
14509 (if (and (org-table-p)
14510 (eq N 1)
14511 (string-match "|" (buffer-substring (point-at-bol) (point)))
14512 (looking-at ".*?|"))
14513 (let ((pos (point))
14514 (noalign (looking-at "[^|\n\r]* |"))
14515 (c org-table-may-need-update))
14516 (backward-delete-char N)
14517 (skip-chars-forward "^|")
14518 (insert " ")
14519 (goto-char (1- pos))
14520 ;; noalign: if there were two spaces at the end, this field
14521 ;; does not determine the width of the column.
14522 (if noalign (setq org-table-may-need-update c)))
14523 (backward-delete-char N)
14524 (org-fix-tags-on-the-fly)))
14526 (defun org-delete-char (N)
14527 "Like `delete-char', but insert whitespace at field end in tables.
14528 When deleting characters, in tables this function will insert whitespace in
14529 front of the next \"|\" separator, to keep the table aligned. The table will
14530 still be marked for re-alignment if the field did fill the entire column,
14531 because, in this case the deletion might narrow the column."
14532 (interactive "p")
14533 (if (and (org-table-p)
14534 (not (bolp))
14535 (not (= (char-after) ?|))
14536 (eq N 1))
14537 (if (looking-at ".*?|")
14538 (let ((pos (point))
14539 (noalign (looking-at "[^|\n\r]* |"))
14540 (c org-table-may-need-update))
14541 (replace-match (concat
14542 (substring (match-string 0) 1 -1)
14543 " |"))
14544 (goto-char pos)
14545 ;; noalign: if there were two spaces at the end, this field
14546 ;; does not determine the width of the column.
14547 (if noalign (setq org-table-may-need-update c)))
14548 (delete-char N))
14549 (delete-char N)
14550 (org-fix-tags-on-the-fly)))
14552 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14553 (put 'org-self-insert-command 'delete-selection t)
14554 (put 'orgtbl-self-insert-command 'delete-selection t)
14555 (put 'org-delete-char 'delete-selection 'supersede)
14556 (put 'org-delete-backward-char 'delete-selection 'supersede)
14557 (put 'org-yank 'delete-selection 'yank)
14559 ;; Make `flyspell-mode' delay after some commands
14560 (put 'org-self-insert-command 'flyspell-delayed t)
14561 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14562 (put 'org-delete-char 'flyspell-delayed t)
14563 (put 'org-delete-backward-char 'flyspell-delayed t)
14565 ;; Make pabbrev-mode expand after org-mode commands
14566 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14567 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14569 ;; How to do this: Measure non-white length of current string
14570 ;; If equal to column width, we should realign.
14572 (defun org-remap (map &rest commands)
14573 "In MAP, remap the functions given in COMMANDS.
14574 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14575 (let (new old)
14576 (while commands
14577 (setq old (pop commands) new (pop commands))
14578 (if (fboundp 'command-remapping)
14579 (org-defkey map (vector 'remap old) new)
14580 (substitute-key-definition old new map global-map)))))
14582 (when (eq org-enable-table-editor 'optimized)
14583 ;; If the user wants maximum table support, we need to hijack
14584 ;; some standard editing functions
14585 (org-remap org-mode-map
14586 'self-insert-command 'org-self-insert-command
14587 'delete-char 'org-delete-char
14588 'delete-backward-char 'org-delete-backward-char)
14589 (org-defkey org-mode-map "|" 'org-force-self-insert))
14591 (defvar org-ctrl-c-ctrl-c-hook nil
14592 "Hook for functions attaching themselves to `C-c C-c'.
14593 This can be used to add additional functionality to the C-c C-c key which
14594 executes context-dependent commands.
14595 Each function will be called with no arguments. The function must check
14596 if the context is appropriate for it to act. If yes, it should do its
14597 thing and then return a non-nil value. If the context is wrong,
14598 just do nothing and return nil.")
14600 (defvar org-tab-first-hook nil
14601 "Hook for functions to attach themselves to TAB.
14602 See `org-ctrl-c-ctrl-c-hook' for more information.
14603 This hook runs as the first action when TAB is pressed, even before
14604 `org-cycle' messes around with the `outline-regexp' to cater for
14605 inline tasks and plain list item folding.
14606 If any function in this hook returns t, not other actions like table
14607 field motion visibility cycling will be done.")
14609 (defvar org-tab-after-check-for-table-hook nil
14610 "Hook for functions to attach themselves to TAB.
14611 See `org-ctrl-c-ctrl-c-hook' for more information.
14612 This hook runs after it has been established that the cursor is not in a
14613 table, but before checking if the cursor is in a headline or if global cycling
14614 should be done.
14615 If any function in this hook returns t, not other actions like visibility
14616 cycling will be done.")
14618 (defvar org-tab-after-check-for-cycling-hook nil
14619 "Hook for functions to attach themselves to TAB.
14620 See `org-ctrl-c-ctrl-c-hook' for more information.
14621 This hook runs after it has been established that not table field motion and
14622 not visibility should be done because of current context. This is probably
14623 the place where a package like yasnippets can hook in.")
14625 (defvar org-metaleft-hook nil
14626 "Hook for functions attaching themselves to `M-left'.
14627 See `org-ctrl-c-ctrl-c-hook' for more information.")
14628 (defvar org-metaright-hook nil
14629 "Hook for functions attaching themselves to `M-right'.
14630 See `org-ctrl-c-ctrl-c-hook' for more information.")
14631 (defvar org-metaup-hook nil
14632 "Hook for functions attaching themselves to `M-up'.
14633 See `org-ctrl-c-ctrl-c-hook' for more information.")
14634 (defvar org-metadown-hook nil
14635 "Hook for functions attaching themselves to `M-down'.
14636 See `org-ctrl-c-ctrl-c-hook' for more information.")
14637 (defvar org-shiftmetaleft-hook nil
14638 "Hook for functions attaching themselves to `M-S-left'.
14639 See `org-ctrl-c-ctrl-c-hook' for more information.")
14640 (defvar org-shiftmetaright-hook nil
14641 "Hook for functions attaching themselves to `M-S-right'.
14642 See `org-ctrl-c-ctrl-c-hook' for more information.")
14643 (defvar org-shiftmetaup-hook nil
14644 "Hook for functions attaching themselves to `M-S-up'.
14645 See `org-ctrl-c-ctrl-c-hook' for more information.")
14646 (defvar org-shiftmetadown-hook nil
14647 "Hook for functions attaching themselves to `M-S-down'.
14648 See `org-ctrl-c-ctrl-c-hook' for more information.")
14649 (defvar org-metareturn-hook nil
14650 "Hook for functions attaching themselves to `M-RET'.
14651 See `org-ctrl-c-ctrl-c-hook' for more information.")
14653 (defun org-modifier-cursor-error ()
14654 "Throw an error, a modified cursor command was applied in wrong context."
14655 (error "This command is active in special context like tables, headlines or items"))
14657 (defun org-shiftselect-error ()
14658 "Throw an error because Shift-Cursor command was applied in wrong context."
14659 (if (and (boundp 'shift-select-mode) shift-select-mode)
14660 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14661 (error "This command works only in special context like headlines or timestamps.")))
14663 (defun org-call-for-shift-select (cmd)
14664 (let ((this-command-keys-shift-translated t))
14665 (call-interactively cmd)))
14667 (defun org-shifttab (&optional arg)
14668 "Global visibility cycling or move to previous table field.
14669 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14670 on context.
14671 See the individual commands for more information."
14672 (interactive "P")
14673 (cond
14674 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14675 ((integerp arg)
14676 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
14677 (message "Content view to level: %d" arg)
14678 (org-content (prefix-numeric-value arg2))
14679 (setq org-cycle-global-status 'overview)))
14680 (t (call-interactively 'org-global-cycle))))
14682 (defun org-shiftmetaleft ()
14683 "Promote subtree or delete table column.
14684 Calls `org-promote-subtree', `org-outdent-item',
14685 or `org-table-delete-column', depending on context.
14686 See the individual commands for more information."
14687 (interactive)
14688 (cond
14689 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14690 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14691 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14692 ((org-at-item-p) (call-interactively 'org-outdent-item))
14693 (t (org-modifier-cursor-error))))
14695 (defun org-shiftmetaright ()
14696 "Demote subtree or insert table column.
14697 Calls `org-demote-subtree', `org-indent-item',
14698 or `org-table-insert-column', depending on context.
14699 See the individual commands for more information."
14700 (interactive)
14701 (cond
14702 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14703 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14704 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14705 ((org-at-item-p) (call-interactively 'org-indent-item))
14706 (t (org-modifier-cursor-error))))
14708 (defun org-shiftmetaup (&optional arg)
14709 "Move subtree up or kill table row.
14710 Calls `org-move-subtree-up' or `org-table-kill-row' or
14711 `org-move-item-up' depending on context. See the individual commands
14712 for more information."
14713 (interactive "P")
14714 (cond
14715 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14716 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14717 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14718 ((org-at-item-p) (call-interactively 'org-move-item-up))
14719 (t (org-modifier-cursor-error))))
14721 (defun org-shiftmetadown (&optional arg)
14722 "Move subtree down or insert table row.
14723 Calls `org-move-subtree-down' or `org-table-insert-row' or
14724 `org-move-item-down', depending on context. See the individual
14725 commands for more information."
14726 (interactive "P")
14727 (cond
14728 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14729 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14730 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14731 ((org-at-item-p) (call-interactively 'org-move-item-down))
14732 (t (org-modifier-cursor-error))))
14734 (defun org-metaleft (&optional arg)
14735 "Promote heading or move table column to left.
14736 Calls `org-do-promote' or `org-table-move-column', depending on context.
14737 With no specific context, calls the Emacs default `backward-word'.
14738 See the individual commands for more information."
14739 (interactive "P")
14740 (cond
14741 ((run-hook-with-args-until-success 'org-metaleft-hook))
14742 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14743 ((or (org-on-heading-p)
14744 (and (org-region-active-p)
14745 (save-excursion
14746 (goto-char (region-beginning))
14747 (org-on-heading-p))))
14748 (call-interactively 'org-do-promote))
14749 ((or (org-at-item-p)
14750 (and (org-region-active-p)
14751 (save-excursion
14752 (goto-char (region-beginning))
14753 (org-at-item-p))))
14754 (call-interactively 'org-outdent-item))
14755 (t (call-interactively 'backward-word))))
14757 (defun org-metaright (&optional arg)
14758 "Demote subtree or move table column to right.
14759 Calls `org-do-demote' or `org-table-move-column', depending on context.
14760 With no specific context, calls the Emacs default `forward-word'.
14761 See the individual commands for more information."
14762 (interactive "P")
14763 (cond
14764 ((run-hook-with-args-until-success 'org-metaright-hook))
14765 ((org-at-table-p) (call-interactively 'org-table-move-column))
14766 ((or (org-on-heading-p)
14767 (and (org-region-active-p)
14768 (save-excursion
14769 (goto-char (region-beginning))
14770 (org-on-heading-p))))
14771 (call-interactively 'org-do-demote))
14772 ((or (org-at-item-p)
14773 (and (org-region-active-p)
14774 (save-excursion
14775 (goto-char (region-beginning))
14776 (org-at-item-p))))
14777 (call-interactively 'org-indent-item))
14778 (t (call-interactively 'forward-word))))
14780 (defun org-metaup (&optional arg)
14781 "Move subtree up or move table row up.
14782 Calls `org-move-subtree-up' or `org-table-move-row' or
14783 `org-move-item-up', depending on context. See the individual commands
14784 for more information."
14785 (interactive "P")
14786 (cond
14787 ((run-hook-with-args-until-success 'org-metaup-hook))
14788 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14789 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14790 ((org-at-item-p) (call-interactively 'org-move-item-up))
14791 (t (transpose-lines 1) (beginning-of-line -1))))
14793 (defun org-metadown (&optional arg)
14794 "Move subtree down or move table row down.
14795 Calls `org-move-subtree-down' or `org-table-move-row' or
14796 `org-move-item-down', depending on context. See the individual
14797 commands for more information."
14798 (interactive "P")
14799 (cond
14800 ((run-hook-with-args-until-success 'org-metadown-hook))
14801 ((org-at-table-p) (call-interactively 'org-table-move-row))
14802 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14803 ((org-at-item-p) (call-interactively 'org-move-item-down))
14804 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14806 (defun org-shiftup (&optional arg)
14807 "Increase item in timestamp or increase priority of current headline.
14808 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14809 depending on context. See the individual commands for more information."
14810 (interactive "P")
14811 (cond
14812 ((and org-support-shift-select (org-region-active-p))
14813 (org-call-for-shift-select 'previous-line))
14814 ((org-at-timestamp-p t)
14815 (call-interactively (if org-edit-timestamp-down-means-later
14816 'org-timestamp-down 'org-timestamp-up)))
14817 ((and (not (eq org-support-shift-select 'always))
14818 org-enable-priority-commands
14819 (org-on-heading-p))
14820 (call-interactively 'org-priority-up))
14821 ((and (not org-support-shift-select) (org-at-item-p))
14822 (call-interactively 'org-previous-item))
14823 ((org-clocktable-try-shift 'up arg))
14824 (org-support-shift-select
14825 (org-call-for-shift-select 'previous-line))
14826 (t (org-shiftselect-error))))
14828 (defun org-shiftdown (&optional arg)
14829 "Decrease item in timestamp or decrease priority of current headline.
14830 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14831 depending on context. See the individual commands for more information."
14832 (interactive "P")
14833 (cond
14834 ((and org-support-shift-select (org-region-active-p))
14835 (org-call-for-shift-select 'next-line))
14836 ((org-at-timestamp-p t)
14837 (call-interactively (if org-edit-timestamp-down-means-later
14838 'org-timestamp-up 'org-timestamp-down)))
14839 ((and (not (eq org-support-shift-select 'always))
14840 org-enable-priority-commands
14841 (org-on-heading-p))
14842 (call-interactively 'org-priority-down))
14843 ((and (not org-support-shift-select) (org-at-item-p))
14844 (call-interactively 'org-next-item))
14845 ((org-clocktable-try-shift 'down arg))
14846 (org-support-shift-select
14847 (org-call-for-shift-select 'next-line))
14848 (t (org-shiftselect-error))))
14850 (defun org-shiftright (&optional arg)
14851 "Cycle the thing at point or in the current line, depending on context.
14852 Depending on context, this does one of the following:
14854 - switch a timestamp at point one day into the future
14855 - on a headline, switch to the next TODO keyword.
14856 - on an item, switch entire list to the next bullet type
14857 - on a property line, switch to the next allowed value
14858 - on a clocktable definition line, move time block into the future"
14859 (interactive "P")
14860 (cond
14861 ((and org-support-shift-select (org-region-active-p))
14862 (org-call-for-shift-select 'forward-char))
14863 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14864 ((and (not (eq org-support-shift-select 'always))
14865 (org-on-heading-p))
14866 (let ((org-inhibit-logging
14867 (not org-treat-S-cursor-todo-selection-as-state-change))
14868 (org-inhibit-blocking
14869 (not org-treat-S-cursor-todo-selection-as-state-change)))
14870 (org-call-with-arg 'org-todo 'right)))
14871 ((or (and org-support-shift-select
14872 (not (eq org-support-shift-select 'always))
14873 (org-at-item-bullet-p))
14874 (and (not org-support-shift-select) (org-at-item-p)))
14875 (org-call-with-arg 'org-cycle-list-bullet nil))
14876 ((and (not (eq org-support-shift-select 'always))
14877 (org-at-property-p))
14878 (call-interactively 'org-property-next-allowed-value))
14879 ((org-clocktable-try-shift 'right arg))
14880 (org-support-shift-select
14881 (org-call-for-shift-select 'forward-char))
14882 (t (org-shiftselect-error))))
14884 (defun org-shiftleft (&optional arg)
14885 "Cycle the thing at point or in the current line, depending on context.
14886 Depending on context, this does one of the following:
14888 - switch a timestamp at point one day into the past
14889 - on a headline, switch to the previous TODO keyword.
14890 - on an item, switch entire list to the previous bullet type
14891 - on a property line, switch to the previous allowed value
14892 - on a clocktable definition line, move time block into the past"
14893 (interactive "P")
14894 (cond
14895 ((and org-support-shift-select (org-region-active-p))
14896 (org-call-for-shift-select 'backward-char))
14897 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14898 ((and (not (eq org-support-shift-select 'always))
14899 (org-on-heading-p))
14900 (let ((org-inhibit-logging
14901 (not org-treat-S-cursor-todo-selection-as-state-change))
14902 (org-inhibit-blocking
14903 (not org-treat-S-cursor-todo-selection-as-state-change)))
14904 (org-call-with-arg 'org-todo 'left)))
14905 ((or (and org-support-shift-select
14906 (not (eq org-support-shift-select 'always))
14907 (org-at-item-bullet-p))
14908 (and (not org-support-shift-select) (org-at-item-p)))
14909 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14910 ((and (not (eq org-support-shift-select 'always))
14911 (org-at-property-p))
14912 (call-interactively 'org-property-previous-allowed-value))
14913 ((org-clocktable-try-shift 'left arg))
14914 (org-support-shift-select
14915 (org-call-for-shift-select 'backward-char))
14916 (t (org-shiftselect-error))))
14918 (defun org-shiftcontrolright ()
14919 "Switch to next TODO set."
14920 (interactive)
14921 (cond
14922 ((and org-support-shift-select (org-region-active-p))
14923 (org-call-for-shift-select 'forward-word))
14924 ((and (not (eq org-support-shift-select 'always))
14925 (org-on-heading-p))
14926 (org-call-with-arg 'org-todo 'nextset))
14927 (org-support-shift-select
14928 (org-call-for-shift-select 'forward-word))
14929 (t (org-shiftselect-error))))
14931 (defun org-shiftcontrolleft ()
14932 "Switch to previous TODO set."
14933 (interactive)
14934 (cond
14935 ((and org-support-shift-select (org-region-active-p))
14936 (org-call-for-shift-select 'backward-word))
14937 ((and (not (eq org-support-shift-select 'always))
14938 (org-on-heading-p))
14939 (org-call-with-arg 'org-todo 'previousset))
14940 (org-support-shift-select
14941 (org-call-for-shift-select 'backward-word))
14942 (t (org-shiftselect-error))))
14944 (defun org-ctrl-c-ret ()
14945 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14946 (interactive)
14947 (cond
14948 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14949 (t (call-interactively 'org-insert-heading))))
14951 (defun org-copy-special ()
14952 "Copy region in table or copy current subtree.
14953 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14954 See the individual commands for more information."
14955 (interactive)
14956 (call-interactively
14957 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14959 (defun org-cut-special ()
14960 "Cut region in table or cut current subtree.
14961 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14962 See the individual commands for more information."
14963 (interactive)
14964 (call-interactively
14965 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14967 (defun org-paste-special (arg)
14968 "Paste rectangular region into table, or past subtree relative to level.
14969 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14970 See the individual commands for more information."
14971 (interactive "P")
14972 (if (org-at-table-p)
14973 (org-table-paste-rectangle)
14974 (org-paste-subtree arg)))
14976 (defun org-edit-special ()
14977 "Call a special editor for the stuff at point.
14978 When at a table, call the formula editor with `org-table-edit-formulas'.
14979 When at the first line of an src example, call `org-edit-src-code'.
14980 When in an #+include line, visit the include file. Otherwise call
14981 `ffap' to visit the file at point."
14982 (interactive)
14983 (cond
14984 ((org-at-table-p)
14985 (call-interactively 'org-table-edit-formulas))
14986 ((save-excursion
14987 (beginning-of-line 1)
14988 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14989 (find-file (org-trim (match-string 1))))
14990 ((org-edit-src-code))
14991 ((org-edit-fixed-width-region))
14992 (t (call-interactively 'ffap))))
14995 (defun org-ctrl-c-ctrl-c (&optional arg)
14996 "Set tags in headline, or update according to changed information at point.
14998 This command does many different things, depending on context:
15000 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15001 this is what we do.
15003 - If the cursor is on a statistics cookie, update it.
15005 - If the cursor is in a headline, prompt for tags and insert them
15006 into the current line, aligned to `org-tags-column'. When called
15007 with prefix arg, realign all tags in the current buffer.
15009 - If the cursor is in one of the special #+KEYWORD lines, this
15010 triggers scanning the buffer for these lines and updating the
15011 information.
15013 - If the cursor is inside a table, realign the table. This command
15014 works even if the automatic table editor has been turned off.
15016 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15017 the entire table.
15019 - If the cursor is at a footnote reference or definition, jump to
15020 the corresponding definition or references, respectively.
15022 - If the cursor is a the beginning of a dynamic block, update it.
15024 - If the cursor is inside a table created by the table.el package,
15025 activate that table.
15027 - If the current buffer is a remember buffer, close note and file
15028 it. A prefix argument of 1 files to the default location
15029 without further interaction. A prefix argument of 2 files to
15030 the currently clocking task.
15032 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15033 links in this buffer.
15035 - If the cursor is on a numbered item in a plain list, renumber the
15036 ordered list.
15038 - If the cursor is on a checkbox, toggle it."
15039 (interactive "P")
15040 (let ((org-enable-table-editor t))
15041 (cond
15042 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15043 org-occur-highlights
15044 org-latex-fragment-image-overlays)
15045 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15046 (org-remove-occur-highlights)
15047 (org-remove-latex-fragment-image-overlays)
15048 (message "Temporary highlights/overlays removed from current buffer"))
15049 ((and (local-variable-p 'org-finish-function (current-buffer))
15050 (fboundp org-finish-function))
15051 (funcall org-finish-function))
15052 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15053 ((org-at-property-p)
15054 (call-interactively 'org-property-action))
15055 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15056 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15057 (or (org-on-heading-p) (org-at-item-p)))
15058 (call-interactively 'org-update-statistics-cookies))
15059 ((org-on-heading-p) (call-interactively 'org-set-tags))
15060 ((org-at-table.el-p)
15061 (require 'table)
15062 (beginning-of-line 1)
15063 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15064 (call-interactively 'table-recognize-table))
15065 ((org-at-table-p)
15066 (org-table-maybe-eval-formula)
15067 (if arg
15068 (call-interactively 'org-table-recalculate)
15069 (org-table-maybe-recalculate-line))
15070 (call-interactively 'org-table-align))
15071 ((or (org-footnote-at-reference-p)
15072 (org-footnote-at-definition-p))
15073 (call-interactively 'org-footnote-action))
15074 ((org-at-item-checkbox-p)
15075 (call-interactively 'org-toggle-checkbox))
15076 ((org-at-item-p)
15077 (if arg
15078 (call-interactively 'org-toggle-checkbox)
15079 (call-interactively 'org-maybe-renumber-ordered-list)))
15080 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15081 ;; Dynamic block
15082 (beginning-of-line 1)
15083 (save-excursion (org-update-dblock)))
15084 ((save-excursion
15085 (beginning-of-line 1)
15086 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15087 (cond
15088 ((equal (match-string 1) "TBLFM")
15089 ;; Recalculate the table before this line
15090 (save-excursion
15091 (beginning-of-line 1)
15092 (skip-chars-backward " \r\n\t")
15093 (if (org-at-table-p)
15094 (org-call-with-arg 'org-table-recalculate t))))
15096 ; (org-set-regexps-and-options)
15097 ; (org-restart-font-lock)
15098 (let ((org-inhibit-startup t)) (org-mode-restart))
15099 (message "Local setup has been refreshed"))))
15100 ((org-clock-update-time-maybe))
15101 (t (error "C-c C-c can do nothing useful at this location.")))))
15103 (defun org-mode-restart ()
15104 "Restart Org-mode, to scan again for special lines.
15105 Also updates the keyword regular expressions."
15106 (interactive)
15107 (org-mode)
15108 (message "Org-mode restarted"))
15110 (defun org-kill-note-or-show-branches ()
15111 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15112 (interactive)
15113 (if (not org-finish-function)
15114 (call-interactively 'show-branches)
15115 (let ((org-note-abort t))
15116 (funcall org-finish-function))))
15118 (defun org-return (&optional indent)
15119 "Goto next table row or insert a newline.
15120 Calls `org-table-next-row' or `newline', depending on context.
15121 See the individual commands for more information."
15122 (interactive)
15123 (cond
15124 ((bobp) (if indent (newline-and-indent) (newline)))
15125 ((org-at-table-p)
15126 (org-table-justify-field-maybe)
15127 (call-interactively 'org-table-next-row))
15128 ((and org-return-follows-link
15129 (eq (get-text-property (point) 'face) 'org-link))
15130 (call-interactively 'org-open-at-point))
15131 ((and (org-at-heading-p)
15132 (looking-at
15133 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15134 (org-show-entry)
15135 (end-of-line 1)
15136 (newline))
15137 (t (if indent (newline-and-indent) (newline)))))
15139 (defun org-return-indent ()
15140 "Goto next table row or insert a newline and indent.
15141 Calls `org-table-next-row' or `newline-and-indent', depending on
15142 context. See the individual commands for more information."
15143 (interactive)
15144 (org-return t))
15146 (defun org-ctrl-c-star ()
15147 "Compute table, or change heading status of lines.
15148 Calls `org-table-recalculate' or `org-toggle-heading',
15149 depending on context."
15150 (interactive)
15151 (cond
15152 ((org-at-table-p)
15153 (call-interactively 'org-table-recalculate))
15155 ;; Convert all lines in region to list items
15156 (call-interactively 'org-toggle-heading))))
15158 (defun org-ctrl-c-minus ()
15159 "Insert separator line in table or modify bullet status of line.
15160 Also turns a plain line or a region of lines into list items.
15161 Calls `org-table-insert-hline', `org-toggle-item', or
15162 `org-cycle-list-bullet', depending on context."
15163 (interactive)
15164 (cond
15165 ((org-at-table-p)
15166 (call-interactively 'org-table-insert-hline))
15167 ((org-region-active-p)
15168 (call-interactively 'org-toggle-item))
15169 ((org-in-item-p)
15170 (call-interactively 'org-cycle-list-bullet))
15172 (call-interactively 'org-toggle-item))))
15174 (defun org-toggle-item ()
15175 "Convert headings or normal lines to items, items to normal lines.
15176 If there is no active region, only the current line is considered.
15178 If the first line in the region is a headline, convert all headlines to items.
15180 If the first line in the region is an item, convert all items to normal lines.
15182 If the first line is normal text, add an item bullet to each line."
15183 (interactive)
15184 (let (l2 l beg end)
15185 (if (org-region-active-p)
15186 (setq beg (region-beginning) end (region-end))
15187 (setq beg (point-at-bol)
15188 end (min (1+ (point-at-eol)) (point-max))))
15189 (save-excursion
15190 (goto-char end)
15191 (setq l2 (org-current-line))
15192 (goto-char beg)
15193 (beginning-of-line 1)
15194 (setq l (1- (org-current-line)))
15195 (if (org-at-item-p)
15196 ;; We already have items, de-itemize
15197 (while (< (setq l (1+ l)) l2)
15198 (when (org-at-item-p)
15199 (goto-char (match-beginning 2))
15200 (delete-region (match-beginning 2) (match-end 2))
15201 (and (looking-at "[ \t]+") (replace-match "")))
15202 (beginning-of-line 2))
15203 (if (org-on-heading-p)
15204 ;; Headings, convert to items
15205 (while (< (setq l (1+ l)) l2)
15206 (if (looking-at org-outline-regexp)
15207 (replace-match "- " t t))
15208 (beginning-of-line 2))
15209 ;; normal lines, turn them into items
15210 (while (< (setq l (1+ l)) l2)
15211 (unless (org-at-item-p)
15212 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15213 (replace-match "\\1- \\2")))
15214 (beginning-of-line 2)))))))
15216 (defun org-toggle-heading (&optional nstars)
15217 "Convert headings to normal text, or items or text to headings.
15218 If there is no active region, only the current line is considered.
15220 If the first line is a heading, remove the stars from all headlines
15221 in the region.
15223 If the first line is a plain list item, turn all plain list items
15224 into headings.
15226 If the first line is a normal line, turn each and every line in the
15227 region into a heading.
15229 When converting a line into a heading, the number of stars is chosen
15230 such that the lines become children of the current entry. However,
15231 when a prefix argument is given, its value determines the number of
15232 stars to add."
15233 (interactive "P")
15234 (let (l2 l itemp beg end)
15235 (if (org-region-active-p)
15236 (setq beg (region-beginning) end (region-end))
15237 (setq beg (point-at-bol)
15238 end (min (1+ (point-at-eol)) (point-max))))
15239 (save-excursion
15240 (goto-char end)
15241 (setq l2 (org-current-line))
15242 (goto-char beg)
15243 (beginning-of-line 1)
15244 (setq l (1- (org-current-line)))
15245 (if (org-on-heading-p)
15246 ;; We already have headlines, de-star them
15247 (while (< (setq l (1+ l)) l2)
15248 (when (org-on-heading-p t)
15249 (and (looking-at outline-regexp) (replace-match "")))
15250 (beginning-of-line 2))
15251 (setq itemp (org-at-item-p))
15252 (let* ((stars
15253 (if nstars
15254 (make-string (prefix-numeric-value current-prefix-arg)
15256 (save-excursion
15257 (if (re-search-backward org-complex-heading-regexp nil t)
15258 (match-string 1) ""))))
15259 (add-stars (cond (nstars "")
15260 ((equal stars "") "*")
15261 (org-odd-levels-only "**")
15262 (t "*")))
15263 (rpl (concat stars add-stars " ")))
15264 (while (< (setq l (1+ l)) l2)
15265 (if itemp
15266 (and (org-at-item-p) (replace-match rpl t t))
15267 (unless (org-on-heading-p)
15268 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15269 (replace-match (concat rpl (match-string 2))))))
15270 (beginning-of-line 2)))))))
15272 (defun org-meta-return (&optional arg)
15273 "Insert a new heading or wrap a region in a table.
15274 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15275 See the individual commands for more information."
15276 (interactive "P")
15277 (cond
15278 ((run-hook-with-args-until-success 'org-metareturn-hook))
15279 ((org-at-table-p)
15280 (call-interactively 'org-table-wrap-region))
15281 (t (call-interactively 'org-insert-heading))))
15283 ;;; Menu entries
15285 ;; Define the Org-mode menus
15286 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15287 '("Tbl"
15288 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15289 ["Next Field" org-cycle (org-at-table-p)]
15290 ["Previous Field" org-shifttab (org-at-table-p)]
15291 ["Next Row" org-return (org-at-table-p)]
15292 "--"
15293 ["Blank Field" org-table-blank-field (org-at-table-p)]
15294 ["Edit Field" org-table-edit-field (org-at-table-p)]
15295 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15296 "--"
15297 ("Column"
15298 ["Move Column Left" org-metaleft (org-at-table-p)]
15299 ["Move Column Right" org-metaright (org-at-table-p)]
15300 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15301 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15302 ("Row"
15303 ["Move Row Up" org-metaup (org-at-table-p)]
15304 ["Move Row Down" org-metadown (org-at-table-p)]
15305 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15306 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15307 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15308 "--"
15309 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15310 ("Rectangle"
15311 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15312 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15313 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15314 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15315 "--"
15316 ("Calculate"
15317 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15318 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15319 ["Edit Formulas" org-edit-special (org-at-table-p)]
15320 "--"
15321 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15322 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15323 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15324 "--"
15325 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15326 "--"
15327 ["Sum Column/Rectangle" org-table-sum
15328 (or (org-at-table-p) (org-region-active-p))]
15329 ["Which Column?" org-table-current-column (org-at-table-p)])
15330 ["Debug Formulas"
15331 org-table-toggle-formula-debugger
15332 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15333 ["Show Col/Row Numbers"
15334 org-table-toggle-coordinate-overlays
15335 :style toggle
15336 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15337 "--"
15338 ["Create" org-table-create (and (not (org-at-table-p))
15339 org-enable-table-editor)]
15340 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15341 ["Import from File" org-table-import (not (org-at-table-p))]
15342 ["Export to File" org-table-export (org-at-table-p)]
15343 "--"
15344 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15346 (easy-menu-define org-org-menu org-mode-map "Org menu"
15347 '("Org"
15348 ("Show/Hide"
15349 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15350 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15351 ["Sparse Tree..." org-sparse-tree t]
15352 ["Reveal Context" org-reveal t]
15353 ["Show All" show-all t]
15354 "--"
15355 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15356 "--"
15357 ["New Heading" org-insert-heading t]
15358 ("Navigate Headings"
15359 ["Up" outline-up-heading t]
15360 ["Next" outline-next-visible-heading t]
15361 ["Previous" outline-previous-visible-heading t]
15362 ["Next Same Level" outline-forward-same-level t]
15363 ["Previous Same Level" outline-backward-same-level t]
15364 "--"
15365 ["Jump" org-goto t])
15366 ("Edit Structure"
15367 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15368 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15369 "--"
15370 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15371 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15372 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15373 "--"
15374 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15375 "--"
15376 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15377 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15378 ["Demote Heading" org-metaright (not (org-at-table-p))]
15379 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15380 "--"
15381 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15382 "--"
15383 ["Convert to odd levels" org-convert-to-odd-levels t]
15384 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15385 ("Editing"
15386 ["Emphasis..." org-emphasize t]
15387 ["Edit Source Example" org-edit-special t]
15388 "--"
15389 ["Footnote new/jump" org-footnote-action t]
15390 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15391 ("Archive"
15392 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15393 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15394 ; :active t :keys "C-u C-c C-x C-a"]
15395 ["Sparse trees open ARCHIVE trees"
15396 (setq org-sparse-tree-open-archived-trees
15397 (not org-sparse-tree-open-archived-trees))
15398 :style toggle :selected org-sparse-tree-open-archived-trees]
15399 ["Cycling opens ARCHIVE trees"
15400 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15401 :style toggle :selected org-cycle-open-archived-trees]
15402 "--"
15403 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15404 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15405 ; ["Check and Move Children" (org-archive-subtree '(4))
15406 ; :active t :keys "C-u C-c C-x C-s"]
15408 "--"
15409 ("Hyperlinks"
15410 ["Store Link (Global)" org-store-link t]
15411 ["Find existing link to here" org-occur-link-in-agenda-files t]
15412 ["Insert Link" org-insert-link t]
15413 ["Follow Link" org-open-at-point t]
15414 "--"
15415 ["Next link" org-next-link t]
15416 ["Previous link" org-previous-link t]
15417 "--"
15418 ["Descriptive Links"
15419 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15420 :style radio
15421 :selected (member '(org-link) buffer-invisibility-spec)]
15422 ["Literal Links"
15423 (progn
15424 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15425 :style radio
15426 :selected (not (member '(org-link) buffer-invisibility-spec))])
15427 "--"
15428 ("TODO Lists"
15429 ["TODO/DONE/-" org-todo t]
15430 ("Select keyword"
15431 ["Next keyword" org-shiftright (org-on-heading-p)]
15432 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15433 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15434 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15435 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15436 ["Show TODO Tree" org-show-todo-tree t]
15437 ["Global TODO list" org-todo-list t]
15438 "--"
15439 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15440 :selected org-enforce-todo-dependencies :style toggle :active t]
15441 "Settings for tree at point"
15442 ["Do Children sequentially" org-toggle-ordered-property :style radio
15443 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15444 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15445 ["Do Children parallel" org-toggle-ordered-property :style radio
15446 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15447 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15448 "--"
15449 ["Set Priority" org-priority t]
15450 ["Priority Up" org-shiftup t]
15451 ["Priority Down" org-shiftdown t]
15452 "--"
15453 ["Get news from all feeds" org-feed-update-all t]
15454 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15455 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15456 ("TAGS and Properties"
15457 ["Set Tags" org-set-tags-command t]
15458 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15459 "--"
15460 ["Set property" org-set-property t]
15461 ["Column view of properties" org-columns t]
15462 ["Insert Column View DBlock" org-insert-columns-dblock t])
15463 ("Dates and Scheduling"
15464 ["Timestamp" org-time-stamp t]
15465 ["Timestamp (inactive)" org-time-stamp-inactive t]
15466 ("Change Date"
15467 ["1 Day Later" org-shiftright t]
15468 ["1 Day Earlier" org-shiftleft t]
15469 ["1 ... Later" org-shiftup t]
15470 ["1 ... Earlier" org-shiftdown t])
15471 ["Compute Time Range" org-evaluate-time-range t]
15472 ["Schedule Item" org-schedule t]
15473 ["Deadline" org-deadline t]
15474 "--"
15475 ["Custom time format" org-toggle-time-stamp-overlays
15476 :style radio :selected org-display-custom-times]
15477 "--"
15478 ["Goto Calendar" org-goto-calendar t]
15479 ["Date from Calendar" org-date-from-calendar t]
15480 "--"
15481 ["Start/Restart Timer" org-timer-start t]
15482 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15483 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15484 ["Insert Timer String" org-timer t]
15485 ["Insert Timer Item" org-timer-item t])
15486 ("Logging work"
15487 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15488 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15489 ["Clock out" org-clock-out t]
15490 ["Clock cancel" org-clock-cancel t]
15491 "--"
15492 ["Mark as default task" org-clock-mark-default-task t]
15493 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15494 ["Goto running clock" org-clock-goto t]
15495 "--"
15496 ["Display times" org-clock-display t]
15497 ["Create clock table" org-clock-report t]
15498 "--"
15499 ["Record DONE time"
15500 (progn (setq org-log-done (not org-log-done))
15501 (message "Switching to %s will %s record a timestamp"
15502 (car org-done-keywords)
15503 (if org-log-done "automatically" "not")))
15504 :style toggle :selected org-log-done])
15505 "--"
15506 ["Agenda Command..." org-agenda t]
15507 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15508 ("File List for Agenda")
15509 ("Special views current file"
15510 ["TODO Tree" org-show-todo-tree t]
15511 ["Check Deadlines" org-check-deadlines t]
15512 ["Timeline" org-timeline t]
15513 ["Tags/Property tree" org-match-sparse-tree t])
15514 "--"
15515 ["Export/Publish..." org-export t]
15516 ("LaTeX"
15517 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15518 :selected org-cdlatex-mode]
15519 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15520 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15521 ["Modify math symbol" org-cdlatex-math-modify
15522 (org-inside-LaTeX-fragment-p)]
15523 ["Insert citation" org-reftex-citation t]
15524 "--"
15525 ["Export LaTeX fragments as images"
15526 (if (featurep 'org-exp)
15527 (setq org-export-with-LaTeX-fragments
15528 (not org-export-with-LaTeX-fragments))
15529 (require 'org-exp))
15530 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15531 org-export-with-LaTeX-fragments)])
15532 "--"
15533 ("MobileOrg"
15534 ["Push Files and Views" org-mobile-push t]
15535 ["Get Captured and Flagged" org-mobile-pull t]
15536 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
15537 "--"
15538 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
15539 "--"
15540 ("Documentation"
15541 ["Show Version" org-version t]
15542 ["Info Documentation" org-info t])
15543 ("Customize"
15544 ["Browse Org Group" org-customize t]
15545 "--"
15546 ["Expand This Menu" org-create-customize-menu
15547 (fboundp 'customize-menu-create)])
15548 ["Send bug report" org-submit-bug-report t]
15549 "--"
15550 ("Refresh/Reload"
15551 ["Refresh setup current buffer" org-mode-restart t]
15552 ["Reload Org (after update)" org-reload t]
15553 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15556 (defun org-info (&optional node)
15557 "Read documentation for Org-mode in the info system.
15558 With optional NODE, go directly to that node."
15559 (interactive)
15560 (info (format "(org)%s" (or node ""))))
15562 ;;;###autoload
15563 (defun org-submit-bug-report ()
15564 "Submit a bug report on Org-mode via mail.
15566 Don't hesitate to report any problems or inaccurate documentation.
15568 If you don't have setup sending mail from (X)Emacs, please copy the
15569 output buffer into your mail program, as it gives us important
15570 information about your Org-mode version and configuration."
15571 (interactive)
15572 (require 'reporter)
15573 (org-load-modules-maybe)
15574 (org-require-autoloaded-modules)
15575 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
15576 (reporter-submit-bug-report
15577 "emacs-orgmode@gnu.org"
15578 (org-version)
15579 (let (list)
15580 (save-window-excursion
15581 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
15582 (delete-other-windows)
15583 (erase-buffer)
15584 (insert "You are about to submit a bug report to the Org-mode mailing list.
15586 We would like to add your full Org-mode and Outline configuration to the
15587 bug report. This greatly simplifies the work of the maintainer and
15588 other experts on the mailing list.
15590 HOWEVER, some variables you have customized may contain private
15591 information. The names of customers, colleagues, or friends, might
15592 appear in the form of file names, tags, todo states, or search strings.
15593 If you answer yes to the prompt, you might want to check and remove
15594 such private information before sending the email.")
15595 (add-text-properties (point-min) (point-max) '(face org-warning))
15596 (when (yes-or-no-p "Include your Org-mode configuration ")
15597 (mapatoms
15598 (lambda (v)
15599 (and (boundp v)
15600 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
15601 (or (and (symbol-value v)
15602 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
15603 (and
15604 (get v 'custom-type) (get v 'standard-value)
15605 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
15606 (push v list)))))
15607 (kill-buffer (get-buffer "*Warn about privacy*"))
15608 list))
15609 nil nil
15610 "Remember to cover the basics, that is, what you expected to happen and
15611 what in fact did happen. You don't know how to make a good report? See
15613 http://orgmode.org/manual/Feedback.html#Feedback
15615 Your bug report will be posted to the Org-mode mailing list.
15616 ------------------------------------------------------------------------")))
15618 (defun org-install-agenda-files-menu ()
15619 (let ((bl (buffer-list)))
15620 (save-excursion
15621 (while bl
15622 (set-buffer (pop bl))
15623 (if (org-mode-p) (setq bl nil)))
15624 (when (org-mode-p)
15625 (easy-menu-change
15626 '("Org") "File List for Agenda"
15627 (append
15628 (list
15629 ["Edit File List" (org-edit-agenda-file-list) t]
15630 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15631 ["Remove Current File from List" org-remove-file t]
15632 ["Cycle through agenda files" org-cycle-agenda-files t]
15633 ["Occur in all agenda files" org-occur-in-agenda-files t]
15634 "--")
15635 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15637 ;;;; Documentation
15639 ;;;###autoload
15640 (defun org-require-autoloaded-modules ()
15641 (interactive)
15642 (mapc 'require
15643 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15644 org-docbook org-exp org-html org-icalendar
15645 org-id org-latex
15646 org-publish org-remember org-table
15647 org-timer org-xoxo)))
15649 ;;;###autoload
15650 (defun org-reload (&optional uncompiled)
15651 "Reload all org lisp files.
15652 With prefix arg UNCOMPILED, load the uncompiled versions."
15653 (interactive "P")
15654 (require 'find-func)
15655 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15656 (dir-org (file-name-directory (org-find-library-name "org")))
15657 (dir-org-contrib (ignore-errors
15658 (file-name-directory
15659 (org-find-library-name "org-contribdir"))))
15660 (files
15661 (append (directory-files dir-org t file-re)
15662 (and dir-org-contrib
15663 (directory-files dir-org-contrib t file-re))))
15664 (remove-re (concat (if (featurep 'xemacs)
15665 "org-colview" "org-colview-xemacs")
15666 "\\'")))
15667 (setq files (mapcar 'file-name-sans-extension files))
15668 (setq files (mapcar
15669 (lambda (x) (if (string-match remove-re x) nil x))
15670 files))
15671 (setq files (delq nil files))
15672 (mapc
15673 (lambda (f)
15674 (when (featurep (intern (file-name-nondirectory f)))
15675 (if (and (not uncompiled)
15676 (file-exists-p (concat f ".elc")))
15677 (load (concat f ".elc") nil nil t)
15678 (load (concat f ".el") nil nil t))))
15679 files))
15680 (org-version))
15682 ;;;###autoload
15683 (defun org-customize ()
15684 "Call the customize function with org as argument."
15685 (interactive)
15686 (org-load-modules-maybe)
15687 (org-require-autoloaded-modules)
15688 (customize-browse 'org))
15690 (defun org-create-customize-menu ()
15691 "Create a full customization menu for Org-mode, insert it into the menu."
15692 (interactive)
15693 (org-load-modules-maybe)
15694 (org-require-autoloaded-modules)
15695 (if (fboundp 'customize-menu-create)
15696 (progn
15697 (easy-menu-change
15698 '("Org") "Customize"
15699 `(["Browse Org group" org-customize t]
15700 "--"
15701 ,(customize-menu-create 'org)
15702 ["Set" Custom-set t]
15703 ["Save" Custom-save t]
15704 ["Reset to Current" Custom-reset-current t]
15705 ["Reset to Saved" Custom-reset-saved t]
15706 ["Reset to Standard Settings" Custom-reset-standard t]))
15707 (message "\"Org\"-menu now contains full customization menu"))
15708 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15710 ;;;; Miscellaneous stuff
15712 ;;; Generally useful functions
15714 (defun org-find-text-property-in-string (prop s)
15715 "Return the first non-nil value of property PROP in string S."
15716 (or (get-text-property 0 prop s)
15717 (get-text-property (or (next-single-property-change 0 prop s) 0)
15718 prop s)))
15720 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15721 "Display the given MESSAGE as a warning."
15722 (if (fboundp 'display-warning)
15723 (display-warning 'org message
15724 (if (featurep 'xemacs)
15725 'warning
15726 :warning))
15727 (let ((buf (get-buffer-create "*Org warnings*")))
15728 (with-current-buffer buf
15729 (goto-char (point-max))
15730 (insert "Warning (Org): " message)
15731 (unless (bolp)
15732 (newline)))
15733 (display-buffer buf)
15734 (sit-for 0))))
15736 (defun org-in-commented-line ()
15737 "Is point in a line starting with `#'?"
15738 (equal (char-after (point-at-bol)) ?#))
15740 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15741 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15742 (if (and marker (marker-buffer marker)
15743 (buffer-live-p (marker-buffer marker)))
15744 (progn
15745 (switch-to-buffer (marker-buffer marker))
15746 (if (or (> marker (point-max)) (< marker (point-min)))
15747 (widen))
15748 (goto-char marker)
15749 (org-show-context 'org-goto))
15750 (if bookmark
15751 (bookmark-jump bookmark)
15752 (error "Cannot find location"))))
15754 (defun org-quote-csv-field (s)
15755 "Quote field for inclusion in CSV material."
15756 (if (string-match "[\",]" s)
15757 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15760 (defun org-plist-delete (plist property)
15761 "Delete PROPERTY from PLIST.
15762 This is in contrast to merely setting it to 0."
15763 (let (p)
15764 (while plist
15765 (if (not (eq property (car plist)))
15766 (setq p (plist-put p (car plist) (nth 1 plist))))
15767 (setq plist (cddr plist)))
15770 (defun org-force-self-insert (N)
15771 "Needed to enforce self-insert under remapping."
15772 (interactive "p")
15773 (self-insert-command N))
15775 (defun org-string-width (s)
15776 "Compute width of string, ignoring invisible characters.
15777 This ignores character with invisibility property `org-link', and also
15778 characters with property `org-cwidth', because these will become invisible
15779 upon the next fontification round."
15780 (let (b l)
15781 (when (or (eq t buffer-invisibility-spec)
15782 (assq 'org-link buffer-invisibility-spec))
15783 (while (setq b (text-property-any 0 (length s)
15784 'invisible 'org-link s))
15785 (setq s (concat (substring s 0 b)
15786 (substring s (or (next-single-property-change
15787 b 'invisible s) (length s)))))))
15788 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15789 (setq s (concat (substring s 0 b)
15790 (substring s (or (next-single-property-change
15791 b 'org-cwidth s) (length s))))))
15792 (setq l (string-width s) b -1)
15793 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15794 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15797 (defun org-get-indentation (&optional line)
15798 "Get the indentation of the current line, interpreting tabs.
15799 When LINE is given, assume it represents a line and compute its indentation."
15800 (if line
15801 (if (string-match "^ *" (org-remove-tabs line))
15802 (match-end 0))
15803 (save-excursion
15804 (beginning-of-line 1)
15805 (skip-chars-forward " \t")
15806 (current-column))))
15808 (defun org-remove-tabs (s &optional width)
15809 "Replace tabulators in S with spaces.
15810 Assumes that s is a single line, starting in column 0."
15811 (setq width (or width tab-width))
15812 (while (string-match "\t" s)
15813 (setq s (replace-match
15814 (make-string
15815 (- (* width (/ (+ (match-beginning 0) width) width))
15816 (match-beginning 0)) ?\ )
15817 t t s)))
15820 (defun org-fix-indentation (line ind)
15821 "Fix indentation in LINE.
15822 IND is a cons cell with target and minimum indentation.
15823 If the current indentation in LINE is smaller than the minimum,
15824 leave it alone. If it is larger than ind, set it to the target."
15825 (let* ((l (org-remove-tabs line))
15826 (i (org-get-indentation l))
15827 (i1 (car ind)) (i2 (cdr ind)))
15828 (if (>= i i2) (setq l (substring line i2)))
15829 (if (> i1 0)
15830 (concat (make-string i1 ?\ ) l)
15831 l)))
15833 (defun org-remove-indentation (code &optional n)
15834 "Remove the maximum common indentation from the lines in CODE.
15835 N may optionally be the number of spaces to remove."
15836 (with-temp-buffer
15837 (insert code)
15838 (org-do-remove-indentation n)
15839 (buffer-string)))
15841 (defun org-do-remove-indentation (&optional n)
15842 "Remove the maximum common indentation from the buffer."
15843 (untabify (point-min) (point-max))
15844 (let ((min 10000) re)
15845 (if n
15846 (setq min n)
15847 (goto-char (point-min))
15848 (while (re-search-forward "^ *[^ \n]" nil t)
15849 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15850 (unless (or (= min 0) (= min 10000))
15851 (setq re (format "^ \\{%d\\}" min))
15852 (goto-char (point-min))
15853 (while (re-search-forward re nil t)
15854 (replace-match "")
15855 (end-of-line 1))
15856 min)))
15858 (defun org-base-buffer (buffer)
15859 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15860 (if (not buffer)
15861 buffer
15862 (or (buffer-base-buffer buffer)
15863 buffer)))
15865 (defun org-trim (s)
15866 "Remove whitespace at beginning and end of string."
15867 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15868 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15871 (defun org-wrap (string &optional width lines)
15872 "Wrap string to either a number of lines, or a width in characters.
15873 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15874 that costs. If there is a word longer than WIDTH, the text is actually
15875 wrapped to the length of that word.
15876 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15877 many lines, whatever width that takes.
15878 The return value is a list of lines, without newlines at the end."
15879 (let* ((words (org-split-string string "[ \t\n]+"))
15880 (maxword (apply 'max (mapcar 'org-string-width words)))
15881 w ll)
15882 (cond (width
15883 (org-do-wrap words (max maxword width)))
15884 (lines
15885 (setq w maxword)
15886 (setq ll (org-do-wrap words maxword))
15887 (if (<= (length ll) lines)
15889 (setq ll words)
15890 (while (> (length ll) lines)
15891 (setq w (1+ w))
15892 (setq ll (org-do-wrap words w)))
15893 ll))
15894 (t (error "Cannot wrap this")))))
15896 (defun org-do-wrap (words width)
15897 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15898 (let (lines line)
15899 (while words
15900 (setq line (pop words))
15901 (while (and words (< (+ (length line) (length (car words))) width))
15902 (setq line (concat line " " (pop words))))
15903 (setq lines (push line lines)))
15904 (nreverse lines)))
15906 (defun org-split-string (string &optional separators)
15907 "Splits STRING into substrings at SEPARATORS.
15908 No empty strings are returned if there are matches at the beginning
15909 and end of string."
15910 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15911 (start 0)
15912 notfirst
15913 (list nil))
15914 (while (and (string-match rexp string
15915 (if (and notfirst
15916 (= start (match-beginning 0))
15917 (< start (length string)))
15918 (1+ start) start))
15919 (< (match-beginning 0) (length string)))
15920 (setq notfirst t)
15921 (or (eq (match-beginning 0) 0)
15922 (and (eq (match-beginning 0) (match-end 0))
15923 (eq (match-beginning 0) start))
15924 (setq list
15925 (cons (substring string start (match-beginning 0))
15926 list)))
15927 (setq start (match-end 0)))
15928 (or (eq start (length string))
15929 (setq list
15930 (cons (substring string start)
15931 list)))
15932 (nreverse list)))
15934 (defun org-quote-vert (s)
15935 "Replace \"|\" with \"\\vert\"."
15936 (while (string-match "|" s)
15937 (setq s (replace-match "\\vert" t t s)))
15940 (defun org-uuidgen-p (s)
15941 "Is S an ID created by UUIDGEN?"
15942 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15944 (defun org-context ()
15945 "Return a list of contexts of the current cursor position.
15946 If several contexts apply, all are returned.
15947 Each context entry is a list with a symbol naming the context, and
15948 two positions indicating start and end of the context. Possible
15949 contexts are:
15951 :headline anywhere in a headline
15952 :headline-stars on the leading stars in a headline
15953 :todo-keyword on a TODO keyword (including DONE) in a headline
15954 :tags on the TAGS in a headline
15955 :priority on the priority cookie in a headline
15956 :item on the first line of a plain list item
15957 :item-bullet on the bullet/number of a plain list item
15958 :checkbox on the checkbox in a plain list item
15959 :table in an org-mode table
15960 :table-special on a special filed in a table
15961 :table-table in a table.el table
15962 :link on a hyperlink
15963 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15964 :target on a <<target>>
15965 :radio-target on a <<<radio-target>>>
15966 :latex-fragment on a LaTeX fragment
15967 :latex-preview on a LaTeX fragment with overlayed preview image
15969 This function expects the position to be visible because it uses font-lock
15970 faces as a help to recognize the following contexts: :table-special, :link,
15971 and :keyword."
15972 (let* ((f (get-text-property (point) 'face))
15973 (faces (if (listp f) f (list f)))
15974 (p (point)) clist o)
15975 ;; First the large context
15976 (cond
15977 ((org-on-heading-p t)
15978 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15979 (when (progn
15980 (beginning-of-line 1)
15981 (looking-at org-todo-line-tags-regexp))
15982 (push (org-point-in-group p 1 :headline-stars) clist)
15983 (push (org-point-in-group p 2 :todo-keyword) clist)
15984 (push (org-point-in-group p 4 :tags) clist))
15985 (goto-char p)
15986 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15987 (if (looking-at "\\[#[A-Z0-9]\\]")
15988 (push (org-point-in-group p 0 :priority) clist)))
15990 ((org-at-item-p)
15991 (push (org-point-in-group p 2 :item-bullet) clist)
15992 (push (list :item (point-at-bol)
15993 (save-excursion (org-end-of-item) (point)))
15994 clist)
15995 (and (org-at-item-checkbox-p)
15996 (push (org-point-in-group p 0 :checkbox) clist)))
15998 ((org-at-table-p)
15999 (push (list :table (org-table-begin) (org-table-end)) clist)
16000 (if (memq 'org-formula faces)
16001 (push (list :table-special
16002 (previous-single-property-change p 'face)
16003 (next-single-property-change p 'face)) clist)))
16004 ((org-at-table-p 'any)
16005 (push (list :table-table) clist)))
16006 (goto-char p)
16008 ;; Now the small context
16009 (cond
16010 ((org-at-timestamp-p)
16011 (push (org-point-in-group p 0 :timestamp) clist))
16012 ((memq 'org-link faces)
16013 (push (list :link
16014 (previous-single-property-change p 'face)
16015 (next-single-property-change p 'face)) clist))
16016 ((memq 'org-special-keyword faces)
16017 (push (list :keyword
16018 (previous-single-property-change p 'face)
16019 (next-single-property-change p 'face)) clist))
16020 ((org-on-target-p)
16021 (push (org-point-in-group p 0 :target) clist)
16022 (goto-char (1- (match-beginning 0)))
16023 (if (looking-at org-radio-target-regexp)
16024 (push (org-point-in-group p 0 :radio-target) clist))
16025 (goto-char p))
16026 ((setq o (car (delq nil
16027 (mapcar
16028 (lambda (x)
16029 (if (memq x org-latex-fragment-image-overlays) x))
16030 (org-overlays-at (point))))))
16031 (push (list :latex-fragment
16032 (org-overlay-start o) (org-overlay-end o)) clist)
16033 (push (list :latex-preview
16034 (org-overlay-start o) (org-overlay-end o)) clist))
16035 ((org-inside-LaTeX-fragment-p)
16036 ;; FIXME: positions wrong.
16037 (push (list :latex-fragment (point) (point)) clist)))
16039 (setq clist (nreverse (delq nil clist)))
16040 clist))
16042 ;; FIXME: Compare with at-regexp-p Do we need both?
16043 (defun org-in-regexp (re &optional nlines visually)
16044 "Check if point is inside a match of regexp.
16045 Normally only the current line is checked, but you can include NLINES extra
16046 lines both before and after point into the search.
16047 If VISUALLY is set, require that the cursor is not after the match but
16048 really on, so that the block visually is on the match."
16049 (catch 'exit
16050 (let ((pos (point))
16051 (eol (point-at-eol (+ 1 (or nlines 0))))
16052 (inc (if visually 1 0)))
16053 (save-excursion
16054 (beginning-of-line (- 1 (or nlines 0)))
16055 (while (re-search-forward re eol t)
16056 (if (and (<= (match-beginning 0) pos)
16057 (>= (+ inc (match-end 0)) pos))
16058 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16060 (defun org-at-regexp-p (regexp)
16061 "Is point inside a match of REGEXP in the current line?"
16062 (catch 'exit
16063 (save-excursion
16064 (let ((pos (point)) (end (point-at-eol)))
16065 (beginning-of-line 1)
16066 (while (re-search-forward regexp end t)
16067 (if (and (<= (match-beginning 0) pos)
16068 (>= (match-end 0) pos))
16069 (throw 'exit t)))
16070 nil))))
16072 (defun org-occur-in-agenda-files (regexp &optional nlines)
16073 "Call `multi-occur' with buffers for all agenda files."
16074 (interactive "sOrg-files matching: \np")
16075 (let* ((files (org-agenda-files))
16076 (tnames (mapcar 'file-truename files))
16077 (extra org-agenda-text-search-extra-files)
16079 (when (eq (car extra) 'agenda-archives)
16080 (setq extra (cdr extra))
16081 (setq files (org-add-archive-files files)))
16082 (while (setq f (pop extra))
16083 (unless (member (file-truename f) tnames)
16084 (add-to-list 'files f 'append)
16085 (add-to-list 'tnames (file-truename f) 'append)))
16086 (multi-occur
16087 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16088 regexp)))
16090 (if (boundp 'occur-mode-find-occurrence-hook)
16091 ;; Emacs 23
16092 (add-hook 'occur-mode-find-occurrence-hook
16093 (lambda ()
16094 (when (org-mode-p)
16095 (org-reveal))))
16096 ;; Emacs 22
16097 (defadvice occur-mode-goto-occurrence
16098 (after org-occur-reveal activate)
16099 (and (org-mode-p) (org-reveal)))
16100 (defadvice occur-mode-goto-occurrence-other-window
16101 (after org-occur-reveal activate)
16102 (and (org-mode-p) (org-reveal)))
16103 (defadvice occur-mode-display-occurrence
16104 (after org-occur-reveal activate)
16105 (when (org-mode-p)
16106 (let ((pos (occur-mode-find-occurrence)))
16107 (with-current-buffer (marker-buffer pos)
16108 (save-excursion
16109 (goto-char pos)
16110 (org-reveal)))))))
16112 (defun org-occur-link-in-agenda-files ()
16113 "Create a link and search for it in the agendas.
16114 The link is not stored in `org-stored-links', it is just created
16115 for the search purpose."
16116 (interactive)
16117 (let ((link (condition-case nil
16118 (org-store-link nil)
16119 (error "Unable to create a link to here"))))
16120 (org-occur-in-agenda-files (regexp-quote link))))
16122 (defun org-uniquify (list)
16123 "Remove duplicate elements from LIST."
16124 (let (res)
16125 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16126 res))
16128 (defun org-delete-all (elts list)
16129 "Remove all elements in ELTS from LIST."
16130 (while elts
16131 (setq list (delete (pop elts) list)))
16132 list)
16134 (defun org-back-over-empty-lines ()
16135 "Move backwards over whitespace, to the beginning of the first empty line.
16136 Returns the number of empty lines passed."
16137 (let ((pos (point)))
16138 (skip-chars-backward " \t\n\r")
16139 (beginning-of-line 2)
16140 (goto-char (min (point) pos))
16141 (count-lines (point) pos)))
16143 (defun org-skip-whitespace ()
16144 (skip-chars-forward " \t\n\r"))
16146 (defun org-point-in-group (point group &optional context)
16147 "Check if POINT is in match-group GROUP.
16148 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16149 match. If the match group does ot exist or point is not inside it,
16150 return nil."
16151 (and (match-beginning group)
16152 (>= point (match-beginning group))
16153 (<= point (match-end group))
16154 (if context
16155 (list context (match-beginning group) (match-end group))
16156 t)))
16158 (defun org-switch-to-buffer-other-window (&rest args)
16159 "Switch to buffer in a second window on the current frame.
16160 In particular, do not allow pop-up frames."
16161 (let (pop-up-frames special-display-buffer-names special-display-regexps
16162 special-display-function)
16163 (apply 'switch-to-buffer-other-window args)))
16165 (defun org-combine-plists (&rest plists)
16166 "Create a single property list from all plists in PLISTS.
16167 The process starts by copying the first list, and then setting properties
16168 from the other lists. Settings in the last list are the most significant
16169 ones and overrule settings in the other lists."
16170 (let ((rtn (copy-sequence (pop plists)))
16171 p v ls)
16172 (while plists
16173 (setq ls (pop plists))
16174 (while ls
16175 (setq p (pop ls) v (pop ls))
16176 (setq rtn (plist-put rtn p v))))
16177 rtn))
16179 (defun org-move-line-down (arg)
16180 "Move the current line down. With prefix argument, move it past ARG lines."
16181 (interactive "p")
16182 (let ((col (current-column))
16183 beg end pos)
16184 (beginning-of-line 1) (setq beg (point))
16185 (beginning-of-line 2) (setq end (point))
16186 (beginning-of-line (+ 1 arg))
16187 (setq pos (move-marker (make-marker) (point)))
16188 (insert (delete-and-extract-region beg end))
16189 (goto-char pos)
16190 (org-move-to-column col)))
16192 (defun org-move-line-up (arg)
16193 "Move the current line up. With prefix argument, move it past ARG lines."
16194 (interactive "p")
16195 (let ((col (current-column))
16196 beg end pos)
16197 (beginning-of-line 1) (setq beg (point))
16198 (beginning-of-line 2) (setq end (point))
16199 (beginning-of-line (- arg))
16200 (setq pos (move-marker (make-marker) (point)))
16201 (insert (delete-and-extract-region beg end))
16202 (goto-char pos)
16203 (org-move-to-column col)))
16205 (defun org-replace-escapes (string table)
16206 "Replace %-escapes in STRING with values in TABLE.
16207 TABLE is an association list with keys like \"%a\" and string values.
16208 The sequences in STRING may contain normal field width and padding information,
16209 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16210 so values can contain further %-escapes if they are define later in TABLE."
16211 (let ((case-fold-search nil)
16212 e re rpl)
16213 (while (setq e (pop table))
16214 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16215 (while (string-match re string)
16216 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16217 (cdr e)))
16218 (setq string (replace-match rpl t t string))))
16219 string))
16222 (defun org-sublist (list start end)
16223 "Return a section of LIST, from START to END.
16224 Counting starts at 1."
16225 (let (rtn (c start))
16226 (setq list (nthcdr (1- start) list))
16227 (while (and list (<= c end))
16228 (push (pop list) rtn)
16229 (setq c (1+ c)))
16230 (nreverse rtn)))
16232 (defun org-find-base-buffer-visiting (file)
16233 "Like `find-buffer-visiting' but always return the base buffer and
16234 not an indirect buffer."
16235 (let ((buf (or (get-file-buffer file)
16236 (find-buffer-visiting file))))
16237 (if buf
16238 (or (buffer-base-buffer buf) buf)
16239 nil)))
16241 (defun org-image-file-name-regexp (&optional extensions)
16242 "Return regexp matching the file names of images.
16243 If EXTENSIONS is given, only match these."
16244 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16245 (image-file-name-regexp)
16246 (let ((image-file-name-extensions
16247 (or extensions
16248 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16249 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16250 (concat "\\."
16251 (regexp-opt (nconc (mapcar 'upcase
16252 image-file-name-extensions)
16253 image-file-name-extensions)
16255 "\\'"))))
16257 (defun org-file-image-p (file &optional extensions)
16258 "Return non-nil if FILE is an image."
16259 (save-match-data
16260 (string-match (org-image-file-name-regexp extensions) file)))
16262 (defun org-get-cursor-date ()
16263 "Return the date at cursor in as a time.
16264 This works in the calendar and in the agenda, anywhere else it just
16265 returns the current time."
16266 (let (date day defd)
16267 (cond
16268 ((eq major-mode 'calendar-mode)
16269 (setq date (calendar-cursor-to-date)
16270 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16271 ((eq major-mode 'org-agenda-mode)
16272 (setq day (get-text-property (point) 'day))
16273 (if day
16274 (setq date (calendar-gregorian-from-absolute day)
16275 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16276 (nth 2 date))))))
16277 (or defd (current-time))))
16279 (defvar org-agenda-action-marker (make-marker)
16280 "Marker pointing to the entry for the next agenda action.")
16282 (defun org-mark-entry-for-agenda-action ()
16283 "Mark the current entry as target of an agenda action.
16284 Agenda actions are actions executed from the agenda with the key `k',
16285 which make use of the date at the cursor."
16286 (interactive)
16287 (move-marker org-agenda-action-marker
16288 (save-excursion (org-back-to-heading t) (point))
16289 (current-buffer))
16290 (message
16291 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16293 ;;; Paragraph filling stuff.
16294 ;; We want this to be just right, so use the full arsenal.
16296 (defun org-indent-line-function ()
16297 "Indent line like previous, but further if previous was headline or item."
16298 (interactive)
16299 (let* ((pos (point))
16300 (itemp (org-at-item-p))
16301 (case-fold-search t)
16302 (org-drawer-regexp (or org-drawer-regexp "\000"))
16303 column bpos bcol tpos tcol bullet btype bullet-type)
16304 ;; Find the previous relevant line
16305 (beginning-of-line 1)
16306 (cond
16307 ((looking-at "#") (setq column 0))
16308 ((looking-at "\\*+ ") (setq column 0))
16309 ((and (looking-at "[ \t]*:END:")
16310 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16311 (save-excursion
16312 (goto-char (1- (match-beginning 1)))
16313 (setq column (current-column))))
16314 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16315 (save-excursion
16316 (re-search-backward
16317 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16318 (setq column (org-get-indentation (match-string 0))))
16320 (beginning-of-line 0)
16321 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16322 (not (looking-at "[ \t]*:END:"))
16323 (not (looking-at org-drawer-regexp)))
16324 (beginning-of-line 0))
16325 (cond
16326 ((looking-at "\\*+[ \t]+")
16327 (if (not org-adapt-indentation)
16328 (setq column 0)
16329 (goto-char (match-end 0))
16330 (setq column (current-column))))
16331 ((looking-at org-drawer-regexp)
16332 (goto-char (1- (match-beginning 1)))
16333 (setq column (current-column)))
16334 ((looking-at "\\([ \t]*\\):END:")
16335 (goto-char (match-end 1))
16336 (setq column (current-column)))
16337 ((org-in-item-p)
16338 (org-beginning-of-item)
16339 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16340 (setq bpos (match-beginning 1) tpos (match-end 0)
16341 bcol (progn (goto-char bpos) (current-column))
16342 tcol (progn (goto-char tpos) (current-column))
16343 bullet (match-string 1)
16344 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16345 (if (> tcol (+ bcol org-description-max-indent))
16346 (setq tcol (+ bcol 5)))
16347 (if (not itemp)
16348 (setq column tcol)
16349 (goto-char pos)
16350 (beginning-of-line 1)
16351 (if (looking-at "\\S-")
16352 (progn
16353 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16354 (setq bullet (match-string 1)
16355 btype (if (string-match "[0-9]" bullet) "n" bullet))
16356 (setq column (if (equal btype bullet-type) bcol tcol)))
16357 (setq column (org-get-indentation)))))
16358 (t (setq column (org-get-indentation))))))
16359 (goto-char pos)
16360 (if (<= (current-column) (current-indentation))
16361 (org-indent-line-to column)
16362 (save-excursion (org-indent-line-to column)))
16363 (setq column (current-column))
16364 (beginning-of-line 1)
16365 (if (looking-at
16366 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16367 (replace-match (concat "\\1" (format org-property-format
16368 (match-string 2) (match-string 3)))
16369 t nil))
16370 (org-move-to-column column)))
16372 (defun org-set-autofill-regexps ()
16373 (interactive)
16374 ;; In the paragraph separator we include headlines, because filling
16375 ;; text in a line directly attached to a headline would otherwise
16376 ;; fill the headline as well.
16377 (org-set-local 'comment-start-skip "^#+[ \t]*")
16378 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16379 ;; The paragraph starter includes hand-formatted lists.
16380 (org-set-local
16381 'paragraph-start
16382 (concat
16383 "\f" "\\|"
16384 "[ ]*$" "\\|"
16385 "\\*+ " "\\|"
16386 "[ \t]*#" "\\|"
16387 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16388 "[ \t]*[:|]" "\\|"
16389 "\\$\\$" "\\|"
16390 "\\\\\\(begin\\|end\\|[][]\\)"))
16391 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16392 ;; But only if the user has not turned off tables or fixed-width regions
16393 (org-set-local
16394 'auto-fill-inhibit-regexp
16395 (concat "\\*+ \\|#\\+"
16396 "\\|[ \t]*" org-keyword-time-regexp
16397 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16398 (concat
16399 "\\|[ \t]*["
16400 (if org-enable-table-editor "|" "")
16401 (if org-enable-fixed-width-editor ":" "")
16402 "]"))))
16403 ;; We use our own fill-paragraph function, to make sure that tables
16404 ;; and fixed-width regions are not wrapped. That function will pass
16405 ;; through to `fill-paragraph' when appropriate.
16406 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16407 ; Adaptive filling: To get full control, first make sure that
16408 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16409 (org-set-local 'adaptive-fill-regexp "\000")
16410 (org-set-local 'adaptive-fill-function
16411 'org-adaptive-fill-function)
16412 (org-set-local
16413 'align-mode-rules-list
16414 '((org-in-buffer-settings
16415 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16416 (modes . '(org-mode))))))
16418 (defun org-fill-paragraph (&optional justify)
16419 "Re-align a table, pass through to fill-paragraph if no table."
16420 (let ((table-p (org-at-table-p))
16421 (table.el-p (org-at-table.el-p)))
16422 (cond ((and (equal (char-after (point-at-bol)) ?*)
16423 (save-excursion (goto-char (point-at-bol))
16424 (looking-at outline-regexp)))
16425 t) ; skip headlines
16426 (table.el-p t) ; skip table.el tables
16427 (table-p (org-table-align) t) ; align org-mode tables
16428 (t nil)))) ; call paragraph-fill
16430 ;; For reference, this is the default value of adaptive-fill-regexp
16431 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16433 (defun org-adaptive-fill-function ()
16434 "Return a fill prefix for org-mode files.
16435 In particular, this makes sure hanging paragraphs for hand-formatted lists
16436 work correctly."
16437 (cond ((looking-at "#[ \t]+")
16438 (match-string 0))
16439 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16440 (save-excursion
16441 (if (> (match-end 1) (+ (match-beginning 1)
16442 org-description-max-indent))
16443 (goto-char (+ (match-beginning 1) 5))
16444 (goto-char (match-end 0)))
16445 (make-string (current-column) ?\ )))
16446 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16447 (save-excursion
16448 (goto-char (match-end 0))
16449 (make-string (current-column) ?\ )))
16450 (t nil)))
16452 ;;; Other stuff.
16454 (defun org-toggle-fixed-width-section (arg)
16455 "Toggle the fixed-width export.
16456 If there is no active region, the QUOTE keyword at the current headline is
16457 inserted or removed. When present, it causes the text between this headline
16458 and the next to be exported as fixed-width text, and unmodified.
16459 If there is an active region, this command adds or removes a colon as the
16460 first character of this line. If the first character of a line is a colon,
16461 this line is also exported in fixed-width font."
16462 (interactive "P")
16463 (let* ((cc 0)
16464 (regionp (org-region-active-p))
16465 (beg (if regionp (region-beginning) (point)))
16466 (end (if regionp (region-end)))
16467 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16468 (case-fold-search nil)
16469 (re "[ \t]*\\(: \\)")
16470 off)
16471 (if regionp
16472 (save-excursion
16473 (goto-char beg)
16474 (setq cc (current-column))
16475 (beginning-of-line 1)
16476 (setq off (looking-at re))
16477 (while (> nlines 0)
16478 (setq nlines (1- nlines))
16479 (beginning-of-line 1)
16480 (cond
16481 (arg
16482 (org-move-to-column cc t)
16483 (insert ": \n")
16484 (forward-line -1))
16485 ((and off (looking-at re))
16486 (replace-match "" t t nil 1))
16487 ((not off) (org-move-to-column cc t) (insert ": ")))
16488 (forward-line 1)))
16489 (save-excursion
16490 (org-back-to-heading)
16491 (if (looking-at (concat outline-regexp
16492 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16493 (replace-match "" t t nil 1)
16494 (if (looking-at outline-regexp)
16495 (progn
16496 (goto-char (match-end 0))
16497 (insert org-quote-string " "))))))))
16499 (defun org-reftex-citation ()
16500 "Use reftex-citation to insert a citation into the buffer.
16501 This looks for a line like
16503 #+BIBLIOGRAPHY: foo plain option:-d
16505 and derives from it that foo.bib is the bbliography file relevant
16506 for this document. It then installs the necessary environment for RefTeX
16507 to work in this buffer and calls `reftex-citation' to insert a citation
16508 into the buffer.
16510 Export of such citations to both LaTeX and HTML is handled by the contributed
16511 package org-exp-bibtex by Taru Karttunen."
16512 (interactive)
16513 (let ((reftex-docstruct-symbol 'rds)
16514 (reftex-cite-format "\\cite{%l}")
16515 rds bib)
16516 (save-excursion
16517 (save-restriction
16518 (widen)
16519 (let ((case-fold-search t)
16520 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16521 (if (not (save-excursion
16522 (or (re-search-forward re nil t)
16523 (re-search-backward re nil t))))
16524 (error "No bibliography defined in file")
16525 (setq bib (concat (match-string 1) ".bib")
16526 rds (list (list 'bib bib)))))))
16527 (call-interactively 'reftex-citation)))
16529 ;;;; Functions extending outline functionality
16531 (defun org-beginning-of-line (&optional arg)
16532 "Go to the beginning of the current line. If that is invisible, continue
16533 to a visible line beginning. This makes the function of C-a more intuitive.
16534 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16535 first attempt, and only move to after the tags when the cursor is already
16536 beyond the end of the headline."
16537 (interactive "P")
16538 (let ((pos (point))
16539 (special (if (consp org-special-ctrl-a/e)
16540 (car org-special-ctrl-a/e)
16541 org-special-ctrl-a/e))
16542 refpos)
16543 (if (org-bound-and-true-p line-move-visual)
16544 (beginning-of-visual-line 1)
16545 (beginning-of-line 1))
16546 (if (and arg (fboundp 'move-beginning-of-line))
16547 (call-interactively 'move-beginning-of-line)
16548 (if (bobp)
16550 (backward-char 1)
16551 (if (org-invisible-p)
16552 (while (and (not (bobp)) (org-invisible-p))
16553 (backward-char 1)
16554 (beginning-of-line 1))
16555 (forward-char 1))))
16556 (when special
16557 (cond
16558 ((and (looking-at org-complex-heading-regexp)
16559 (= (char-after (match-end 1)) ?\ ))
16560 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16561 (point-at-eol)))
16562 (goto-char
16563 (if (eq special t)
16564 (cond ((> pos refpos) refpos)
16565 ((= pos (point)) refpos)
16566 (t (point)))
16567 (cond ((> pos (point)) (point))
16568 ((not (eq last-command this-command)) (point))
16569 (t refpos)))))
16570 ((org-at-item-p)
16571 (goto-char
16572 (if (eq special t)
16573 (cond ((> pos (match-end 4)) (match-end 4))
16574 ((= pos (point)) (match-end 4))
16575 (t (point)))
16576 (cond ((> pos (point)) (point))
16577 ((not (eq last-command this-command)) (point))
16578 (t (match-end 4))))))))
16579 (org-no-warnings
16580 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16582 (defun org-end-of-line (&optional arg)
16583 "Go to the end of the line.
16584 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16585 first attempt, and only move to after the tags when the cursor is already
16586 beyond the end of the headline."
16587 (interactive "P")
16588 (let ((special (if (consp org-special-ctrl-a/e)
16589 (cdr org-special-ctrl-a/e)
16590 org-special-ctrl-a/e)))
16591 (if (or (not special)
16592 (not (org-on-heading-p))
16593 arg)
16594 (call-interactively
16595 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16596 ((fboundp 'move-end-of-line) 'move-end-of-line)
16597 (t 'end-of-line)))
16598 (let ((pos (point)))
16599 (beginning-of-line 1)
16600 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16601 (if (eq special t)
16602 (if (or (< pos (match-beginning 1))
16603 (= pos (match-end 0)))
16604 (goto-char (match-beginning 1))
16605 (goto-char (match-end 0)))
16606 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16607 (goto-char (match-end 0))
16608 (goto-char (match-beginning 1))))
16609 (call-interactively (if (fboundp 'move-end-of-line)
16610 'move-end-of-line
16611 'end-of-line)))))
16612 (org-no-warnings
16613 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16615 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16616 (define-key org-mode-map "\C-e" 'org-end-of-line)
16618 (defun org-backward-sentence (&optional arg)
16619 "Go to beginning of sentence, or beginning of table field.
16620 This will call `backward-sentence' or `org-table-beginning-of-field',
16621 depending on context."
16622 (interactive "P")
16623 (cond
16624 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16625 (t (call-interactively 'backward-sentence))))
16627 (defun org-forward-sentence (&optional arg)
16628 "Go to end of sentence, or end of table field.
16629 This will call `forward-sentence' or `org-table-end-of-field',
16630 depending on context."
16631 (interactive "P")
16632 (cond
16633 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16634 (t (call-interactively 'forward-sentence))))
16636 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16637 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16639 (defun org-kill-line (&optional arg)
16640 "Kill line, to tags or end of line."
16641 (interactive "P")
16642 (cond
16643 ((or (not org-special-ctrl-k)
16644 (bolp)
16645 (not (org-on-heading-p)))
16646 (call-interactively 'kill-line))
16647 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16648 (kill-region (point) (match-beginning 1))
16649 (org-set-tags nil t))
16650 (t (kill-region (point) (point-at-eol)))))
16652 (define-key org-mode-map "\C-k" 'org-kill-line)
16654 (defun org-yank (&optional arg)
16655 "Yank. If the kill is a subtree, treat it specially.
16656 This command will look at the current kill and check if is a single
16657 subtree, or a series of subtrees[1]. If it passes the test, and if the
16658 cursor is at the beginning of a line or after the stars of a currently
16659 empty headline, then the yank is handled specially. How exactly depends
16660 on the value of the following variables, both set by default.
16662 org-yank-folded-subtrees
16663 When set, the subtree(s) will be folded after insertion, but only
16664 if doing so would now swallow text after the yanked text.
16666 org-yank-adjusted-subtrees
16667 When set, the subtree will be promoted or demoted in order to
16668 fit into the local outline tree structure, which means that the level
16669 will be adjusted so that it becomes the smaller one of the two
16670 *visible* surrounding headings.
16672 Any prefix to this command will cause `yank' to be called directly with
16673 no special treatment. In particular, a simple `C-u' prefix will just
16674 plainly yank the text as it is.
16676 \[1] The test checks if the first non-white line is a heading
16677 and if there are no other headings with fewer stars."
16678 (interactive "P")
16679 (org-yank-generic 'yank arg))
16681 (defun org-yank-generic (command arg)
16682 "Perform some yank-like command.
16684 This function implements the behavior described in the `org-yank'
16685 documentation. However, it has been generalized to work for any
16686 interactive command with similar behavior."
16688 ;; pretend to be command COMMAND
16689 (setq this-command command)
16691 (if arg
16692 (call-interactively command)
16694 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16695 (and (org-kill-is-subtree-p)
16696 (or (bolp)
16697 (and (looking-at "[ \t]*$")
16698 (string-match
16699 "\\`\\*+\\'"
16700 (buffer-substring (point-at-bol) (point)))))))
16701 swallowp)
16702 (cond
16703 ((and subtreep org-yank-folded-subtrees)
16704 (let ((beg (point))
16705 end)
16706 (if (and subtreep org-yank-adjusted-subtrees)
16707 (org-paste-subtree nil nil 'for-yank)
16708 (call-interactively command))
16710 (setq end (point))
16711 (goto-char beg)
16712 (when (and (bolp) subtreep
16713 (not (setq swallowp
16714 (org-yank-folding-would-swallow-text beg end))))
16715 (or (looking-at outline-regexp)
16716 (re-search-forward (concat "^" outline-regexp) end t))
16717 (while (and (< (point) end) (looking-at outline-regexp))
16718 (hide-subtree)
16719 (org-cycle-show-empty-lines 'folded)
16720 (condition-case nil
16721 (outline-forward-same-level 1)
16722 (error (goto-char end)))))
16723 (when swallowp
16724 (message
16725 "Inserted text not folded because that would swallow text"))
16727 (goto-char end)
16728 (skip-chars-forward " \t\n\r")
16729 (beginning-of-line 1)
16730 (push-mark beg 'nomsg)))
16731 ((and subtreep org-yank-adjusted-subtrees)
16732 (let ((beg (point-at-bol)))
16733 (org-paste-subtree nil nil 'for-yank)
16734 (push-mark beg 'nomsg)))
16736 (call-interactively command))))))
16738 (defun org-yank-folding-would-swallow-text (beg end)
16739 "Would hide-subtree at BEG swallow any text after END?"
16740 (let (level)
16741 (save-excursion
16742 (goto-char beg)
16743 (when (or (looking-at outline-regexp)
16744 (re-search-forward (concat "^" outline-regexp) end t))
16745 (setq level (org-outline-level)))
16746 (goto-char end)
16747 (skip-chars-forward " \t\r\n\v\f")
16748 (if (or (eobp)
16749 (and (bolp) (looking-at org-outline-regexp)
16750 (<= (org-outline-level) level)))
16751 nil ; Nothing would be swallowed
16752 t)))) ; something would swallow
16754 (define-key org-mode-map "\C-y" 'org-yank)
16756 (defun org-invisible-p ()
16757 "Check if point is at a character currently not visible."
16758 ;; Early versions of noutline don't have `outline-invisible-p'.
16759 (if (fboundp 'outline-invisible-p)
16760 (outline-invisible-p)
16761 (get-char-property (point) 'invisible)))
16763 (defun org-invisible-p2 ()
16764 "Check if point is at a character currently not visible."
16765 (save-excursion
16766 (if (and (eolp) (not (bobp))) (backward-char 1))
16767 ;; Early versions of noutline don't have `outline-invisible-p'.
16768 (if (fboundp 'outline-invisible-p)
16769 (outline-invisible-p)
16770 (get-char-property (point) 'invisible))))
16772 (defun org-back-to-heading (&optional invisible-ok)
16773 "Call `outline-back-to-heading', but provide a better error message."
16774 (condition-case nil
16775 (outline-back-to-heading invisible-ok)
16776 (error (error "Before first headline at position %d in buffer %s"
16777 (point) (current-buffer)))))
16779 (defun org-before-first-heading-p ()
16780 "Before first heading?"
16781 (save-excursion
16782 (null (re-search-backward "^\\*+ " nil t))))
16784 (defun org-on-heading-p (&optional ignored)
16785 (outline-on-heading-p t))
16786 (defun org-at-heading-p (&optional ignored)
16787 (outline-on-heading-p t))
16789 (defun org-at-heading-or-item-p ()
16790 (or (org-on-heading-p) (org-at-item-p)))
16792 (defun org-on-target-p ()
16793 (or (org-in-regexp org-radio-target-regexp)
16794 (org-in-regexp org-target-regexp)))
16796 (defun org-up-heading-all (arg)
16797 "Move to the heading line of which the present line is a subheading.
16798 This function considers both visible and invisible heading lines.
16799 With argument, move up ARG levels."
16800 (if (fboundp 'outline-up-heading-all)
16801 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16802 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16804 (defun org-up-heading-safe ()
16805 "Move to the heading line of which the present line is a subheading.
16806 This version will not throw an error. It will return the level of the
16807 headline found, or nil if no higher level is found.
16809 Also, this function will be a lot faster than `outline-up-heading',
16810 because it relies on stars being the outline starters. This can really
16811 make a significant difference in outlines with very many siblings."
16812 (let (start-level re)
16813 (org-back-to-heading t)
16814 (setq start-level (funcall outline-level))
16815 (if (equal start-level 1)
16817 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16818 (if (re-search-backward re nil t)
16819 (funcall outline-level)))))
16821 (defun org-first-sibling-p ()
16822 "Is this heading the first child of its parents?"
16823 (interactive)
16824 (let ((re (concat "^" outline-regexp))
16825 level l)
16826 (unless (org-at-heading-p t)
16827 (error "Not at a heading"))
16828 (setq level (funcall outline-level))
16829 (save-excursion
16830 (if (not (re-search-backward re nil t))
16832 (setq l (funcall outline-level))
16833 (< l level)))))
16835 (defun org-goto-sibling (&optional previous)
16836 "Goto the next sibling, even if it is invisible.
16837 When PREVIOUS is set, go to the previous sibling instead. Returns t
16838 when a sibling was found. When none is found, return nil and don't
16839 move point."
16840 (let ((fun (if previous 're-search-backward 're-search-forward))
16841 (pos (point))
16842 (re (concat "^" outline-regexp))
16843 level l)
16844 (when (condition-case nil (org-back-to-heading t) (error nil))
16845 (setq level (funcall outline-level))
16846 (catch 'exit
16847 (or previous (forward-char 1))
16848 (while (funcall fun re nil t)
16849 (setq l (funcall outline-level))
16850 (when (< l level) (goto-char pos) (throw 'exit nil))
16851 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16852 (goto-char pos)
16853 nil))))
16855 (defun org-show-siblings ()
16856 "Show all siblings of the current headline."
16857 (save-excursion
16858 (while (org-goto-sibling) (org-flag-heading nil)))
16859 (save-excursion
16860 (while (org-goto-sibling 'previous)
16861 (org-flag-heading nil))))
16863 (defun org-show-hidden-entry ()
16864 "Show an entry where even the heading is hidden."
16865 (save-excursion
16866 (org-show-entry)))
16868 (defun org-flag-heading (flag &optional entry)
16869 "Flag the current heading. FLAG non-nil means make invisible.
16870 When ENTRY is non-nil, show the entire entry."
16871 (save-excursion
16872 (org-back-to-heading t)
16873 ;; Check if we should show the entire entry
16874 (if entry
16875 (progn
16876 (org-show-entry)
16877 (save-excursion
16878 (and (outline-next-heading)
16879 (org-flag-heading nil))))
16880 (outline-flag-region (max (point-min) (1- (point)))
16881 (save-excursion (outline-end-of-heading) (point))
16882 flag))))
16884 (defun org-get-next-sibling ()
16885 "Move to next heading of the same level, and return point.
16886 If there is no such heading, return nil.
16887 This is like outline-next-sibling, but invisible headings are ok."
16888 (let ((level (funcall outline-level)))
16889 (outline-next-heading)
16890 (while (and (not (eobp)) (> (funcall outline-level) level))
16891 (outline-next-heading))
16892 (if (or (eobp) (< (funcall outline-level) level))
16894 (point))))
16896 (defun org-get-last-sibling ()
16897 "Move to previous heading of the same level, and return point.
16898 If there is no such heading, return nil."
16899 (let ((opoint (point))
16900 (level (funcall outline-level)))
16901 (outline-previous-heading)
16902 (when (and (/= (point) opoint) (outline-on-heading-p t))
16903 (while (and (> (funcall outline-level) level)
16904 (not (bobp)))
16905 (outline-previous-heading))
16906 (if (< (funcall outline-level) level)
16908 (point)))))
16910 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16911 ;; This contains an exact copy of the original function, but it uses
16912 ;; `org-back-to-heading', to make it work also in invisible
16913 ;; trees. And is uses an invisible-OK argument.
16914 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16915 ;; Furthermore, when used inside Org, finding the end of a large subtree
16916 ;; with many children and grandchildren etc, this can be much faster
16917 ;; than the outline version.
16918 (org-back-to-heading invisible-OK)
16919 (let ((first t)
16920 (level (funcall outline-level)))
16921 (if (and (org-mode-p) (< level 1000))
16922 ;; A true heading (not a plain list item), in Org-mode
16923 ;; This means we can easily find the end by looking
16924 ;; only for the right number of stars. Using a regexp to do
16925 ;; this is so much faster than using a Lisp loop.
16926 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16927 (forward-char 1)
16928 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16929 ;; something else, do it the slow way
16930 (while (and (not (eobp))
16931 (or first (> (funcall outline-level) level)))
16932 (setq first nil)
16933 (outline-next-heading)))
16934 (unless to-heading
16935 (if (memq (preceding-char) '(?\n ?\^M))
16936 (progn
16937 ;; Go to end of line before heading
16938 (forward-char -1)
16939 (if (memq (preceding-char) '(?\n ?\^M))
16940 ;; leave blank line before heading
16941 (forward-char -1))))))
16942 (point))
16944 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16945 "Use Org version in org-mode, for dramatic speed-up."
16946 (if (eq major-mode 'org-mode)
16947 (progn
16948 (org-end-of-subtree nil t)
16949 (unless (eobp) (backward-char 1)))
16950 ad-do-it))
16952 (defun org-forward-same-level (arg &optional invisible-ok)
16953 "Move forward to the arg'th subheading at same level as this one.
16954 Stop at the first and last subheadings of a superior heading."
16955 (interactive "p")
16956 (org-back-to-heading invisible-ok)
16957 (org-on-heading-p)
16958 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16959 (re (format "^\\*\\{1,%d\\} " level))
16961 (forward-char 1)
16962 (while (> arg 0)
16963 (while (and (re-search-forward re nil 'move)
16964 (setq l (- (match-end 0) (match-beginning 0) 1))
16965 (= l level)
16966 (not invisible-ok)
16967 (org-invisible-p))
16968 (if (< l level) (setq arg 1)))
16969 (setq arg (1- arg)))
16970 (beginning-of-line 1)))
16972 (defun org-backward-same-level (arg &optional invisible-ok)
16973 "Move backward to the arg'th subheading at same level as this one.
16974 Stop at the first and last subheadings of a superior heading."
16975 (interactive "p")
16976 (org-back-to-heading)
16977 (org-on-heading-p)
16978 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16979 (re (format "^\\*\\{1,%d\\} " level))
16981 (while (> arg 0)
16982 (while (and (re-search-backward re nil 'move)
16983 (setq l (- (match-end 0) (match-beginning 0) 1))
16984 (= l level)
16985 (not invisible-ok)
16986 (org-invisible-p))
16987 (if (< l level) (setq arg 1)))
16988 (setq arg (1- arg)))))
16990 (defun org-show-subtree ()
16991 "Show everything after this heading at deeper levels."
16992 (outline-flag-region
16993 (point)
16994 (save-excursion
16995 (org-end-of-subtree t t))
16996 nil))
16998 (defun org-show-entry ()
16999 "Show the body directly following this heading.
17000 Show the heading too, if it is currently invisible."
17001 (interactive)
17002 (save-excursion
17003 (condition-case nil
17004 (progn
17005 (org-back-to-heading t)
17006 (outline-flag-region
17007 (max (point-min) (1- (point)))
17008 (save-excursion
17009 (if (re-search-forward
17010 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17011 (match-beginning 1)
17012 (point-max)))
17013 nil)
17014 (org-cycle-hide-drawers 'children))
17015 (error nil))))
17017 (defun org-make-options-regexp (kwds &optional extra)
17018 "Make a regular expression for keyword lines."
17019 (concat
17021 "#?[ \t]*\\+\\("
17022 (mapconcat 'regexp-quote kwds "\\|")
17023 (if extra (concat "\\|" extra))
17024 "\\):[ \t]*"
17025 "\\(.*\\)"))
17027 ;; Make isearch reveal the necessary context
17028 (defun org-isearch-end ()
17029 "Reveal context after isearch exits."
17030 (when isearch-success ; only if search was successful
17031 (if (featurep 'xemacs)
17032 ;; Under XEmacs, the hook is run in the correct place,
17033 ;; we directly show the context.
17034 (org-show-context 'isearch)
17035 ;; In Emacs the hook runs *before* restoring the overlays.
17036 ;; So we have to use a one-time post-command-hook to do this.
17037 ;; (Emacs 22 has a special variable, see function `org-mode')
17038 (unless (and (boundp 'isearch-mode-end-hook-quit)
17039 isearch-mode-end-hook-quit)
17040 ;; Only when the isearch was not quitted.
17041 (org-add-hook 'post-command-hook 'org-isearch-post-command
17042 'append 'local)))))
17044 (defun org-isearch-post-command ()
17045 "Remove self from hook, and show context."
17046 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17047 (org-show-context 'isearch))
17050 ;;;; Integration with and fixes for other packages
17052 ;;; Imenu support
17054 (defvar org-imenu-markers nil
17055 "All markers currently used by Imenu.")
17056 (make-variable-buffer-local 'org-imenu-markers)
17058 (defun org-imenu-new-marker (&optional pos)
17059 "Return a new marker for use by Imenu, and remember the marker."
17060 (let ((m (make-marker)))
17061 (move-marker m (or pos (point)))
17062 (push m org-imenu-markers)
17065 (defun org-imenu-get-tree ()
17066 "Produce the index for Imenu."
17067 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17068 (setq org-imenu-markers nil)
17069 (let* ((n org-imenu-depth)
17070 (re (concat "^" outline-regexp))
17071 (subs (make-vector (1+ n) nil))
17072 (last-level 0)
17073 m level head)
17074 (save-excursion
17075 (save-restriction
17076 (widen)
17077 (goto-char (point-max))
17078 (while (re-search-backward re nil t)
17079 (setq level (org-reduced-level (funcall outline-level)))
17080 (when (<= level n)
17081 (looking-at org-complex-heading-regexp)
17082 (setq head (org-link-display-format
17083 (org-match-string-no-properties 4))
17084 m (org-imenu-new-marker))
17085 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17086 (if (>= level last-level)
17087 (push (cons head m) (aref subs level))
17088 (push (cons head (aref subs (1+ level))) (aref subs level))
17089 (loop for i from (1+ level) to n do (aset subs i nil)))
17090 (setq last-level level)))))
17091 (aref subs 1)))
17093 (eval-after-load "imenu"
17094 '(progn
17095 (add-hook 'imenu-after-jump-hook
17096 (lambda ()
17097 (if (eq major-mode 'org-mode)
17098 (org-show-context 'org-goto))))))
17100 (defun org-link-display-format (link)
17101 "Replace a link with either the description, or the link target
17102 if no description is present"
17103 (save-match-data
17104 (if (string-match org-bracket-link-analytic-regexp link)
17105 (replace-match (or (match-string 5 link)
17106 (concat (match-string 1 link)
17107 (match-string 3 link)))
17108 nil nil link)
17109 link)))
17111 ;; Speedbar support
17113 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17114 "Overlay marking the agenda restriction line in speedbar.")
17115 (org-overlay-put org-speedbar-restriction-lock-overlay
17116 'face 'org-agenda-restriction-lock)
17117 (org-overlay-put org-speedbar-restriction-lock-overlay
17118 'help-echo "Agendas are currently limited to this item.")
17119 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17121 (defun org-speedbar-set-agenda-restriction ()
17122 "Restrict future agenda commands to the location at point in speedbar.
17123 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17124 (interactive)
17125 (require 'org-agenda)
17126 (let (p m tp np dir txt)
17127 (cond
17128 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17129 'org-imenu t))
17130 (setq m (get-text-property p 'org-imenu-marker))
17131 (save-excursion
17132 (save-restriction
17133 (set-buffer (marker-buffer m))
17134 (goto-char m)
17135 (org-agenda-set-restriction-lock 'subtree))))
17136 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17137 'speedbar-function 'speedbar-find-file))
17138 (setq tp (previous-single-property-change
17139 (1+ p) 'speedbar-function)
17140 np (next-single-property-change
17141 tp 'speedbar-function)
17142 dir (speedbar-line-directory)
17143 txt (buffer-substring-no-properties (or tp (point-min))
17144 (or np (point-max))))
17145 (save-excursion
17146 (save-restriction
17147 (set-buffer (find-file-noselect
17148 (let ((default-directory dir))
17149 (expand-file-name txt))))
17150 (unless (org-mode-p)
17151 (error "Cannot restrict to non-Org-mode file"))
17152 (org-agenda-set-restriction-lock 'file))))
17153 (t (error "Don't know how to restrict Org-mode's agenda")))
17154 (org-move-overlay org-speedbar-restriction-lock-overlay
17155 (point-at-bol) (point-at-eol))
17156 (setq current-prefix-arg nil)
17157 (org-agenda-maybe-redo)))
17159 (eval-after-load "speedbar"
17160 '(progn
17161 (speedbar-add-supported-extension ".org")
17162 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17163 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17164 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17165 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17166 (add-hook 'speedbar-visiting-tag-hook
17167 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17170 ;;; Fixes and Hacks for problems with other packages
17172 ;; Make flyspell not check words in links, to not mess up our keymap
17173 (defun org-mode-flyspell-verify ()
17174 "Don't let flyspell put overlays at active buttons."
17175 (and (not (get-text-property (point) 'keymap))
17176 (not (get-text-property (point) 'org-no-flyspell))))
17178 (defun org-remove-flyspell-overlays-in (beg end)
17179 "Remove flyspell overlays in region."
17180 (and (org-bound-and-true-p flyspell-mode)
17181 (fboundp 'flyspell-delete-region-overlays)
17182 (flyspell-delete-region-overlays beg end))
17183 (add-text-properties beg end '(org-no-flyspell t)))
17185 ;; Make `bookmark-jump' show the jump location if it was hidden.
17186 (eval-after-load "bookmark"
17187 '(if (boundp 'bookmark-after-jump-hook)
17188 ;; We can use the hook
17189 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17190 ;; Hook not available, use advice
17191 (defadvice bookmark-jump (after org-make-visible activate)
17192 "Make the position visible."
17193 (org-bookmark-jump-unhide))))
17195 ;; Make sure saveplace show the location if it was hidden
17196 (eval-after-load "saveplace"
17197 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17198 "Make the position visible."
17199 (org-bookmark-jump-unhide)))
17201 (defun org-bookmark-jump-unhide ()
17202 "Unhide the current position, to show the bookmark location."
17203 (and (org-mode-p)
17204 (or (org-invisible-p)
17205 (save-excursion (goto-char (max (point-min) (1- (point))))
17206 (org-invisible-p)))
17207 (org-show-context 'bookmark-jump)))
17209 ;; Make session.el ignore our circular variable
17210 (eval-after-load "session"
17211 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17213 ;;;; Experimental code
17215 (defun org-closed-in-range ()
17216 "Sparse tree of items closed in a certain time range.
17217 Still experimental, may disappear in the future."
17218 (interactive)
17219 ;; Get the time interval from the user.
17220 (let* ((time1 (org-float-time
17221 (org-read-date nil 'to-time nil "Starting date: ")))
17222 (time2 (org-float-time
17223 (org-read-date nil 'to-time nil "End date:")))
17224 ;; callback function
17225 (callback (lambda ()
17226 (let ((time
17227 (org-float-time
17228 (apply 'encode-time
17229 (org-parse-time-string
17230 (match-string 1))))))
17231 ;; check if time in interval
17232 (and (>= time time1) (<= time time2))))))
17233 ;; make tree, check each match with the callback
17234 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17236 ;;;; Finish up
17238 (provide 'org)
17240 (run-hooks 'org-load-hook)
17242 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17244 ;;; org.el ends here