Autoload org-mobile.el
[org-mode.git] / lisp / org.el
blobfd4f3effea8585dba5ce2c65e7306a3367af9b86
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
290 #+STARTUP: nofold
291 #+STARTUP: content"
292 :group 'org-startup
293 :type '(choice
294 (const :tag "nofold: show all" nil)
295 (const :tag "fold: overview" t)
296 (const :tag "content: all headlines" content)))
298 (defcustom org-startup-truncated t
299 "Non-nil means, entering Org-mode will set `truncate-lines'.
300 This is useful since some lines containing links can be very long and
301 uninteresting. Also tables look terrible when wrapped."
302 :group 'org-startup
303 :type 'boolean)
305 (defcustom org-startup-indented nil
306 "Non-nil means, turn on `org-indent-mode' on startup.
307 This can also be configured on a per-file basis by adding one of
308 the following lines anywhere in the buffer:
310 #+STARTUP: indent
311 #+STARTUP: noindent"
312 :group 'org-structure
313 :type '(choice
314 (const :tag "Not" nil)
315 (const :tag "Globally (slow on startup in large files)" t)))
317 (defcustom org-startup-align-all-tables nil
318 "Non-nil means, align all tables when visiting a file.
319 This is useful when the column width in tables is forced with <N> cookies
320 in table fields. Such tables will look correct only after the first re-align.
321 This can also be configured on a per-file basis by adding one of
322 the following lines anywhere in the buffer:
323 #+STARTUP: align
324 #+STARTUP: noalign"
325 :group 'org-startup
326 :type 'boolean)
328 (defcustom org-insert-mode-line-in-empty-file nil
329 "Non-nil means insert the first line setting Org-mode in empty files.
330 When the function `org-mode' is called interactively in an empty file, this
331 normally means that the file name does not automatically trigger Org-mode.
332 To ensure that the file will always be in Org-mode in the future, a
333 line enforcing Org-mode will be inserted into the buffer, if this option
334 has been set."
335 :group 'org-startup
336 :type 'boolean)
338 (defcustom org-replace-disputed-keys nil
339 "Non-nil means use alternative key bindings for some keys.
340 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
341 These keys are also used by other packages like shift-selection-mode'
342 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
343 If you want to use Org-mode together with one of these other modes,
344 or more generally if you would like to move some Org-mode commands to
345 other keys, set this variable and configure the keys with the variable
346 `org-disputed-keys'.
348 This option is only relevant at load-time of Org-mode, and must be set
349 *before* org.el is loaded. Changing it requires a restart of Emacs to
350 become effective."
351 :group 'org-startup
352 :type 'boolean)
354 (defcustom org-use-extra-keys nil
355 "Non-nil means use extra key sequence definitions for certain
356 commands. This happens automatically if you run XEmacs or if
357 window-system is nil. This variable lets you do the same
358 manually. You must set it before loading org.
360 Example: on Carbon Emacs 22 running graphically, with an external
361 keyboard on a Powerbook, the default way of setting M-left might
362 not work for either Alt or ESC. Setting this variable will make
363 it work for ESC."
364 :group 'org-startup
365 :type 'boolean)
367 (if (fboundp 'defvaralias)
368 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
370 (defcustom org-disputed-keys
371 '(([(shift up)] . [(meta p)])
372 ([(shift down)] . [(meta n)])
373 ([(shift left)] . [(meta -)])
374 ([(shift right)] . [(meta +)])
375 ([(control shift right)] . [(meta shift +)])
376 ([(control shift left)] . [(meta shift -)]))
377 "Keys for which Org-mode and other modes compete.
378 This is an alist, cars are the default keys, second element specifies
379 the alternative to use when `org-replace-disputed-keys' is t.
381 Keys can be specified in any syntax supported by `define-key'.
382 The value of this option takes effect only at Org-mode's startup,
383 therefore you'll have to restart Emacs to apply it after changing."
384 :group 'org-startup
385 :type 'alist)
387 (defun org-key (key)
388 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
389 Or return the original if not disputed."
390 (if org-replace-disputed-keys
391 (let* ((nkey (key-description key))
392 (x (org-find-if (lambda (x)
393 (equal (key-description (car x)) nkey))
394 org-disputed-keys)))
395 (if x (cdr x) key))
396 key))
398 (defun org-find-if (predicate seq)
399 (catch 'exit
400 (while seq
401 (if (funcall predicate (car seq))
402 (throw 'exit (car seq))
403 (pop seq)))))
405 (defun org-defkey (keymap key def)
406 "Define a key, possibly translated, as returned by `org-key'."
407 (define-key keymap (org-key key) def))
409 (defcustom org-ellipsis nil
410 "The ellipsis to use in the Org-mode outline.
411 When nil, just use the standard three dots. When a string, use that instead,
412 When a face, use the standard 3 dots, but with the specified face.
413 The change affects only Org-mode (which will then use its own display table).
414 Changing this requires executing `M-x org-mode' in a buffer to become
415 effective."
416 :group 'org-startup
417 :type '(choice (const :tag "Default" nil)
418 (face :tag "Face" :value org-warning)
419 (string :tag "String" :value "...#")))
421 (defvar org-display-table nil
422 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
424 (defgroup org-keywords nil
425 "Keywords in Org-mode."
426 :tag "Org Keywords"
427 :group 'org)
429 (defcustom org-deadline-string "DEADLINE:"
430 "String to mark deadline entries.
431 A deadline is this string, followed by a time stamp. Should be a word,
432 terminated by a colon. You can insert a schedule keyword and
433 a timestamp with \\[org-deadline].
434 Changes become only effective after restarting Emacs."
435 :group 'org-keywords
436 :type 'string)
438 (defcustom org-scheduled-string "SCHEDULED:"
439 "String to mark scheduled TODO entries.
440 A schedule is this string, followed by a time stamp. Should be a word,
441 terminated by a colon. You can insert a schedule keyword and
442 a timestamp with \\[org-schedule].
443 Changes become only effective after restarting Emacs."
444 :group 'org-keywords
445 :type 'string)
447 (defcustom org-closed-string "CLOSED:"
448 "String used as the prefix for timestamps logging closing a TODO entry."
449 :group 'org-keywords
450 :type 'string)
452 (defcustom org-clock-string "CLOCK:"
453 "String used as prefix for timestamps clocking work hours on an item."
454 :group 'org-keywords
455 :type 'string)
457 (defcustom org-comment-string "COMMENT"
458 "Entries starting with this keyword will never be exported.
459 An entry can be toggled between COMMENT and normal with
460 \\[org-toggle-comment].
461 Changes become only effective after restarting Emacs."
462 :group 'org-keywords
463 :type 'string)
465 (defcustom org-quote-string "QUOTE"
466 "Entries starting with this keyword will be exported in fixed-width font.
467 Quoting applies only to the text in the entry following the headline, and does
468 not extend beyond the next headline, even if that is lower level.
469 An entry can be toggled between QUOTE and normal with
470 \\[org-toggle-fixed-width-section]."
471 :group 'org-keywords
472 :type 'string)
474 (defconst org-repeat-re
475 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
476 "Regular expression for specifying repeated events.
477 After a match, group 1 contains the repeat expression.")
479 (defgroup org-structure nil
480 "Options concerning the general structure of Org-mode files."
481 :tag "Org Structure"
482 :group 'org)
484 (defgroup org-reveal-location nil
485 "Options about how to make context of a location visible."
486 :tag "Org Reveal Location"
487 :group 'org-structure)
489 (defconst org-context-choice
490 '(choice
491 (const :tag "Always" t)
492 (const :tag "Never" nil)
493 (repeat :greedy t :tag "Individual contexts"
494 (cons
495 (choice :tag "Context"
496 (const agenda)
497 (const org-goto)
498 (const occur-tree)
499 (const tags-tree)
500 (const link-search)
501 (const mark-goto)
502 (const bookmark-jump)
503 (const isearch)
504 (const default))
505 (boolean))))
506 "Contexts for the reveal options.")
508 (defcustom org-show-hierarchy-above '((default . t))
509 "Non-nil means, show full hierarchy when revealing a location.
510 Org-mode often shows locations in an org-mode file which might have
511 been invisible before. When this is set, the hierarchy of headings
512 above the exposed location is shown.
513 Turning this off for example for sparse trees makes them very compact.
514 Instead of t, this can also be an alist specifying this option for different
515 contexts. Valid contexts are
516 agenda when exposing an entry from the agenda
517 org-goto when using the command `org-goto' on key C-c C-j
518 occur-tree when using the command `org-occur' on key C-c /
519 tags-tree when constructing a sparse tree based on tags matches
520 link-search when exposing search matches associated with a link
521 mark-goto when exposing the jump goal of a mark
522 bookmark-jump when exposing a bookmark location
523 isearch when exiting from an incremental search
524 default default for all contexts not set explicitly"
525 :group 'org-reveal-location
526 :type org-context-choice)
528 (defcustom org-show-following-heading '((default . nil))
529 "Non-nil means, show following heading when revealing a location.
530 Org-mode often shows locations in an org-mode file which might have
531 been invisible before. When this is set, the heading following the
532 match is shown.
533 Turning this off for example for sparse trees makes them very compact,
534 but makes it harder to edit the location of the match. In such a case,
535 use the command \\[org-reveal] to show more context.
536 Instead of t, this can also be an alist specifying this option for different
537 contexts. See `org-show-hierarchy-above' for valid contexts."
538 :group 'org-reveal-location
539 :type org-context-choice)
541 (defcustom org-show-siblings '((default . nil) (isearch t))
542 "Non-nil means, show all sibling heading when revealing a location.
543 Org-mode often shows locations in an org-mode file which might have
544 been invisible before. When this is set, the sibling of the current entry
545 heading are all made visible. If `org-show-hierarchy-above' is t,
546 the same happens on each level of the hierarchy above the current entry.
548 By default this is on for the isearch context, off for all other contexts.
549 Turning this off for example for sparse trees makes them very compact,
550 but makes it harder to edit the location of the match. In such a case,
551 use the command \\[org-reveal] to show more context.
552 Instead of t, this can also be an alist specifying this option for different
553 contexts. See `org-show-hierarchy-above' for valid contexts."
554 :group 'org-reveal-location
555 :type org-context-choice)
557 (defcustom org-show-entry-below '((default . nil))
558 "Non-nil means, show the entry below a headline when revealing a location.
559 Org-mode often shows locations in an org-mode file which might have
560 been invisible before. When this is set, the text below the headline that is
561 exposed is also shown.
563 By default this is off for all contexts.
564 Instead of t, this can also be an alist specifying this option for different
565 contexts. See `org-show-hierarchy-above' for valid contexts."
566 :group 'org-reveal-location
567 :type org-context-choice)
569 (defcustom org-indirect-buffer-display 'other-window
570 "How should indirect tree buffers be displayed?
571 This applies to indirect buffers created with the commands
572 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
573 Valid values are:
574 current-window Display in the current window
575 other-window Just display in another window.
576 dedicated-frame Create one new frame, and re-use it each time.
577 new-frame Make a new frame each time. Note that in this case
578 previously-made indirect buffers are kept, and you need to
579 kill these buffers yourself."
580 :group 'org-structure
581 :group 'org-agenda-windows
582 :type '(choice
583 (const :tag "In current window" current-window)
584 (const :tag "In current frame, other window" other-window)
585 (const :tag "Each time a new frame" new-frame)
586 (const :tag "One dedicated frame" dedicated-frame)))
588 (defgroup org-cycle nil
589 "Options concerning visibility cycling in Org-mode."
590 :tag "Org Cycle"
591 :group 'org-structure)
593 (defcustom org-cycle-skip-children-state-if-no-children t
594 "Non-nil means, skip CHILDREN state in entries that don't have any."
595 :group 'org-cycle
596 :type 'boolean)
598 (defcustom org-cycle-max-level nil
599 "Maximum level which should still be subject to visibility cycling.
600 Levels higher than this will, for cycling, be treated as text, not a headline.
601 When `org-odd-levels-only' is set, a value of N in this variable actually
602 means 2N-1 stars as the limiting headline.
603 When nil, cycle all levels.
604 Note that the limiting level of cycling is also influenced by
605 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
606 `org-inlinetask-min-level' is, cycling will be limited to levels one less
607 than its value."
608 :group 'org-cycle
609 :type '(choice
610 (const :tag "No limit" nil)
611 (integer :tag "Maximum level")))
613 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
614 "Names of drawers. Drawers are not opened by cycling on the headline above.
615 Drawers only open with a TAB on the drawer line itself. A drawer looks like
616 this:
617 :DRAWERNAME:
618 .....
619 :END:
620 The drawer \"PROPERTIES\" is special for capturing properties through
621 the property API.
623 Drawers can be defined on the per-file basis with a line like:
625 #+DRAWERS: HIDDEN STATE PROPERTIES"
626 :group 'org-structure
627 :group 'org-cycle
628 :type '(repeat (string :tag "Drawer Name")))
630 (defcustom org-hide-block-startup nil
631 "Non-nil means, , entering Org-mode will fold all blocks.
632 This can also be set in on a per-file basis with
634 #+STARTUP: hideblocks
635 #+STARTUP: showblocks"
636 :group 'org-startup
637 :group 'org-cycle
638 :type 'boolean)
640 (defcustom org-cycle-global-at-bob nil
641 "Cycle globally if cursor is at beginning of buffer and not at a headline.
642 This makes it possible to do global cycling without having to use S-TAB or
643 C-u TAB. For this special case to work, the first line of the buffer
644 must not be a headline - it may be empty or some other text. When used in
645 this way, `org-cycle-hook' is disables temporarily, to make sure the
646 cursor stays at the beginning of the buffer.
647 When this option is nil, don't do anything special at the beginning
648 of the buffer."
649 :group 'org-cycle
650 :type 'boolean)
652 (defcustom org-cycle-emulate-tab t
653 "Where should `org-cycle' emulate TAB.
654 nil Never
655 white Only in completely white lines
656 whitestart Only at the beginning of lines, before the first non-white char
657 t Everywhere except in headlines
658 exc-hl-bol Everywhere except at the start of a headline
659 If TAB is used in a place where it does not emulate TAB, the current subtree
660 visibility is cycled."
661 :group 'org-cycle
662 :type '(choice (const :tag "Never" nil)
663 (const :tag "Only in completely white lines" white)
664 (const :tag "Before first char in a line" whitestart)
665 (const :tag "Everywhere except in headlines" t)
666 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
669 (defcustom org-cycle-separator-lines 2
670 "Number of empty lines needed to keep an empty line between collapsed trees.
671 If you leave an empty line between the end of a subtree and the following
672 headline, this empty line is hidden when the subtree is folded.
673 Org-mode will leave (exactly) one empty line visible if the number of
674 empty lines is equal or larger to the number given in this variable.
675 So the default 2 means, at least 2 empty lines after the end of a subtree
676 are needed to produce free space between a collapsed subtree and the
677 following headline.
679 If the number is negative, and the number of empty lines is at least -N,
680 all empty lines are shown.
682 Special case: when 0, never leave empty lines in collapsed view."
683 :group 'org-cycle
684 :type 'integer)
685 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
687 (defcustom org-pre-cycle-hook nil
688 "Hook that is run before visibility cycling is happening.
689 The function(s) in this hook must accept a single argument which indicates
690 the new state that will be set right after running this hook. The
691 argument is a symbol. Before a global state change, it can have the values
692 `overview', `content', or `all'. Before a local state change, it can have
693 the values `folded', `children', or `subtree'."
694 :group 'org-cycle
695 :type 'hook)
697 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
698 org-cycle-hide-drawers
699 org-cycle-show-empty-lines
700 org-optimize-window-after-visibility-change)
701 "Hook that is run after `org-cycle' has changed the buffer visibility.
702 The function(s) in this hook must accept a single argument which indicates
703 the new state that was set by the most recent `org-cycle' command. The
704 argument is a symbol. After a global state change, it can have the values
705 `overview', `content', or `all'. After a local state change, it can have
706 the values `folded', `children', or `subtree'."
707 :group 'org-cycle
708 :type 'hook)
710 (defgroup org-edit-structure nil
711 "Options concerning structure editing in Org-mode."
712 :tag "Org Edit Structure"
713 :group 'org-structure)
715 (defcustom org-odd-levels-only nil
716 "Non-nil means, skip even levels and only use odd levels for the outline.
717 This has the effect that two stars are being added/taken away in
718 promotion/demotion commands. It also influences how levels are
719 handled by the exporters.
720 Changing it requires restart of `font-lock-mode' to become effective
721 for fontification also in regions already fontified.
722 You may also set this on a per-file basis by adding one of the following
723 lines to the buffer:
725 #+STARTUP: odd
726 #+STARTUP: oddeven"
727 :group 'org-edit-structure
728 :group 'org-font-lock
729 :type 'boolean)
731 (defcustom org-adapt-indentation t
732 "Non-nil means, adapt indentation to outline node level.
734 When this variable is set, Org assumes that you write outlines by
735 indenting text in each node to align with the headline (after the stars).
736 The following issues are influenced by this variable:
738 - When this is set and the *entire* text in an entry is indented, the
739 indentation is increased by one space in a demotion command, and
740 decreased by one in a promotion command. If any line in the entry
741 body starts with text at column 0, indentation is not changed at all.
743 - Property drawers and planning information is inserted indented when
744 this variable s set. When nil, they will not be indented.
746 - TAB indents a line relative to context. The lines below a headline
747 will be indented when this variable is set.
749 Note that this is all about true indentation, by adding and removing
750 space characters. See also `org-indent.el' which does level-dependent
751 indentation in a virtual way, i.e. at display time in Emacs."
752 :group 'org-edit-structure
753 :type 'boolean)
755 (defcustom org-special-ctrl-a/e nil
756 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
758 When t, `C-a' will bring back the cursor to the beginning of the
759 headline text, i.e. after the stars and after a possible TODO keyword.
760 In an item, this will be the position after the bullet.
761 When the cursor is already at that position, another `C-a' will bring
762 it to the beginning of the line.
764 `C-e' will jump to the end of the headline, ignoring the presence of tags
765 in the headline. A second `C-e' will then jump to the true end of the
766 line, after any tags.
768 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
769 going to the true line boundary first. Only a directly following, identical
770 keypress will bring the cursor to the special positions.
772 This may also be a cons cell where the behavior for `C-a' and `C-e' is
773 set separately."
774 :group 'org-edit-structure
775 :type '(choice
776 (const :tag "off" nil)
777 (const :tag "after stars/bullet and before tags first" t)
778 (const :tag "true line boundary first" reversed)
779 (cons :tag "Set C-a and C-e separately"
780 (choice :tag "Special C-a"
781 (const :tag "off" nil)
782 (const :tag "after stars/bullet first" t)
783 (const :tag "before stars/bullet first" reversed))
784 (choice :tag "Special C-e"
785 (const :tag "off" nil)
786 (const :tag "before tags first" t)
787 (const :tag "after tags first" reversed)))))
788 (if (fboundp 'defvaralias)
789 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
791 (defcustom org-special-ctrl-k nil
792 "Non-nil means `C-k' will behave specially in headlines.
793 When nil, `C-k' will call the default `kill-line' command.
794 When t, the following will happen while the cursor is in the headline:
796 - When the cursor is at the beginning of a headline, kill the entire
797 line and possible the folded subtree below the line.
798 - When in the middle of the headline text, kill the headline up to the tags.
799 - When after the headline text, kill the tags."
800 :group 'org-edit-structure
801 :type 'boolean)
803 (defcustom org-yank-folded-subtrees t
804 "Non-nil means, when yanking subtrees, fold them.
805 If the kill is a single subtree, or a sequence of subtrees, i.e. if
806 it starts with a heading and all other headings in it are either children
807 or siblings, then fold all the subtrees. However, do this only if no
808 text after the yank would be swallowed into a folded tree by this action."
809 :group 'org-edit-structure
810 :type 'boolean)
812 (defcustom org-yank-adjusted-subtrees nil
813 "Non-nil means, when yanking subtrees, adjust the level.
814 With this setting, `org-paste-subtree' is used to insert the subtree, see
815 this function for details."
816 :group 'org-edit-structure
817 :type 'boolean)
819 (defcustom org-M-RET-may-split-line '((default . t))
820 "Non-nil means, M-RET will split the line at the cursor position.
821 When nil, it will go to the end of the line before making a
822 new line.
823 You may also set this option in a different way for different
824 contexts. Valid contexts are:
826 headline when creating a new headline
827 item when creating a new item
828 table in a table field
829 default the value to be used for all contexts not explicitly
830 customized"
831 :group 'org-structure
832 :group 'org-table
833 :type '(choice
834 (const :tag "Always" t)
835 (const :tag "Never" nil)
836 (repeat :greedy t :tag "Individual contexts"
837 (cons
838 (choice :tag "Context"
839 (const headline)
840 (const item)
841 (const table)
842 (const default))
843 (boolean)))))
846 (defcustom org-insert-heading-respect-content nil
847 "Non-nil means, insert new headings after the current subtree.
848 When nil, the new heading is created directly after the current line.
849 The commands \\[org-insert-heading-respect-content] and
850 \\[org-insert-todo-heading-respect-content] turn this variable on
851 for the duration of the command."
852 :group 'org-structure
853 :type 'boolean)
855 (defcustom org-blank-before-new-entry '((heading . auto)
856 (plain-list-item . auto))
857 "Should `org-insert-heading' leave a blank line before new heading/item?
858 The value is an alist, with `heading' and `plain-list-item' as car,
859 and a boolean flag as cdr. For plain lists, if the variable
860 `org-empty-line-terminates-plain-lists' is set, the setting here
861 is ignored and no empty line is inserted, to keep the list in tact."
862 :group 'org-edit-structure
863 :type '(list
864 (cons (const heading)
865 (choice (const :tag "Never" nil)
866 (const :tag "Always" t)
867 (const :tag "Auto" auto)))
868 (cons (const plain-list-item)
869 (choice (const :tag "Never" nil)
870 (const :tag "Always" t)
871 (const :tag "Auto" auto)))))
873 (defcustom org-insert-heading-hook nil
874 "Hook being run after inserting a new heading."
875 :group 'org-edit-structure
876 :type 'hook)
878 (defcustom org-enable-fixed-width-editor t
879 "Non-nil means, lines starting with \":\" are treated as fixed-width.
880 This currently only means, they are never auto-wrapped.
881 When nil, such lines will be treated like ordinary lines.
882 See also the QUOTE keyword."
883 :group 'org-edit-structure
884 :type 'boolean)
887 (defcustom org-goto-auto-isearch t
888 "Non-nil means, typing characters in org-goto starts incremental search."
889 :group 'org-edit-structure
890 :type 'boolean)
892 (defgroup org-sparse-trees nil
893 "Options concerning sparse trees in Org-mode."
894 :tag "Org Sparse Trees"
895 :group 'org-structure)
897 (defcustom org-highlight-sparse-tree-matches t
898 "Non-nil means, highlight all matches that define a sparse tree.
899 The highlights will automatically disappear the next time the buffer is
900 changed by an edit command."
901 :group 'org-sparse-trees
902 :type 'boolean)
904 (defcustom org-remove-highlights-with-change t
905 "Non-nil means, any change to the buffer will remove temporary highlights.
906 Such highlights are created by `org-occur' and `org-clock-display'.
907 When nil, `C-c C-c needs to be used to get rid of the highlights.
908 The highlights created by `org-preview-latex-fragment' always need
909 `C-c C-c' to be removed."
910 :group 'org-sparse-trees
911 :group 'org-time
912 :type 'boolean)
915 (defcustom org-occur-hook '(org-first-headline-recenter)
916 "Hook that is run after `org-occur' has constructed a sparse tree.
917 This can be used to recenter the window to show as much of the structure
918 as possible."
919 :group 'org-sparse-trees
920 :type 'hook)
922 (defgroup org-imenu-and-speedbar nil
923 "Options concerning imenu and speedbar in Org-mode."
924 :tag "Org Imenu and Speedbar"
925 :group 'org-structure)
927 (defcustom org-imenu-depth 2
928 "The maximum level for Imenu access to Org-mode headlines.
929 This also applied for speedbar access."
930 :group 'org-imenu-and-speedbar
931 :type 'integer)
933 (defgroup org-table nil
934 "Options concerning tables in Org-mode."
935 :tag "Org Table"
936 :group 'org)
938 (defcustom org-enable-table-editor 'optimized
939 "Non-nil means, lines starting with \"|\" are handled by the table editor.
940 When nil, such lines will be treated like ordinary lines.
942 When equal to the symbol `optimized', the table editor will be optimized to
943 do the following:
944 - Automatic overwrite mode in front of whitespace in table fields.
945 This makes the structure of the table stay in tact as long as the edited
946 field does not exceed the column width.
947 - Minimize the number of realigns. Normally, the table is aligned each time
948 TAB or RET are pressed to move to another field. With optimization this
949 happens only if changes to a field might have changed the column width.
950 Optimization requires replacing the functions `self-insert-command',
951 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
952 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
953 very good at guessing when a re-align will be necessary, but you can always
954 force one with \\[org-ctrl-c-ctrl-c].
956 If you would like to use the optimized version in Org-mode, but the
957 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
959 This variable can be used to turn on and off the table editor during a session,
960 but in order to toggle optimization, a restart is required.
962 See also the variable `org-table-auto-blank-field'."
963 :group 'org-table
964 :type '(choice
965 (const :tag "off" nil)
966 (const :tag "on" t)
967 (const :tag "on, optimized" optimized)))
969 (defcustom org-self-insert-cluster-for-undo t
970 "Non-nil means cluster self-insert commands for undo when possible.
971 If this is set, then, like in the Emacs command loop, 20 consequtive
972 characters will be undone together.
973 This is configurable, because there is some impact on typing performance."
974 :group 'org-table
975 :type 'boolean)
977 (defcustom org-table-tab-recognizes-table.el t
978 "Non-nil means, TAB will automatically notice a table.el table.
979 When it sees such a table, it moves point into it and - if necessary -
980 calls `table-recognize-table'."
981 :group 'org-table-editing
982 :type 'boolean)
984 (defgroup org-link nil
985 "Options concerning links in Org-mode."
986 :tag "Org Link"
987 :group 'org)
989 (defvar org-link-abbrev-alist-local nil
990 "Buffer-local version of `org-link-abbrev-alist', which see.
991 The value of this is taken from the #+LINK lines.")
992 (make-variable-buffer-local 'org-link-abbrev-alist-local)
994 (defcustom org-link-abbrev-alist nil
995 "Alist of link abbreviations.
996 The car of each element is a string, to be replaced at the start of a link.
997 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
998 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1000 [[linkkey:tag][description]]
1002 The 'linkkey' must be a word word, starting with a letter, followed
1003 by letters, numbers, '-' or '_'.
1005 If REPLACE is a string, the tag will simply be appended to create the link.
1006 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1007 the placeholder \"%h\" will cause a url-encoded version of the tag to
1008 be inserted at that point (see the function `url-hexify-string').
1010 REPLACE may also be a function that will be called with the tag as the
1011 only argument to create the link, which should be returned as a string.
1013 See the manual for examples."
1014 :group 'org-link
1015 :type '(repeat
1016 (cons
1017 (string :tag "Protocol")
1018 (choice
1019 (string :tag "Format")
1020 (function)))))
1022 (defcustom org-descriptive-links t
1023 "Non-nil means, hide link part and only show description of bracket links.
1024 Bracket links are like [[link][description]]. This variable sets the initial
1025 state in new org-mode buffers. The setting can then be toggled on a
1026 per-buffer basis from the Org->Hyperlinks menu."
1027 :group 'org-link
1028 :type 'boolean)
1030 (defcustom org-link-file-path-type 'adaptive
1031 "How the path name in file links should be stored.
1032 Valid values are:
1034 relative Relative to the current directory, i.e. the directory of the file
1035 into which the link is being inserted.
1036 absolute Absolute path, if possible with ~ for home directory.
1037 noabbrev Absolute path, no abbreviation of home directory.
1038 adaptive Use relative path for files in the current directory and sub-
1039 directories of it. For other files, use an absolute path."
1040 :group 'org-link
1041 :type '(choice
1042 (const relative)
1043 (const absolute)
1044 (const noabbrev)
1045 (const adaptive)))
1047 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1048 "Types of links that should be activated in Org-mode files.
1049 This is a list of symbols, each leading to the activation of a certain link
1050 type. In principle, it does not hurt to turn on most link types - there may
1051 be a small gain when turning off unused link types. The types are:
1053 bracket The recommended [[link][description]] or [[link]] links with hiding.
1054 angular Links in angular brackets that may contain whitespace like
1055 <bbdb:Carsten Dominik>.
1056 plain Plain links in normal text, no whitespace, like http://google.com.
1057 radio Text that is matched by a radio target, see manual for details.
1058 tag Tag settings in a headline (link to tag search).
1059 date Time stamps (link to calendar).
1060 footnote Footnote labels.
1062 Changing this variable requires a restart of Emacs to become effective."
1063 :group 'org-link
1064 :type '(set :greedy t
1065 (const :tag "Double bracket links (new style)" bracket)
1066 (const :tag "Angular bracket links (old style)" angular)
1067 (const :tag "Plain text links" plain)
1068 (const :tag "Radio target matches" radio)
1069 (const :tag "Tags" tag)
1070 (const :tag "Timestamps" date)
1071 (const :tag "Footnotes" footnote)))
1073 (defcustom org-make-link-description-function nil
1074 "Function to use to generate link descriptions from links. If
1075 nil the link location will be used. This function must take two
1076 parameters; the first is the link and the second the description
1077 org-insert-link has generated, and should return the description
1078 to use."
1079 :group 'org-link
1080 :type 'function)
1082 (defgroup org-link-store nil
1083 "Options concerning storing links in Org-mode."
1084 :tag "Org Store Link"
1085 :group 'org-link)
1087 (defcustom org-email-link-description-format "Email %c: %.30s"
1088 "Format of the description part of a link to an email or usenet message.
1089 The following %-escapes will be replaced by corresponding information:
1091 %F full \"From\" field
1092 %f name, taken from \"From\" field, address if no name
1093 %T full \"To\" field
1094 %t first name in \"To\" field, address if no name
1095 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1096 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1097 %s subject
1098 %m message-id.
1100 You may use normal field width specification between the % and the letter.
1101 This is for example useful to limit the length of the subject.
1103 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1104 :group 'org-link-store
1105 :type 'string)
1107 (defcustom org-from-is-user-regexp
1108 (let (r1 r2)
1109 (when (and user-mail-address (not (string= user-mail-address "")))
1110 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1111 (when (and user-full-name (not (string= user-full-name "")))
1112 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1113 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1114 "Regexp matched against the \"From:\" header of an email or usenet message.
1115 It should match if the message is from the user him/herself."
1116 :group 'org-link-store
1117 :type 'regexp)
1119 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1120 "Non-nil means, storing a link to an Org file will use entry IDs.
1122 Note that before this variable is even considered, org-id must be loaded,
1123 so please customize `org-modules' and turn it on.
1125 The variable can have the following values:
1127 t Create an ID if needed to make a link to the current entry.
1129 create-if-interactive
1130 If `org-store-link' is called directly (interactively, as a user
1131 command), do create an ID to support the link. But when doing the
1132 job for remember, only use the ID if it already exists. The
1133 purpose of this setting is to avoid proliferation of unwanted
1134 IDs, just because you happen to be in an Org file when you
1135 call `org-remember' that automatically and preemptively
1136 creates a link. If you do want to get an ID link in a remember
1137 template to an entry not having an ID, create it first by
1138 explicitly creating a link to it, using `C-c C-l' first.
1140 create-if-interactive-and-no-custom-id
1141 Like create-if-interactive, but do not create an ID if there is
1142 a CUSTOM_ID property defined in the entry. This is the default.
1144 use-existing
1145 Use existing ID, do not create one.
1147 nil Never use an ID to make a link, instead link using a text search for
1148 the headline text."
1149 :group 'org-link-store
1150 :type '(choice
1151 (const :tag "Create ID to make link" t)
1152 (const :tag "Create if storing link interactively"
1153 create-if-interactive)
1154 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1155 create-if-interactive-and-no-custom-id)
1156 (const :tag "Only use existing" use-existing)
1157 (const :tag "Do not use ID to create link" nil)))
1159 (defcustom org-context-in-file-links t
1160 "Non-nil means, file links from `org-store-link' contain context.
1161 A search string will be added to the file name with :: as separator and
1162 used to find the context when the link is activated by the command
1163 `org-open-at-point'.
1164 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1165 negates this setting for the duration of the command."
1166 :group 'org-link-store
1167 :type 'boolean)
1169 (defcustom org-keep-stored-link-after-insertion nil
1170 "Non-nil means, keep link in list for entire session.
1172 The command `org-store-link' adds a link pointing to the current
1173 location to an internal list. These links accumulate during a session.
1174 The command `org-insert-link' can be used to insert links into any
1175 Org-mode file (offering completion for all stored links). When this
1176 option is nil, every link which has been inserted once using \\[org-insert-link]
1177 will be removed from the list, to make completing the unused links
1178 more efficient."
1179 :group 'org-link-store
1180 :type 'boolean)
1182 (defgroup org-link-follow nil
1183 "Options concerning following links in Org-mode."
1184 :tag "Org Follow Link"
1185 :group 'org-link)
1187 (defcustom org-link-translation-function nil
1188 "Function to translate links with different syntax to Org syntax.
1189 This can be used to translate links created for example by the Planner
1190 or emacs-wiki packages to Org syntax.
1191 The function must accept two parameters, a TYPE containing the link
1192 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1193 which is everything after the link protocol. It should return a cons
1194 with possibly modified values of type and path.
1195 Org contains a function for this, so if you set this variable to
1196 `org-translate-link-from-planner', you should be able follow many
1197 links created by planner."
1198 :group 'org-link-follow
1199 :type 'function)
1201 (defcustom org-follow-link-hook nil
1202 "Hook that is run after a link has been followed."
1203 :group 'org-link-follow
1204 :type 'hook)
1206 (defcustom org-tab-follows-link nil
1207 "Non-nil means, on links TAB will follow the link.
1208 Needs to be set before org.el is loaded.
1209 This really should not be used, it does not make sense, and the
1210 implementation is bad."
1211 :group 'org-link-follow
1212 :type 'boolean)
1214 (defcustom org-return-follows-link nil
1215 "Non-nil means, on links RET will follow the link.
1216 Needs to be set before org.el is loaded."
1217 :group 'org-link-follow
1218 :type 'boolean)
1220 (defcustom org-mouse-1-follows-link
1221 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1222 "Non-nil means, mouse-1 on a link will follow the link.
1223 A longer mouse click will still set point. Does not work on XEmacs.
1224 Needs to be set before org.el is loaded."
1225 :group 'org-link-follow
1226 :type 'boolean)
1228 (defcustom org-mark-ring-length 4
1229 "Number of different positions to be recorded in the ring
1230 Changing this requires a restart of Emacs to work correctly."
1231 :group 'org-link-follow
1232 :type 'integer)
1234 (defcustom org-link-frame-setup
1235 '((vm . vm-visit-folder-other-frame)
1236 (gnus . gnus-other-frame)
1237 (file . find-file-other-window))
1238 "Setup the frame configuration for following links.
1239 When following a link with Emacs, it may often be useful to display
1240 this link in another window or frame. This variable can be used to
1241 set this up for the different types of links.
1242 For VM, use any of
1243 `vm-visit-folder'
1244 `vm-visit-folder-other-frame'
1245 For Gnus, use any of
1246 `gnus'
1247 `gnus-other-frame'
1248 `org-gnus-no-new-news'
1249 For FILE, use any of
1250 `find-file'
1251 `find-file-other-window'
1252 `find-file-other-frame'
1253 For the calendar, use the variable `calendar-setup'.
1254 For BBDB, it is currently only possible to display the matches in
1255 another window."
1256 :group 'org-link-follow
1257 :type '(list
1258 (cons (const vm)
1259 (choice
1260 (const vm-visit-folder)
1261 (const vm-visit-folder-other-window)
1262 (const vm-visit-folder-other-frame)))
1263 (cons (const gnus)
1264 (choice
1265 (const gnus)
1266 (const gnus-other-frame)
1267 (const org-gnus-no-new-news)))
1268 (cons (const file)
1269 (choice
1270 (const find-file)
1271 (const find-file-other-window)
1272 (const find-file-other-frame)))))
1274 (defcustom org-display-internal-link-with-indirect-buffer nil
1275 "Non-nil means, use indirect buffer to display infile links.
1276 Activating internal links (from one location in a file to another location
1277 in the same file) normally just jumps to the location. When the link is
1278 activated with a C-u prefix (or with mouse-3), the link is displayed in
1279 another window. When this option is set, the other window actually displays
1280 an indirect buffer clone of the current buffer, to avoid any visibility
1281 changes to the current buffer."
1282 :group 'org-link-follow
1283 :type 'boolean)
1285 (defcustom org-open-non-existing-files nil
1286 "Non-nil means, `org-open-file' will open non-existing files.
1287 When nil, an error will be generated.
1288 This variable applies only to external applications because they
1289 might choke on non-existing files. If the link is to a file that
1290 will be openend in Emacs, the variable is ignored."
1291 :group 'org-link-follow
1292 :type 'boolean)
1294 (defcustom org-open-directory-means-index-dot-org nil
1295 "Non-nil means, a link to a directory really means to index.org.
1296 When nil, following a directory link will run dired or open a finder/explorer
1297 window on that directory."
1298 :group 'org-link-follow
1299 :type 'boolean)
1301 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1302 "Function and arguments to call for following mailto links.
1303 This is a list with the first element being a lisp function, and the
1304 remaining elements being arguments to the function. In string arguments,
1305 %a will be replaced by the address, and %s will be replaced by the subject
1306 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1307 :group 'org-link-follow
1308 :type '(choice
1309 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1310 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1311 (const :tag "message-mail" (message-mail "%a" "%s"))
1312 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1314 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1315 "Non-nil means, ask for confirmation before executing shell links.
1316 Shell links can be dangerous: just think about a link
1318 [[shell:rm -rf ~/*][Google Search]]
1320 This link would show up in your Org-mode document as \"Google Search\",
1321 but really it would remove your entire home directory.
1322 Therefore we advise against setting this variable to nil.
1323 Just change it to `y-or-n-p' if you want to confirm with a
1324 single keystroke rather than having to type \"yes\"."
1325 :group 'org-link-follow
1326 :type '(choice
1327 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1328 (const :tag "with y-or-n (faster)" y-or-n-p)
1329 (const :tag "no confirmation (dangerous)" nil)))
1331 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1332 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1333 Elisp links can be dangerous: just think about a link
1335 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1337 This link would show up in your Org-mode document as \"Google Search\",
1338 but really it would remove your entire home directory.
1339 Therefore we advise against setting this variable to nil.
1340 Just change it to `y-or-n-p' if you want to confirm with a
1341 single keystroke rather than having to type \"yes\"."
1342 :group 'org-link-follow
1343 :type '(choice
1344 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1345 (const :tag "with y-or-n (faster)" y-or-n-p)
1346 (const :tag "no confirmation (dangerous)" nil)))
1348 (defconst org-file-apps-defaults-gnu
1349 '((remote . emacs)
1350 (system . mailcap)
1351 (t . mailcap))
1352 "Default file applications on a UNIX or GNU/Linux system.
1353 See `org-file-apps'.")
1355 (defconst org-file-apps-defaults-macosx
1356 '((remote . emacs)
1357 (t . "open %s")
1358 (system . "open %s")
1359 ("ps.gz" . "gv %s")
1360 ("eps.gz" . "gv %s")
1361 ("dvi" . "xdvi %s")
1362 ("fig" . "xfig %s"))
1363 "Default file applications on a MacOS X system.
1364 The system \"open\" is known as a default, but we use X11 applications
1365 for some files for which the OS does not have a good default.
1366 See `org-file-apps'.")
1368 (defconst org-file-apps-defaults-windowsnt
1369 (list
1370 '(remote . emacs)
1371 (cons t
1372 (list (if (featurep 'xemacs)
1373 'mswindows-shell-execute
1374 'w32-shell-execute)
1375 "open" 'file))
1376 (cons 'system
1377 (list (if (featurep 'xemacs)
1378 'mswindows-shell-execute
1379 'w32-shell-execute)
1380 "open" 'file)))
1381 "Default file applications on a Windows NT system.
1382 The system \"open\" is used for most files.
1383 See `org-file-apps'.")
1385 (defcustom org-file-apps
1387 (auto-mode . emacs)
1388 ("\\.x?html?\\'" . default)
1389 ("\\.pdf\\'" . default)
1391 "External applications for opening `file:path' items in a document.
1392 Org-mode uses system defaults for different file types, but
1393 you can use this variable to set the application for a given file
1394 extension. The entries in this list are cons cells where the car identifies
1395 files and the cdr the corresponding command. Possible values for the
1396 file identifier are
1397 \"regex\" Regular expression matched against the file name. For backward
1398 compatibility, this can also be a string with only alphanumeric
1399 characters, which is then interpreted as an extension.
1400 `directory' Matches a directory
1401 `remote' Matches a remote file, accessible through tramp or efs.
1402 Remote files most likely should be visited through Emacs
1403 because external applications cannot handle such paths.
1404 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1405 so all files Emacs knows how to handle. Using this with
1406 command `emacs' will open most files in Emacs. Beware that this
1407 will also open html files inside Emacs, unless you add
1408 (\"html\" . default) to the list as well.
1409 t Default for files not matched by any of the other options.
1410 `system' The system command to open files, like `open' on Windows
1411 and Mac OS X, and mailcap under GNU/Linux. This is the command
1412 that will be selected if you call `C-c C-o' with a double
1413 `C-u C-u' prefix.
1415 Possible values for the command are:
1416 `emacs' The file will be visited by the current Emacs process.
1417 `default' Use the default application for this file type, which is the
1418 association for t in the list, most likely in the system-specific
1419 part.
1420 This can be used to overrule an unwanted setting in the
1421 system-specific variable.
1422 `system' Use the system command for opening files, like \"open\".
1423 This command is specified by the entry whose car is `system'.
1424 Most likely, the system-specific version of this variable
1425 does define this command, but you can overrule/replace it
1426 here.
1427 string A command to be executed by a shell; %s will be replaced
1428 by the path to the file.
1429 sexp A Lisp form which will be evaluated. The file path will
1430 be available in the Lisp variable `file'.
1431 For more examples, see the system specific constants
1432 `org-file-apps-defaults-macosx'
1433 `org-file-apps-defaults-windowsnt'
1434 `org-file-apps-defaults-gnu'."
1435 :group 'org-link-follow
1436 :type '(repeat
1437 (cons (choice :value ""
1438 (string :tag "Extension")
1439 (const :tag "System command to open files" system)
1440 (const :tag "Default for unrecognized files" t)
1441 (const :tag "Remote file" remote)
1442 (const :tag "Links to a directory" directory)
1443 (const :tag "Any files that have Emacs modes"
1444 auto-mode))
1445 (choice :value ""
1446 (const :tag "Visit with Emacs" emacs)
1447 (const :tag "Use default" default)
1448 (const :tag "Use the system command" system)
1449 (string :tag "Command")
1450 (sexp :tag "Lisp form")))))
1452 (defgroup org-refile nil
1453 "Options concerning refiling entries in Org-mode."
1454 :tag "Org Refile"
1455 :group 'org)
1457 (defcustom org-directory "~/org"
1458 "Directory with org files.
1459 This is just a default location to look for Org files. There is no need
1460 at all to put your files into this directory. It is only used in the
1461 following situations:
1463 1. When a remember template specifies a target file that is not an
1464 absolute path. The path will then be interpreted relative to
1465 `org-directory'
1466 2. When a remember note is filed away in an interactive way (when exiting the
1467 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1468 with `org-directory' as the default path."
1469 :group 'org-refile
1470 :group 'org-remember
1471 :type 'directory)
1473 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1474 "Default target for storing notes.
1475 Used by the hooks for remember.el. This can be a string, or nil to mean
1476 the value of `remember-data-file'.
1477 You can set this on a per-template basis with the variable
1478 `org-remember-templates'."
1479 :group 'org-refile
1480 :group 'org-remember
1481 :type '(choice
1482 (const :tag "Default from remember-data-file" nil)
1483 file))
1485 (defcustom org-goto-interface 'outline
1486 "The default interface to be used for `org-goto'.
1487 Allowed values are:
1488 outline The interface shows an outline of the relevant file
1489 and the correct heading is found by moving through
1490 the outline or by searching with incremental search.
1491 outline-path-completion Headlines in the current buffer are offered via
1492 completion. This is the interface also used by
1493 the refile command."
1494 :group 'org-refile
1495 :type '(choice
1496 (const :tag "Outline" outline)
1497 (const :tag "Outline-path-completion" outline-path-completion)))
1499 (defcustom org-goto-max-level 5
1500 "Maximum level to be considered when running org-goto with refile interface."
1501 :group 'org-refile
1502 :type 'integer)
1504 (defcustom org-reverse-note-order nil
1505 "Non-nil means, store new notes at the beginning of a file or entry.
1506 When nil, new notes will be filed to the end of a file or entry.
1507 This can also be a list with cons cells of regular expressions that
1508 are matched against file names, and values."
1509 :group 'org-remember
1510 :group 'org-refile
1511 :type '(choice
1512 (const :tag "Reverse always" t)
1513 (const :tag "Reverse never" nil)
1514 (repeat :tag "By file name regexp"
1515 (cons regexp boolean))))
1517 (defcustom org-refile-targets nil
1518 "Targets for refiling entries with \\[org-refile].
1519 This is list of cons cells. Each cell contains:
1520 - a specification of the files to be considered, either a list of files,
1521 or a symbol whose function or variable value will be used to retrieve
1522 a file name or a list of file names. If you use `org-agenda-files' for
1523 that, all agenda files will be scanned for targets. Nil means, consider
1524 headings in the current buffer.
1525 - A specification of how to find candidate refile targets. This may be
1526 any of:
1527 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1528 This tag has to be present in all target headlines, inheritance will
1529 not be considered.
1530 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1531 todo keyword.
1532 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1533 headlines that are refiling targets.
1534 - a cons cell (:level . N). Any headline of level N is considered a target.
1535 Note that, when `org-odd-levels-only' is set, level corresponds to
1536 order in hierarchy, not to the number of stars.
1537 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1538 Note that, when `org-odd-levels-only' is set, level corresponds to
1539 order in hierarchy, not to the number of stars.
1541 You can set the variable `org-refile-target-verify-function' to a function
1542 to verify each headline found by the simple critery above.
1544 When this variable is nil, all top-level headlines in the current buffer
1545 are used, equivalent to the value `((nil . (:level . 1))'."
1546 :group 'org-refile
1547 :type '(repeat
1548 (cons
1549 (choice :value org-agenda-files
1550 (const :tag "All agenda files" org-agenda-files)
1551 (const :tag "Current buffer" nil)
1552 (function) (variable) (file))
1553 (choice :tag "Identify target headline by"
1554 (cons :tag "Specific tag" (const :value :tag) (string))
1555 (cons :tag "TODO keyword" (const :value :todo) (string))
1556 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1557 (cons :tag "Level number" (const :value :level) (integer))
1558 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1560 (defcustom org-refile-target-verify-function nil
1561 "Function to verify if the headline at point should be a refile target.
1562 The function will be called without arguments, with point at the
1563 beginning of the headline. It should return t and leave point
1564 where it is if the headline is a valid target for refiling.
1566 If the target should not be selected, the function must return nil.
1567 In addition to this, it may move point to a place from where the search
1568 should be continued. For example, the function may decide that the entire
1569 subtree of the current entry should be excluded and move point to the end
1570 of the subtree."
1571 :group 'org-refile
1572 :type 'function)
1574 (defcustom org-refile-use-outline-path nil
1575 "Non-nil means, provide refile targets as paths.
1576 So a level 3 headline will be available as level1/level2/level3.
1578 When the value is `file', also include the file name (without directory)
1579 into the path. In this case, you can also stop the completion after
1580 the file name, to get entries inserted as top level in the file.
1582 When `full-file-path', include the full file path."
1583 :group 'org-refile
1584 :type '(choice
1585 (const :tag "Not" nil)
1586 (const :tag "Yes" t)
1587 (const :tag "Start with file name" file)
1588 (const :tag "Start with full file path" full-file-path)))
1590 (defcustom org-outline-path-complete-in-steps t
1591 "Non-nil means, complete the outline path in hierarchical steps.
1592 When Org-mode uses the refile interface to select an outline path
1593 \(see variable `org-refile-use-outline-path'), the completion of
1594 the path can be done is a single go, or if can be done in steps down
1595 the headline hierarchy. Going in steps is probably the best if you
1596 do not use a special completion package like `ido' or `icicles'.
1597 However, when using these packages, going in one step can be very
1598 fast, while still showing the whole path to the entry."
1599 :group 'org-refile
1600 :type 'boolean)
1602 (defcustom org-refile-allow-creating-parent-nodes nil
1603 "Non-nil means, allow to create new nodes as refile targets.
1604 New nodes are then created by adding \"/new node name\" to the completion
1605 of an existing node. When the value of this variable is `confirm',
1606 new node creation must be confirmed by the user (recommended)
1607 When nil, the completion must match an existing entry.
1609 Note that, if the new heading is not seen by the criteria
1610 listed in `org-refile-targets', multiple instances of the same
1611 heading would be created by trying again to file under the new
1612 heading."
1613 :group 'org-refile
1614 :type '(choice
1615 (const :tag "Never" nil)
1616 (const :tag "Always" t)
1617 (const :tag "Prompt for confirmation" confirm)))
1619 (defgroup org-todo nil
1620 "Options concerning TODO items in Org-mode."
1621 :tag "Org TODO"
1622 :group 'org)
1624 (defgroup org-progress nil
1625 "Options concerning Progress logging in Org-mode."
1626 :tag "Org Progress"
1627 :group 'org-time)
1629 (defvar org-todo-interpretation-widgets
1631 (:tag "Sequence (cycling hits every state)" sequence)
1632 (:tag "Type (cycling directly to DONE)" type))
1633 "The available interpretation symbols for customizing
1634 `org-todo-keywords'.
1635 Interested libraries should add to this list.")
1637 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1638 "List of TODO entry keyword sequences and their interpretation.
1639 \\<org-mode-map>This is a list of sequences.
1641 Each sequence starts with a symbol, either `sequence' or `type',
1642 indicating if the keywords should be interpreted as a sequence of
1643 action steps, or as different types of TODO items. The first
1644 keywords are states requiring action - these states will select a headline
1645 for inclusion into the global TODO list Org-mode produces. If one of
1646 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1647 signify that no further action is necessary. If \"|\" is not found,
1648 the last keyword is treated as the only DONE state of the sequence.
1650 The command \\[org-todo] cycles an entry through these states, and one
1651 additional state where no keyword is present. For details about this
1652 cycling, see the manual.
1654 TODO keywords and interpretation can also be set on a per-file basis with
1655 the special #+SEQ_TODO and #+TYP_TODO lines.
1657 Each keyword can optionally specify a character for fast state selection
1658 \(in combination with the variable `org-use-fast-todo-selection')
1659 and specifiers for state change logging, using the same syntax
1660 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1661 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1662 indicates to record a time stamp each time this state is selected.
1664 Each keyword may also specify if a timestamp or a note should be
1665 recorded when entering or leaving the state, by adding additional
1666 characters in the parenthesis after the keyword. This looks like this:
1667 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1668 record only the time of the state change. With X and Y being either
1669 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1670 Y when leaving the state if and only if the *target* state does not
1671 define X. You may omit any of the fast-selection key or X or /Y,
1672 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1674 For backward compatibility, this variable may also be just a list
1675 of keywords - in this case the interpretation (sequence or type) will be
1676 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1677 :group 'org-todo
1678 :group 'org-keywords
1679 :type '(choice
1680 (repeat :tag "Old syntax, just keywords"
1681 (string :tag "Keyword"))
1682 (repeat :tag "New syntax"
1683 (cons
1684 (choice
1685 :tag "Interpretation"
1686 ;;Quick and dirty way to see
1687 ;;`org-todo-interpretations'. This takes the
1688 ;;place of item arguments
1689 :convert-widget
1690 (lambda (widget)
1691 (widget-put widget
1692 :args (mapcar
1693 #'(lambda (x)
1694 (widget-convert
1695 (cons 'const x)))
1696 org-todo-interpretation-widgets))
1697 widget))
1698 (repeat
1699 (string :tag "Keyword"))))))
1701 (defvar org-todo-keywords-1 nil
1702 "All TODO and DONE keywords active in a buffer.")
1703 (make-variable-buffer-local 'org-todo-keywords-1)
1704 (defvar org-todo-keywords-for-agenda nil)
1705 (defvar org-done-keywords-for-agenda nil)
1706 (defvar org-todo-keyword-alist-for-agenda nil)
1707 (defvar org-tag-alist-for-agenda nil)
1708 (defvar org-agenda-contributing-files nil)
1709 (defvar org-not-done-keywords nil)
1710 (make-variable-buffer-local 'org-not-done-keywords)
1711 (defvar org-done-keywords nil)
1712 (make-variable-buffer-local 'org-done-keywords)
1713 (defvar org-todo-heads nil)
1714 (make-variable-buffer-local 'org-todo-heads)
1715 (defvar org-todo-sets nil)
1716 (make-variable-buffer-local 'org-todo-sets)
1717 (defvar org-todo-log-states nil)
1718 (make-variable-buffer-local 'org-todo-log-states)
1719 (defvar org-todo-kwd-alist nil)
1720 (make-variable-buffer-local 'org-todo-kwd-alist)
1721 (defvar org-todo-key-alist nil)
1722 (make-variable-buffer-local 'org-todo-key-alist)
1723 (defvar org-todo-key-trigger nil)
1724 (make-variable-buffer-local 'org-todo-key-trigger)
1726 (defcustom org-todo-interpretation 'sequence
1727 "Controls how TODO keywords are interpreted.
1728 This variable is in principle obsolete and is only used for
1729 backward compatibility, if the interpretation of todo keywords is
1730 not given already in `org-todo-keywords'. See that variable for
1731 more information."
1732 :group 'org-todo
1733 :group 'org-keywords
1734 :type '(choice (const sequence)
1735 (const type)))
1737 (defcustom org-use-fast-todo-selection t
1738 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1739 This variable describes if and under what circumstances the cycling
1740 mechanism for TODO keywords will be replaced by a single-key, direct
1741 selection scheme.
1743 When nil, fast selection is never used.
1745 When the symbol `prefix', it will be used when `org-todo' is called with
1746 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1747 in an agenda buffer.
1749 When t, fast selection is used by default. In this case, the prefix
1750 argument forces cycling instead.
1752 In all cases, the special interface is only used if access keys have actually
1753 been assigned by the user, i.e. if keywords in the configuration are followed
1754 by a letter in parenthesis, like TODO(t)."
1755 :group 'org-todo
1756 :type '(choice
1757 (const :tag "Never" nil)
1758 (const :tag "By default" t)
1759 (const :tag "Only with C-u C-c C-t" prefix)))
1761 (defcustom org-provide-todo-statistics t
1762 "Non-nil means, update todo statistics after insert and toggle.
1763 ALL-HEADLINES means update todo statistics by including headlines
1764 with no TODO keyword as well, counting them as not done.
1765 A list of TODO keywords means the same, but skip keywords that are
1766 not in this list.
1768 When this is set, todo statistics is updated in the parent of the
1769 current entry each time a todo state is changed."
1770 :group 'org-todo
1771 :type '(choice
1772 (const :tag "Yes, only for TODO entries" t)
1773 (const :tag "Yes, including all entries" 'all-headlines)
1774 (repeat :tag "Yes, for TODOs in this list"
1775 (string :tag "TODO keyword"))
1776 (other :tag "No TODO statistics" nil)))
1778 (defcustom org-hierarchical-todo-statistics t
1779 "Non-nil means, TODO statistics covers just direct children.
1780 When nil, all entries in the subtree are considered.
1781 This has only an effect if `org-provide-todo-statistics' is set.
1782 To set this to nil for only a single subtree, use a COOKIE_DATA
1783 property and include the word \"recursive\" into the value."
1784 :group 'org-todo
1785 :type 'boolean)
1787 (defcustom org-after-todo-state-change-hook nil
1788 "Hook which is run after the state of a TODO item was changed.
1789 The new state (a string with a TODO keyword, or nil) is available in the
1790 Lisp variable `state'."
1791 :group 'org-todo
1792 :type 'hook)
1794 (defvar org-blocker-hook nil
1795 "Hook for functions that are allowed to block a state change.
1797 Each function gets as its single argument a property list, see
1798 `org-trigger-hook' for more information about this list.
1800 If any of the functions in this hook returns nil, the state change
1801 is blocked.")
1803 (defvar org-trigger-hook nil
1804 "Hook for functions that are triggered by a state change.
1806 Each function gets as its single argument a property list with at least
1807 the following elements:
1809 (:type type-of-change :position pos-at-entry-start
1810 :from old-state :to new-state)
1812 Depending on the type, more properties may be present.
1814 This mechanism is currently implemented for:
1816 TODO state changes
1817 ------------------
1818 :type todo-state-change
1819 :from previous state (keyword as a string), or nil, or a symbol
1820 'todo' or 'done', to indicate the general type of state.
1821 :to new state, like in :from")
1823 (defcustom org-enforce-todo-dependencies nil
1824 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1825 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1826 be blocked if any prior sibling is not yet done.
1827 Finally, if the parent is blocked because of ordered siblings of its own,
1828 the child will also be blocked.
1829 This variable needs to be set before org.el is loaded, and you need to
1830 restart Emacs after a change to make the change effective. The only way
1831 to change is while Emacs is running is through the customize interface."
1832 :set (lambda (var val)
1833 (set var val)
1834 (if val
1835 (add-hook 'org-blocker-hook
1836 'org-block-todo-from-children-or-siblings-or-parent)
1837 (remove-hook 'org-blocker-hook
1838 'org-block-todo-from-children-or-siblings-or-parent)))
1839 :group 'org-todo
1840 :type 'boolean)
1842 (defcustom org-enforce-todo-checkbox-dependencies nil
1843 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1844 When this is nil, checkboxes have no influence on switching TODO states.
1845 When non-nil, you first need to check off all check boxes before the TODO
1846 entry can be switched to DONE.
1847 This variable needs to be set before org.el is loaded, and you need to
1848 restart Emacs after a change to make the change effective. The only way
1849 to change is while Emacs is running is through the customize interface."
1850 :set (lambda (var val)
1851 (set var val)
1852 (if val
1853 (add-hook 'org-blocker-hook
1854 'org-block-todo-from-checkboxes)
1855 (remove-hook 'org-blocker-hook
1856 'org-block-todo-from-checkboxes)))
1857 :group 'org-todo
1858 :type 'boolean)
1860 (defcustom org-treat-insert-todo-heading-as-state-change nil
1861 "Non-nil means, inserting a TODO heading is treated as state change.
1862 So when the command \\[org-insert-todo-heading] is used, state change
1863 logging will apply if appropriate. When nil, the new TODO item will
1864 be inserted directly, and no logging will take place."
1865 :group 'org-todo
1866 :type 'boolean)
1868 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1869 "Non-nil means, switching TODO states with S-cursor counts as state change.
1870 This is the default behavior. However, setting this to nil allows a
1871 convenient way to select a TODO state and bypass any logging associated
1872 with that."
1873 :group 'org-todo
1874 :type 'boolean)
1876 (defcustom org-todo-state-tags-triggers nil
1877 "Tag changes that should be triggered by TODO state changes.
1878 This is a list. Each entry is
1880 (state-change (tag . flag) .......)
1882 State-change can be a string with a state, and empty string to indicate the
1883 state that has no TODO keyword, or it can be one of the symbols `todo'
1884 or `done', meaning any not-done or done state, respectively."
1885 :group 'org-todo
1886 :group 'org-tags
1887 :type '(repeat
1888 (cons (choice :tag "When changing to"
1889 (const :tag "Not-done state" todo)
1890 (const :tag "Done state" done)
1891 (string :tag "State"))
1892 (repeat
1893 (cons :tag "Tag action"
1894 (string :tag "Tag")
1895 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1897 (defcustom org-log-done nil
1898 "Information to record when a task moves to the DONE state.
1900 Possible values are:
1902 nil Don't add anything, just change the keyword
1903 time Add a time stamp to the task
1904 note Prompt a closing note and add it with template `org-log-note-headings'
1906 This option can also be set with on a per-file-basis with
1908 #+STARTUP: nologdone
1909 #+STARTUP: logdone
1910 #+STARTUP: lognotedone
1912 You can have local logging settings for a subtree by setting the LOGGING
1913 property to one or more of these keywords."
1914 :group 'org-todo
1915 :group 'org-progress
1916 :type '(choice
1917 (const :tag "No logging" nil)
1918 (const :tag "Record CLOSED timestamp" time)
1919 (const :tag "Record CLOSED timestamp with closing note." note)))
1921 ;; Normalize old uses of org-log-done.
1922 (cond
1923 ((eq org-log-done t) (setq org-log-done 'time))
1924 ((and (listp org-log-done) (memq 'done org-log-done))
1925 (setq org-log-done 'note)))
1927 (defcustom org-log-note-clock-out nil
1928 "Non-nil means, record a note when clocking out of an item.
1929 This can also be configured on a per-file basis by adding one of
1930 the following lines anywhere in the buffer:
1932 #+STARTUP: lognoteclock-out
1933 #+STARTUP: nolognoteclock-out"
1934 :group 'org-todo
1935 :group 'org-progress
1936 :type 'boolean)
1938 (defcustom org-log-done-with-time t
1939 "Non-nil means, the CLOSED time stamp will contain date and time.
1940 When nil, only the date will be recorded."
1941 :group 'org-progress
1942 :type 'boolean)
1944 (defcustom org-log-note-headings
1945 '((done . "CLOSING NOTE %t")
1946 (state . "State %-12s from %-12S %t")
1947 (note . "Note taken on %t")
1948 (clock-out . ""))
1949 "Headings for notes added to entries.
1950 The value is an alist, with the car being a symbol indicating the note
1951 context, and the cdr is the heading to be used. The heading may also be the
1952 empty string.
1953 %t in the heading will be replaced by a time stamp.
1954 %s will be replaced by the new TODO state, in double quotes.
1955 %S will be replaced by the old TODO state, in double quotes.
1956 %u will be replaced by the user name.
1957 %U will be replaced by the full user name."
1958 :group 'org-todo
1959 :group 'org-progress
1960 :type '(list :greedy t
1961 (cons (const :tag "Heading when closing an item" done) string)
1962 (cons (const :tag
1963 "Heading when changing todo state (todo sequence only)"
1964 state) string)
1965 (cons (const :tag "Heading when just taking a note" note) string)
1966 (cons (const :tag "Heading when clocking out" clock-out) string)))
1968 (unless (assq 'note org-log-note-headings)
1969 (push '(note . "%t") org-log-note-headings))
1971 (defcustom org-log-into-drawer nil
1972 "Non-nil means, insert state change notes and time stamps into a drawer.
1973 When nil, state changes notes will be inserted after the headline and
1974 any scheduling and clock lines, but not inside a drawer.
1976 The value of this variable should be the name of the drawer to use.
1977 LOGBOOK is proposed at the default drawer for this purpose, you can
1978 also set this to a string to define the drawer of your choice.
1980 A value of t is also allowed, representing \"LOGBOOK\".
1982 If this variable is set, `org-log-state-notes-insert-after-drawers'
1983 will be ignored.
1985 You can set the property LOG_INTO_DRAWER to overrule this setting for
1986 a subtree."
1987 :group 'org-todo
1988 :group 'org-progress
1989 :type '(choice
1990 (const :tag "Not into a drawer" nil)
1991 (const :tag "LOGBOOK" t)
1992 (string :tag "Other")))
1994 (if (fboundp 'defvaralias)
1995 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1997 (defun org-log-into-drawer ()
1998 "Return the value of `org-log-into-drawer', but let properties overrule.
1999 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2000 used instead of the default value."
2001 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2002 (cond
2003 ((or (not p) (equal p "nil")) org-log-into-drawer)
2004 ((equal p "t") "LOGBOOK")
2005 (t p))))
2007 (defcustom org-log-state-notes-insert-after-drawers nil
2008 "Non-nil means, insert state change notes after any drawers in entry.
2009 Only the drawers that *immediately* follow the headline and the
2010 deadline/scheduled line are skipped.
2011 When nil, insert notes right after the heading and perhaps the line
2012 with deadline/scheduling if present.
2014 This variable will have no effect if `org-log-into-drawer' is
2015 set."
2016 :group 'org-todo
2017 :group 'org-progress
2018 :type 'boolean)
2020 (defcustom org-log-states-order-reversed t
2021 "Non-nil means, the latest state change note will be directly after heading.
2022 When nil, the notes will be orderer according to time."
2023 :group 'org-todo
2024 :group 'org-progress
2025 :type 'boolean)
2027 (defcustom org-log-repeat 'time
2028 "Non-nil means, record moving through the DONE state when triggering repeat.
2029 An auto-repeating task is immediately switched back to TODO when
2030 marked DONE. If you are not logging state changes (by adding \"@\"
2031 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2032 record a closing note, there will be no record of the task moving
2033 through DONE. This variable forces taking a note anyway.
2035 nil Don't force a record
2036 time Record a time stamp
2037 note Record a note
2039 This option can also be set with on a per-file-basis with
2041 #+STARTUP: logrepeat
2042 #+STARTUP: lognoterepeat
2043 #+STARTUP: nologrepeat
2045 You can have local logging settings for a subtree by setting the LOGGING
2046 property to one or more of these keywords."
2047 :group 'org-todo
2048 :group 'org-progress
2049 :type '(choice
2050 (const :tag "Don't force a record" nil)
2051 (const :tag "Force recording the DONE state" time)
2052 (const :tag "Force recording a note with the DONE state" note)))
2055 (defgroup org-priorities nil
2056 "Priorities in Org-mode."
2057 :tag "Org Priorities"
2058 :group 'org-todo)
2060 (defcustom org-enable-priority-commands t
2061 "Non-nil means, priority commands are active.
2062 When nil, these commands will be disabled, so that you never accidentally
2063 set a priority."
2064 :group 'org-priorities
2065 :type 'boolean)
2067 (defcustom org-highest-priority ?A
2068 "The highest priority of TODO items. A character like ?A, ?B etc.
2069 Must have a smaller ASCII number than `org-lowest-priority'."
2070 :group 'org-priorities
2071 :type 'character)
2073 (defcustom org-lowest-priority ?C
2074 "The lowest priority of TODO items. A character like ?A, ?B etc.
2075 Must have a larger ASCII number than `org-highest-priority'."
2076 :group 'org-priorities
2077 :type 'character)
2079 (defcustom org-default-priority ?B
2080 "The default priority of TODO items.
2081 This is the priority an item get if no explicit priority is given."
2082 :group 'org-priorities
2083 :type 'character)
2085 (defcustom org-priority-start-cycle-with-default t
2086 "Non-nil means, start with default priority when starting to cycle.
2087 When this is nil, the first step in the cycle will be (depending on the
2088 command used) one higher or lower that the default priority."
2089 :group 'org-priorities
2090 :type 'boolean)
2092 (defgroup org-time nil
2093 "Options concerning time stamps and deadlines in Org-mode."
2094 :tag "Org Time"
2095 :group 'org)
2097 (defcustom org-insert-labeled-timestamps-at-point nil
2098 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2099 When nil, these labeled time stamps are forces into the second line of an
2100 entry, just after the headline. When scheduling from the global TODO list,
2101 the time stamp will always be forced into the second line."
2102 :group 'org-time
2103 :type 'boolean)
2105 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2106 "Formats for `format-time-string' which are used for time stamps.
2107 It is not recommended to change this constant.")
2109 (defcustom org-time-stamp-rounding-minutes '(0 5)
2110 "Number of minutes to round time stamps to.
2111 These are two values, the first applies when first creating a time stamp.
2112 The second applies when changing it with the commands `S-up' and `S-down'.
2113 When changing the time stamp, this means that it will change in steps
2114 of N minutes, as given by the second value.
2116 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2117 numbers should be factors of 60, so for example 5, 10, 15.
2119 When this is larger than 1, you can still force an exact time-stamp by using
2120 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2121 and by using a prefix arg to `S-up/down' to specify the exact number
2122 of minutes to shift."
2123 :group 'org-time
2124 :get '(lambda (var) ; Make sure all entries have 5 elements
2125 (if (integerp (default-value var))
2126 (list (default-value var) 5)
2127 (default-value var)))
2128 :type '(list
2129 (integer :tag "when inserting times")
2130 (integer :tag "when modifying times")))
2132 ;; Normalize old customizations of this variable.
2133 (when (integerp org-time-stamp-rounding-minutes)
2134 (setq org-time-stamp-rounding-minutes
2135 (list org-time-stamp-rounding-minutes
2136 org-time-stamp-rounding-minutes)))
2138 (defcustom org-display-custom-times nil
2139 "Non-nil means, overlay custom formats over all time stamps.
2140 The formats are defined through the variable `org-time-stamp-custom-formats'.
2141 To turn this on on a per-file basis, insert anywhere in the file:
2142 #+STARTUP: customtime"
2143 :group 'org-time
2144 :set 'set-default
2145 :type 'sexp)
2146 (make-variable-buffer-local 'org-display-custom-times)
2148 (defcustom org-time-stamp-custom-formats
2149 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2150 "Custom formats for time stamps. See `format-time-string' for the syntax.
2151 These are overlayed over the default ISO format if the variable
2152 `org-display-custom-times' is set. Time like %H:%M should be at the
2153 end of the second format. The custom formats are also honored by export
2154 commands, if custom time display is turned on at the time of export."
2155 :group 'org-time
2156 :type 'sexp)
2158 (defun org-time-stamp-format (&optional long inactive)
2159 "Get the right format for a time string."
2160 (let ((f (if long (cdr org-time-stamp-formats)
2161 (car org-time-stamp-formats))))
2162 (if inactive
2163 (concat "[" (substring f 1 -1) "]")
2164 f)))
2166 (defcustom org-time-clocksum-format "%d:%02d"
2167 "The format string used when creating CLOCKSUM lines, or when
2168 org-mode generates a time duration."
2169 :group 'org-time
2170 :type 'string)
2172 (defcustom org-deadline-warning-days 14
2173 "No. of days before expiration during which a deadline becomes active.
2174 This variable governs the display in sparse trees and in the agenda.
2175 When 0 or negative, it means use this number (the absolute value of it)
2176 even if a deadline has a different individual lead time specified.
2178 Custom commands can set this variable in the options section."
2179 :group 'org-time
2180 :group 'org-agenda-daily/weekly
2181 :type 'integer)
2183 (defcustom org-read-date-prefer-future t
2184 "Non-nil means, assume future for incomplete date input from user.
2185 This affects the following situations:
2186 1. The user gives a day, but no month.
2187 For example, if today is the 15th, and you enter \"3\", Org-mode will
2188 read this as the third of *next* month. However, if you enter \"17\",
2189 it will be considered as *this* month.
2190 2. The user gives a month but not a year.
2191 For example, if it is april and you enter \"feb 2\", this will be read
2192 as feb 2, *next* year. \"May 5\", however, will be this year.
2194 Currently this does not work for ISO week specifications.
2196 When this option is nil, the current month and year will always be used
2197 as defaults."
2198 :group 'org-time
2199 :type 'boolean)
2201 (defcustom org-read-date-display-live t
2202 "Non-nil means, display current interpretation of date prompt live.
2203 This display will be in an overlay, in the minibuffer."
2204 :group 'org-time
2205 :type 'boolean)
2207 (defcustom org-read-date-popup-calendar t
2208 "Non-nil means, pop up a calendar when prompting for a date.
2209 In the calendar, the date can be selected with mouse-1. However, the
2210 minibuffer will also be active, and you can simply enter the date as well.
2211 When nil, only the minibuffer will be available."
2212 :group 'org-time
2213 :type 'boolean)
2214 (if (fboundp 'defvaralias)
2215 (defvaralias 'org-popup-calendar-for-date-prompt
2216 'org-read-date-popup-calendar))
2218 (defcustom org-read-date-minibuffer-setup-hook nil
2219 "Hook to be used to set up keys for the date/time interface.
2220 Add key definitions to `minibuffer-local-map', which will be a temporary
2221 copy."
2222 :group 'org-time
2223 :type 'hook)
2225 (defcustom org-extend-today-until 0
2226 "The hour when your day really ends. Must be an integer.
2227 This has influence for the following applications:
2228 - When switching the agenda to \"today\". It it is still earlier than
2229 the time given here, the day recognized as TODAY is actually yesterday.
2230 - When a date is read from the user and it is still before the time given
2231 here, the current date and time will be assumed to be yesterday, 23:59.
2232 Also, timestamps inserted in remember templates follow this rule.
2234 IMPORTANT: This is a feature whose implementation is and likely will
2235 remain incomplete. Really, it is only here because past midnight seems to
2236 be the favorite working time of John Wiegley :-)"
2237 :group 'org-time
2238 :type 'integer)
2240 (defcustom org-edit-timestamp-down-means-later nil
2241 "Non-nil means, S-down will increase the time in a time stamp.
2242 When nil, S-up will increase."
2243 :group 'org-time
2244 :type 'boolean)
2246 (defcustom org-calendar-follow-timestamp-change t
2247 "Non-nil means, make the calendar window follow timestamp changes.
2248 When a timestamp is modified and the calendar window is visible, it will be
2249 moved to the new date."
2250 :group 'org-time
2251 :type 'boolean)
2253 (defgroup org-tags nil
2254 "Options concerning tags in Org-mode."
2255 :tag "Org Tags"
2256 :group 'org)
2258 (defcustom org-tag-alist nil
2259 "List of tags allowed in Org-mode files.
2260 When this list is nil, Org-mode will base TAG input on what is already in the
2261 buffer.
2262 The value of this variable is an alist, the car of each entry must be a
2263 keyword as a string, the cdr may be a character that is used to select
2264 that tag through the fast-tag-selection interface.
2265 See the manual for details."
2266 :group 'org-tags
2267 :type '(repeat
2268 (choice
2269 (cons (string :tag "Tag name")
2270 (character :tag "Access char"))
2271 (const :tag "Start radio group" (:startgroup))
2272 (const :tag "End radio group" (:endgroup))
2273 (const :tag "New line" (:newline)))))
2275 (defcustom org-tag-persistent-alist nil
2276 "List of tags that will always appear in all Org-mode files.
2277 This is in addition to any in buffer settings or customizations
2278 of `org-tag-alist'.
2279 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2280 The value of this variable is an alist, the car of each entry must be a
2281 keyword as a string, the cdr may be a character that is used to select
2282 that tag through the fast-tag-selection interface.
2283 See the manual for details.
2284 To disable these tags on a per-file basis, insert anywhere in the file:
2285 #+STARTUP: noptag"
2286 :group 'org-tags
2287 :type '(repeat
2288 (choice
2289 (cons (string :tag "Tag name")
2290 (character :tag "Access char"))
2291 (const :tag "Start radio group" (:startgroup))
2292 (const :tag "End radio group" (:endgroup))
2293 (const :tag "New line" (:newline)))))
2295 (defvar org-file-tags nil
2296 "List of tags that can be inherited by all entries in the file.
2297 The tags will be inherited if the variable `org-use-tag-inheritance'
2298 says they should be.
2299 This variable is populated from #+TAG lines.")
2301 (defcustom org-use-fast-tag-selection 'auto
2302 "Non-nil means, use fast tag selection scheme.
2303 This is a special interface to select and deselect tags with single keys.
2304 When nil, fast selection is never used.
2305 When the symbol `auto', fast selection is used if and only if selection
2306 characters for tags have been configured, either through the variable
2307 `org-tag-alist' or through a #+TAGS line in the buffer.
2308 When t, fast selection is always used and selection keys are assigned
2309 automatically if necessary."
2310 :group 'org-tags
2311 :type '(choice
2312 (const :tag "Always" t)
2313 (const :tag "Never" nil)
2314 (const :tag "When selection characters are configured" 'auto)))
2316 (defcustom org-fast-tag-selection-single-key nil
2317 "Non-nil means, fast tag selection exits after first change.
2318 When nil, you have to press RET to exit it.
2319 During fast tag selection, you can toggle this flag with `C-c'.
2320 This variable can also have the value `expert'. In this case, the window
2321 displaying the tags menu is not even shown, until you press C-c again."
2322 :group 'org-tags
2323 :type '(choice
2324 (const :tag "No" nil)
2325 (const :tag "Yes" t)
2326 (const :tag "Expert" expert)))
2328 (defvar org-fast-tag-selection-include-todo nil
2329 "Non-nil means, fast tags selection interface will also offer TODO states.
2330 This is an undocumented feature, you should not rely on it.")
2332 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2333 "The column to which tags should be indented in a headline.
2334 If this number is positive, it specifies the column. If it is negative,
2335 it means that the tags should be flushright to that column. For example,
2336 -80 works well for a normal 80 character screen."
2337 :group 'org-tags
2338 :type 'integer)
2340 (defcustom org-auto-align-tags t
2341 "Non-nil means, realign tags after pro/demotion of TODO state change.
2342 These operations change the length of a headline and therefore shift
2343 the tags around. With this options turned on, after each such operation
2344 the tags are again aligned to `org-tags-column'."
2345 :group 'org-tags
2346 :type 'boolean)
2348 (defcustom org-use-tag-inheritance t
2349 "Non-nil means, tags in levels apply also for sublevels.
2350 When nil, only the tags directly given in a specific line apply there.
2351 This may also be a list of tags that should be inherited, or a regexp that
2352 matches tags that should be inherited. Additional control is possible
2353 with the variable `org-tags-exclude-from-inheritance' which gives an
2354 explicit list of tags to be excluded from inheritance., even if the value of
2355 `org-use-tag-inheritance' would select it for inheritance.
2357 If this option is t, a match early-on in a tree can lead to a large
2358 number of matches in the subtree when constructing the agenda or creating
2359 a sparse tree. If you only want to see the first match in a tree during
2360 a search, check out the variable `org-tags-match-list-sublevels'."
2361 :group 'org-tags
2362 :type '(choice
2363 (const :tag "Not" nil)
2364 (const :tag "Always" t)
2365 (repeat :tag "Specific tags" (string :tag "Tag"))
2366 (regexp :tag "Tags matched by regexp")))
2368 (defcustom org-tags-exclude-from-inheritance nil
2369 "List of tags that should never be inherited.
2370 This is a way to exclude a few tags from inheritance. For way to do
2371 the opposite, to actively allow inheritance for selected tags,
2372 see the variable `org-use-tag-inheritance'."
2373 :group 'org-tags
2374 :type '(repeat (string :tag "Tag")))
2376 (defun org-tag-inherit-p (tag)
2377 "Check if TAG is one that should be inherited."
2378 (cond
2379 ((member tag org-tags-exclude-from-inheritance) nil)
2380 ((eq org-use-tag-inheritance t) t)
2381 ((not org-use-tag-inheritance) nil)
2382 ((stringp org-use-tag-inheritance)
2383 (string-match org-use-tag-inheritance tag))
2384 ((listp org-use-tag-inheritance)
2385 (member tag org-use-tag-inheritance))
2386 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2388 (defcustom org-tags-match-list-sublevels t
2389 "Non-nil means list also sublevels of headlines matching a search.
2390 This variable applies to tags/property searches, and also to stuck
2391 projects because this search is based on a tags match as well.
2393 When set to the symbol `indented', sublevels are indented with
2394 leading dots.
2396 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2397 the sublevels of a headline matching a tag search often also match
2398 the same search. Listing all of them can create very long lists.
2399 Setting this variable to nil causes subtrees of a match to be skipped.
2401 This variable is semi-obsolete and probably should always be true. It
2402 is better to limit inheritance to certain tags using the variables
2403 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2404 :group 'org-tags
2405 :type '(choice
2406 (const :tag "No, don't list them" nil)
2407 (const :tag "Yes, do list them" t)
2408 (const :tag "List them, indented with leading dots" indented)))
2410 (defcustom org-tags-sort-function nil
2411 "When set, tags are sorted using this function as a comparator"
2412 :group 'org-tags
2413 :type '(choice
2414 (const :tag "No sorting" nil)
2415 (const :tag "Alphabetical" string<)
2416 (const :tag "Reverse alphabetical" string>)
2417 (function :tag "Custom function" nil)))
2419 (defvar org-tags-history nil
2420 "History of minibuffer reads for tags.")
2421 (defvar org-last-tags-completion-table nil
2422 "The last used completion table for tags.")
2423 (defvar org-after-tags-change-hook nil
2424 "Hook that is run after the tags in a line have changed.")
2426 (defgroup org-properties nil
2427 "Options concerning properties in Org-mode."
2428 :tag "Org Properties"
2429 :group 'org)
2431 (defcustom org-property-format "%-10s %s"
2432 "How property key/value pairs should be formatted by `indent-line'.
2433 When `indent-line' hits a property definition, it will format the line
2434 according to this format, mainly to make sure that the values are
2435 lined-up with respect to each other."
2436 :group 'org-properties
2437 :type 'string)
2439 (defcustom org-use-property-inheritance nil
2440 "Non-nil means, properties apply also for sublevels.
2442 This setting is chiefly used during property searches. Turning it on can
2443 cause significant overhead when doing a search, which is why it is not
2444 on by default.
2446 When nil, only the properties directly given in the current entry count.
2447 When t, every property is inherited. The value may also be a list of
2448 properties that should have inheritance, or a regular expression matching
2449 properties that should be inherited.
2451 However, note that some special properties use inheritance under special
2452 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2453 and the properties ending in \"_ALL\" when they are used as descriptor
2454 for valid values of a property.
2456 Note for programmers:
2457 When querying an entry with `org-entry-get', you can control if inheritance
2458 should be used. By default, `org-entry-get' looks only at the local
2459 properties. You can request inheritance by setting the inherit argument
2460 to t (to force inheritance) or to `selective' (to respect the setting
2461 in this variable)."
2462 :group 'org-properties
2463 :type '(choice
2464 (const :tag "Not" nil)
2465 (const :tag "Always" t)
2466 (repeat :tag "Specific properties" (string :tag "Property"))
2467 (regexp :tag "Properties matched by regexp")))
2469 (defun org-property-inherit-p (property)
2470 "Check if PROPERTY is one that should be inherited."
2471 (cond
2472 ((eq org-use-property-inheritance t) t)
2473 ((not org-use-property-inheritance) nil)
2474 ((stringp org-use-property-inheritance)
2475 (string-match org-use-property-inheritance property))
2476 ((listp org-use-property-inheritance)
2477 (member property org-use-property-inheritance))
2478 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2480 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2481 "The default column format, if no other format has been defined.
2482 This variable can be set on the per-file basis by inserting a line
2484 #+COLUMNS: %25ITEM ....."
2485 :group 'org-properties
2486 :type 'string)
2488 (defcustom org-columns-ellipses ".."
2489 "The ellipses to be used when a field in column view is truncated.
2490 When this is the empty string, as many characters as possible are shown,
2491 but then there will be no visual indication that the field has been truncated.
2492 When this is a string of length N, the last N characters of a truncated
2493 field are replaced by this string. If the column is narrower than the
2494 ellipses string, only part of the ellipses string will be shown."
2495 :group 'org-properties
2496 :type 'string)
2498 (defcustom org-columns-modify-value-for-display-function nil
2499 "Function that modifies values for display in column view.
2500 For example, it can be used to cut out a certain part from a time stamp.
2501 The function must take 2 arguments:
2503 column-title The title of the column (*not* the property name)
2504 value The value that should be modified.
2506 The function should return the value that should be displayed,
2507 or nil if the normal value should be used."
2508 :group 'org-properties
2509 :type 'function)
2511 (defcustom org-effort-property "Effort"
2512 "The property that is being used to keep track of effort estimates.
2513 Effort estimates given in this property need to have the format H:MM."
2514 :group 'org-properties
2515 :group 'org-progress
2516 :type '(string :tag "Property"))
2518 (defconst org-global-properties-fixed
2519 '(("VISIBILITY_ALL" . "folded children content all")
2520 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2521 "List of property/value pairs that can be inherited by any entry.
2523 These are fixed values, for the preset properties. The user variable
2524 that can be used to add to this list is `org-global-properties'.
2526 The entries in this list are cons cells where the car is a property
2527 name and cdr is a string with the value. If the value represents
2528 multiple items like an \"_ALL\" property, separate the items by
2529 spaces.")
2531 (defcustom org-global-properties nil
2532 "List of property/value pairs that can be inherited by any entry.
2534 This list will be combined with the constant `org-global-properties-fixed'.
2536 The entries in this list are cons cells where the car is a property
2537 name and cdr is a string with the value.
2539 You can set buffer-local values for the same purpose in the variable
2540 `org-file-properties' this by adding lines like
2542 #+PROPERTY: NAME VALUE"
2543 :group 'org-properties
2544 :type '(repeat
2545 (cons (string :tag "Property")
2546 (string :tag "Value"))))
2548 (defvar org-file-properties nil
2549 "List of property/value pairs that can be inherited by any entry.
2550 Valid for the current buffer.
2551 This variable is populated from #+PROPERTY lines.")
2552 (make-variable-buffer-local 'org-file-properties)
2554 (defgroup org-agenda nil
2555 "Options concerning agenda views in Org-mode."
2556 :tag "Org Agenda"
2557 :group 'org)
2559 (defvar org-category nil
2560 "Variable used by org files to set a category for agenda display.
2561 Such files should use a file variable to set it, for example
2563 # -*- mode: org; org-category: \"ELisp\"
2565 or contain a special line
2567 #+CATEGORY: ELisp
2569 If the file does not specify a category, then file's base name
2570 is used instead.")
2571 (make-variable-buffer-local 'org-category)
2572 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2574 (defcustom org-agenda-files nil
2575 "The files to be used for agenda display.
2576 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2577 \\[org-remove-file]. You can also use customize to edit the list.
2579 If an entry is a directory, all files in that directory that are matched by
2580 `org-agenda-file-regexp' will be part of the file list.
2582 If the value of the variable is not a list but a single file name, then
2583 the list of agenda files is actually stored and maintained in that file, one
2584 agenda file per line."
2585 :group 'org-agenda
2586 :type '(choice
2587 (repeat :tag "List of files and directories" file)
2588 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2590 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2591 "Regular expression to match files for `org-agenda-files'.
2592 If any element in the list in that variable contains a directory instead
2593 of a normal file, all files in that directory that are matched by this
2594 regular expression will be included."
2595 :group 'org-agenda
2596 :type 'regexp)
2598 (defcustom org-agenda-text-search-extra-files nil
2599 "List of extra files to be searched by text search commands.
2600 These files will be search in addition to the agenda files by the
2601 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2602 Note that these files will only be searched for text search commands,
2603 not for the other agenda views like todo lists, tag searches or the weekly
2604 agenda. This variable is intended to list notes and possibly archive files
2605 that should also be searched by these two commands.
2606 In fact, if the first element in the list is the symbol `agenda-archives',
2607 than all archive files of all agenda files will be added to the search
2608 scope."
2609 :group 'org-agenda
2610 :type '(set :greedy t
2611 (const :tag "Agenda Archives" agenda-archives)
2612 (repeat :inline t (file))))
2614 (if (fboundp 'defvaralias)
2615 (defvaralias 'org-agenda-multi-occur-extra-files
2616 'org-agenda-text-search-extra-files))
2618 (defcustom org-agenda-skip-unavailable-files nil
2619 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2620 A nil value means to remove them, after a query, from the list."
2621 :group 'org-agenda
2622 :type 'boolean)
2624 (defcustom org-calendar-to-agenda-key [?c]
2625 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2626 The command `org-calendar-goto-agenda' will be bound to this key. The
2627 default is the character `c' because then `c' can be used to switch back and
2628 forth between agenda and calendar."
2629 :group 'org-agenda
2630 :type 'sexp)
2632 (defcustom org-calendar-agenda-action-key [?k]
2633 "The key to be installed in `calendar-mode-map' for agenda-action.
2634 The command `org-agenda-action' will be bound to this key. The
2635 default is the character `k' because we use the same key in the agenda."
2636 :group 'org-agenda
2637 :type 'sexp)
2639 (eval-after-load "calendar"
2640 '(progn
2641 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2642 'org-calendar-goto-agenda)
2643 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2644 'org-agenda-action)))
2646 (defgroup org-latex nil
2647 "Options for embedding LaTeX code into Org-mode."
2648 :tag "Org LaTeX"
2649 :group 'org)
2651 (defcustom org-format-latex-options
2652 '(:foreground default :background default :scale 1.0
2653 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2654 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2655 "Options for creating images from LaTeX fragments.
2656 This is a property list with the following properties:
2657 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2658 `default' means use the foreground of the default face.
2659 :background the background color, or \"Transparent\".
2660 `default' means use the background of the default face.
2661 :scale a scaling factor for the size of the images.
2662 :html-foreground, :html-background, :html-scale
2663 the same numbers for HTML export.
2664 :matchers a list indicating which matchers should be used to
2665 find LaTeX fragments. Valid members of this list are:
2666 \"begin\" find environments
2667 \"$1\" find single characters surrounded by $.$
2668 \"$\" find math expressions surrounded by $...$
2669 \"$$\" find math expressions surrounded by $$....$$
2670 \"\\(\" find math expressions surrounded by \\(...\\)
2671 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2672 :group 'org-latex
2673 :type 'plist)
2675 (defcustom org-format-latex-header "\\documentclass{article}
2676 \\usepackage{fullpage} % do not remove
2677 \\usepackage{amssymb}
2678 \\usepackage[usenames]{color}
2679 \\usepackage{amsmath}
2680 \\usepackage{latexsym}
2681 \\usepackage[mathscr]{eucal}
2682 \\pagestyle{empty} % do not remove"
2683 "The document header used for processing LaTeX fragments."
2684 :group 'org-latex
2685 :type 'string)
2688 (defgroup org-font-lock nil
2689 "Font-lock settings for highlighting in Org-mode."
2690 :tag "Org Font Lock"
2691 :group 'org)
2693 (defcustom org-level-color-stars-only nil
2694 "Non-nil means fontify only the stars in each headline.
2695 When nil, the entire headline is fontified.
2696 Changing it requires restart of `font-lock-mode' to become effective
2697 also in regions already fontified."
2698 :group 'org-font-lock
2699 :type 'boolean)
2701 (defcustom org-hide-leading-stars nil
2702 "Non-nil means, hide the first N-1 stars in a headline.
2703 This works by using the face `org-hide' for these stars. This
2704 face is white for a light background, and black for a dark
2705 background. You may have to customize the face `org-hide' to
2706 make this work.
2707 Changing it requires restart of `font-lock-mode' to become effective
2708 also in regions already fontified.
2709 You may also set this on a per-file basis by adding one of the following
2710 lines to the buffer:
2712 #+STARTUP: hidestars
2713 #+STARTUP: showstars"
2714 :group 'org-font-lock
2715 :type 'boolean)
2717 (defcustom org-fontify-done-headline nil
2718 "Non-nil means, change the face of a headline if it is marked DONE.
2719 Normally, only the TODO/DONE keyword indicates the state of a headline.
2720 When this is non-nil, the headline after the keyword is set to the
2721 `org-headline-done' as an additional indication."
2722 :group 'org-font-lock
2723 :type 'boolean)
2725 (defcustom org-fontify-emphasized-text t
2726 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2727 Changing this variable requires a restart of Emacs to take effect."
2728 :group 'org-font-lock
2729 :type 'boolean)
2731 (defcustom org-fontify-whole-heading-line nil
2732 "Non-nil means fontify the whole line for headings.
2733 This is useful when setting a background color for the
2734 org-leve-* faces."
2735 :group 'org-font-lock
2736 :type 'boolean)
2738 (defcustom org-highlight-latex-fragments-and-specials nil
2739 "Non-nil means, fontify what is treated specially by the exporters."
2740 :group 'org-font-lock
2741 :type 'boolean)
2743 (defcustom org-hide-emphasis-markers nil
2744 "Non-nil mean font-lock should hide the emphasis marker characters."
2745 :group 'org-font-lock
2746 :type 'boolean)
2748 (defvar org-emph-re nil
2749 "Regular expression for matching emphasis.")
2750 (defvar org-verbatim-re nil
2751 "Regular expression for matching verbatim text.")
2752 (defvar org-emphasis-regexp-components) ; defined just below
2753 (defvar org-emphasis-alist) ; defined just below
2754 (defun org-set-emph-re (var val)
2755 "Set variable and compute the emphasis regular expression."
2756 (set var val)
2757 (when (and (boundp 'org-emphasis-alist)
2758 (boundp 'org-emphasis-regexp-components)
2759 org-emphasis-alist org-emphasis-regexp-components)
2760 (let* ((e org-emphasis-regexp-components)
2761 (pre (car e))
2762 (post (nth 1 e))
2763 (border (nth 2 e))
2764 (body (nth 3 e))
2765 (nl (nth 4 e))
2766 (body1 (concat body "*?"))
2767 (markers (mapconcat 'car org-emphasis-alist ""))
2768 (vmarkers (mapconcat
2769 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2770 org-emphasis-alist "")))
2771 ;; make sure special characters appear at the right position in the class
2772 (if (string-match "\\^" markers)
2773 (setq markers (concat (replace-match "" t t markers) "^")))
2774 (if (string-match "-" markers)
2775 (setq markers (concat (replace-match "" t t markers) "-")))
2776 (if (string-match "\\^" vmarkers)
2777 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2778 (if (string-match "-" vmarkers)
2779 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2780 (if (> nl 0)
2781 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2782 (int-to-string nl) "\\}")))
2783 ;; Make the regexp
2784 (setq org-emph-re
2785 (concat "\\([" pre "]\\|^\\)"
2786 "\\("
2787 "\\([" markers "]\\)"
2788 "\\("
2789 "[^" border "]\\|"
2790 "[^" border "]"
2791 body1
2792 "[^" border "]"
2793 "\\)"
2794 "\\3\\)"
2795 "\\([" post "]\\|$\\)"))
2796 (setq org-verbatim-re
2797 (concat "\\([" pre "]\\|^\\)"
2798 "\\("
2799 "\\([" vmarkers "]\\)"
2800 "\\("
2801 "[^" border "]\\|"
2802 "[^" border "]"
2803 body1
2804 "[^" border "]"
2805 "\\)"
2806 "\\3\\)"
2807 "\\([" post "]\\|$\\)")))))
2809 (defcustom org-emphasis-regexp-components
2810 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2811 "Components used to build the regular expression for emphasis.
2812 This is a list with 6 entries. Terminology: In an emphasis string
2813 like \" *strong word* \", we call the initial space PREMATCH, the final
2814 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2815 and \"trong wor\" is the body. The different components in this variable
2816 specify what is allowed/forbidden in each part:
2818 pre Chars allowed as prematch. Beginning of line will be allowed too.
2819 post Chars allowed as postmatch. End of line will be allowed too.
2820 border The chars *forbidden* as border characters.
2821 body-regexp A regexp like \".\" to match a body character. Don't use
2822 non-shy groups here, and don't allow newline here.
2823 newline The maximum number of newlines allowed in an emphasis exp.
2825 Use customize to modify this, or restart Emacs after changing it."
2826 :group 'org-font-lock
2827 :set 'org-set-emph-re
2828 :type '(list
2829 (sexp :tag "Allowed chars in pre ")
2830 (sexp :tag "Allowed chars in post ")
2831 (sexp :tag "Forbidden chars in border ")
2832 (sexp :tag "Regexp for body ")
2833 (integer :tag "number of newlines allowed")
2834 (option (boolean :tag "Please ignore this button"))))
2836 (defcustom org-emphasis-alist
2837 `(("*" bold "<b>" "</b>")
2838 ("/" italic "<i>" "</i>")
2839 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2840 ("=" org-code "<code>" "</code>" verbatim)
2841 ("~" org-verbatim "<code>" "</code>" verbatim)
2842 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2843 "<del>" "</del>")
2845 "Special syntax for emphasized text.
2846 Text starting and ending with a special character will be emphasized, for
2847 example *bold*, _underlined_ and /italic/. This variable sets the marker
2848 characters, the face to be used by font-lock for highlighting in Org-mode
2849 Emacs buffers, and the HTML tags to be used for this.
2850 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2851 Use customize to modify this, or restart Emacs after changing it."
2852 :group 'org-font-lock
2853 :set 'org-set-emph-re
2854 :type '(repeat
2855 (list
2856 (string :tag "Marker character")
2857 (choice
2858 (face :tag "Font-lock-face")
2859 (plist :tag "Face property list"))
2860 (string :tag "HTML start tag")
2861 (string :tag "HTML end tag")
2862 (option (const verbatim)))))
2864 (defvar org-protecting-blocks
2865 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2866 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2867 This is needed for font-lock setup.")
2869 ;;; Miscellaneous options
2871 (defgroup org-completion nil
2872 "Completion in Org-mode."
2873 :tag "Org Completion"
2874 :group 'org)
2876 (defcustom org-completion-use-ido nil
2877 "Non-nil means, use ido completion wherever possible.
2878 Note that `ido-mode' must be active for this variable to be relevant.
2879 If you decide to turn this variable on, you might well want to turn off
2880 `org-outline-path-complete-in-steps'.
2881 See also `org-completion-use-iswitchb'."
2882 :group 'org-completion
2883 :type 'boolean)
2885 (defcustom org-completion-use-iswitchb nil
2886 "Non-nil means, use iswitchb completion wherever possible.
2887 Note that `iswitchb-mode' must be active for this variable to be relevant.
2888 If you decide to turn this variable on, you might well want to turn off
2889 `org-outline-path-complete-in-steps'.
2890 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
2891 :group 'org-completion
2892 :type 'boolean)
2894 (defcustom org-completion-fallback-command 'hippie-expand
2895 "The expansion command called by \\[org-complete] in normal context.
2896 Normal means, no org-mode-specific context."
2897 :group 'org-completion
2898 :type 'function)
2900 ;;; Functions and variables from ther packages
2901 ;; Declared here to avoid compiler warnings
2903 ;; XEmacs only
2904 (defvar outline-mode-menu-heading)
2905 (defvar outline-mode-menu-show)
2906 (defvar outline-mode-menu-hide)
2907 (defvar zmacs-regions) ; XEmacs regions
2909 ;; Emacs only
2910 (defvar mark-active)
2912 ;; Various packages
2913 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2914 (declare-function calendar-forward-day "cal-move" (arg))
2915 (declare-function calendar-goto-date "cal-move" (date))
2916 (declare-function calendar-goto-today "cal-move" ())
2917 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2918 (defvar calc-embedded-close-formula)
2919 (defvar calc-embedded-open-formula)
2920 (declare-function cdlatex-tab "ext:cdlatex" ())
2921 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2922 (defvar font-lock-unfontify-region-function)
2923 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2924 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2925 (defvar iswitchb-temp-buflist)
2926 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2927 (defvar org-agenda-tags-todo-honor-ignore-options)
2928 (declare-function org-agenda-skip "org-agenda" ())
2929 (declare-function org-format-agenda-item "org-agenda"
2930 (extra txt &optional category tags dotime noprefix remove-re))
2931 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2932 (declare-function org-agenda-change-all-lines "org-agenda"
2933 (newhead hdmarker &optional fixface just-this))
2934 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2935 (declare-function org-agenda-maybe-redo "org-agenda" ())
2936 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2937 (beg end))
2938 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2939 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2940 "org-agenda" (&optional end))
2941 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
2942 (declare-function org-indent-mode "org-indent" (arg))
2943 (declare-function parse-time-string "parse-time" (string))
2944 (declare-function remember "remember" (&optional initial))
2945 (declare-function remember-buffer-desc "remember" ())
2946 (declare-function remember-finalize "remember" ())
2947 (defvar remember-save-after-remembering)
2948 (defvar remember-data-file)
2949 (defvar remember-register)
2950 (defvar remember-buffer)
2951 (defvar remember-handler-functions)
2952 (defvar remember-annotation-functions)
2953 (defvar texmathp-why)
2954 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2955 (declare-function table--at-cell-p "table" (position &optional object at-column))
2957 (defvar w3m-current-url)
2958 (defvar w3m-current-title)
2960 (defvar org-latex-regexps)
2962 ;;; Autoload and prepare some org modules
2964 ;; Some table stuff that needs to be defined here, because it is used
2965 ;; by the functions setting up org-mode or checking for table context.
2967 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2968 "Detects an org-type or table-type table.")
2969 (defconst org-table-line-regexp "^[ \t]*|"
2970 "Detects an org-type table line.")
2971 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2972 "Detects an org-type table line.")
2973 (defconst org-table-hline-regexp "^[ \t]*|-"
2974 "Detects an org-type table hline.")
2975 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2976 "Detects a table-type table hline.")
2977 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2978 "Searching from within a table (any type) this finds the first line
2979 outside the table.")
2981 ;; Autoload the functions in org-table.el that are needed by functions here.
2983 (eval-and-compile
2984 (org-autoload "org-table"
2985 '(org-table-align org-table-begin org-table-blank-field
2986 org-table-convert org-table-convert-region org-table-copy-down
2987 org-table-copy-region org-table-create
2988 org-table-create-or-convert-from-region
2989 org-table-create-with-table.el org-table-current-dline
2990 org-table-cut-region org-table-delete-column org-table-edit-field
2991 org-table-edit-formulas org-table-end org-table-eval-formula
2992 org-table-export org-table-field-info
2993 org-table-get-stored-formulas org-table-goto-column
2994 org-table-hline-and-move org-table-import org-table-insert-column
2995 org-table-insert-hline org-table-insert-row org-table-iterate
2996 org-table-justify-field-maybe org-table-kill-row
2997 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2998 org-table-move-column org-table-move-column-left
2999 org-table-move-column-right org-table-move-row
3000 org-table-move-row-down org-table-move-row-up
3001 org-table-next-field org-table-next-row org-table-paste-rectangle
3002 org-table-previous-field org-table-recalculate
3003 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3004 org-table-toggle-coordinate-overlays
3005 org-table-toggle-formula-debugger org-table-wrap-region
3006 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3008 (defun org-at-table-p (&optional table-type)
3009 "Return t if the cursor is inside an org-type table.
3010 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3011 (if org-enable-table-editor
3012 (save-excursion
3013 (beginning-of-line 1)
3014 (looking-at (if table-type org-table-any-line-regexp
3015 org-table-line-regexp)))
3016 nil))
3017 (defsubst org-table-p () (org-at-table-p))
3019 (defun org-at-table.el-p ()
3020 "Return t if and only if we are at a table.el table."
3021 (and (org-at-table-p 'any)
3022 (save-excursion
3023 (goto-char (org-table-begin 'any))
3024 (looking-at org-table1-hline-regexp))))
3025 (defun org-table-recognize-table.el ()
3026 "If there is a table.el table nearby, recognize it and move into it."
3027 (if org-table-tab-recognizes-table.el
3028 (if (org-at-table.el-p)
3029 (progn
3030 (beginning-of-line 1)
3031 (if (looking-at org-table-dataline-regexp)
3033 (if (looking-at org-table1-hline-regexp)
3034 (progn
3035 (beginning-of-line 2)
3036 (if (looking-at org-table-any-border-regexp)
3037 (beginning-of-line -1)))))
3038 (if (re-search-forward "|" (org-table-end t) t)
3039 (progn
3040 (require 'table)
3041 (if (table--at-cell-p (point))
3043 (message "recognizing table.el table...")
3044 (table-recognize-table)
3045 (message "recognizing table.el table...done")))
3046 (error "This should not happen..."))
3048 nil)
3049 nil))
3051 (defun org-at-table-hline-p ()
3052 "Return t if the cursor is inside a hline in a table."
3053 (if org-enable-table-editor
3054 (save-excursion
3055 (beginning-of-line 1)
3056 (looking-at org-table-hline-regexp))
3057 nil))
3059 (defvar org-table-clean-did-remove-column nil)
3061 (defun org-table-map-tables (function)
3062 "Apply FUNCTION to the start of all tables in the buffer."
3063 (save-excursion
3064 (save-restriction
3065 (widen)
3066 (goto-char (point-min))
3067 (while (re-search-forward org-table-any-line-regexp nil t)
3068 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3069 (beginning-of-line 1)
3070 (when (looking-at org-table-line-regexp)
3071 (save-excursion (funcall function))
3072 (or (looking-at org-table-line-regexp)
3073 (forward-char 1)))
3074 (re-search-forward org-table-any-border-regexp nil 1))))
3075 (message "Mapping tables: done"))
3077 ;; Declare and autoload functions from org-exp.el & Co
3079 (declare-function org-default-export-plist "org-exp")
3080 (declare-function org-infile-export-plist "org-exp")
3081 (declare-function org-get-current-options "org-exp")
3082 (eval-and-compile
3083 (org-autoload "org-exp"
3084 '(org-export org-export-visible
3085 org-insert-export-options-template
3086 org-table-clean-before-export))
3087 (org-autoload "org-ascii"
3088 '(org-export-as-ascii org-export-ascii-preprocess
3089 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3090 org-export-region-as-ascii))
3091 (org-autoload "org-html"
3092 '(org-export-as-html-and-open
3093 org-export-as-html-batch org-export-as-html-to-buffer
3094 org-replace-region-by-html org-export-region-as-html
3095 org-export-as-html))
3096 (org-autoload "org-icalendar"
3097 '(org-export-icalendar-this-file
3098 org-export-icalendar-all-agenda-files
3099 org-export-icalendar-combine-agenda-files))
3100 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3102 ;; Declare and autoload functions from org-agenda.el
3104 (eval-and-compile
3105 (org-autoload "org-agenda"
3106 '(org-agenda org-agenda-list org-search-view
3107 org-todo-list org-tags-view org-agenda-list-stuck-projects
3108 org-diary org-agenda-to-appt
3109 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3111 ;; Autoload org-remember
3113 (eval-and-compile
3114 (org-autoload "org-remember"
3115 '(org-remember-insinuate org-remember-annotation
3116 org-remember-apply-template org-remember org-remember-handler)))
3118 ;; Autoload org-clock.el
3121 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3122 (beg end))
3123 (declare-function org-clock-update-mode-line "org-clock" ())
3124 (defvar org-clock-start-time)
3125 (defvar org-clock-marker (make-marker)
3126 "Marker recording the last clock-in.")
3127 (defvar org-clock-hd-marker (make-marker)
3128 "Marker recording the last clock-in, but the headline position.")
3129 (defun org-clock-is-active ()
3130 "Return non-nil if clock is currently running.
3131 The return value is actually the clock marker."
3132 (marker-buffer org-clock-marker))
3134 (eval-and-compile
3135 (org-autoload
3136 "org-clock"
3137 '(org-clock-in org-clock-out org-clock-cancel
3138 org-clock-goto org-clock-sum org-clock-display
3139 org-clock-remove-overlays org-clock-report
3140 org-clocktable-shift org-dblock-write:clocktable
3141 org-get-clocktable)))
3143 (defun org-clock-update-time-maybe ()
3144 "If this is a CLOCK line, update it and return t.
3145 Otherwise, return nil."
3146 (interactive)
3147 (save-excursion
3148 (beginning-of-line 1)
3149 (skip-chars-forward " \t")
3150 (when (looking-at org-clock-string)
3151 (let ((re (concat "[ \t]*" org-clock-string
3152 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3153 "\\([ \t]*=>.*\\)?\\)?"))
3154 ts te h m s neg)
3155 (cond
3156 ((not (looking-at re))
3157 nil)
3158 ((not (match-end 2))
3159 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3160 (> org-clock-marker (point))
3161 (<= org-clock-marker (point-at-eol)))
3162 ;; The clock is running here
3163 (setq org-clock-start-time
3164 (apply 'encode-time
3165 (org-parse-time-string (match-string 1))))
3166 (org-clock-update-mode-line)))
3168 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3169 (end-of-line 1)
3170 (setq ts (match-string 1)
3171 te (match-string 3))
3172 (setq s (- (org-float-time
3173 (apply 'encode-time (org-parse-time-string te)))
3174 (org-float-time
3175 (apply 'encode-time (org-parse-time-string ts))))
3176 neg (< s 0)
3177 s (abs s)
3178 h (floor (/ s 3600))
3179 s (- s (* 3600 h))
3180 m (floor (/ s 60))
3181 s (- s (* 60 s)))
3182 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3183 t))))))
3185 (defun org-check-running-clock ()
3186 "Check if the current buffer contains the running clock.
3187 If yes, offer to stop it and to save the buffer with the changes."
3188 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3189 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3190 (buffer-name))))
3191 (org-clock-out)
3192 (when (y-or-n-p "Save changed buffer?")
3193 (save-buffer))))
3195 (defun org-clocktable-try-shift (dir n)
3196 "Check if this line starts a clock table, if yes, shift the time block."
3197 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3198 (org-clocktable-shift dir n)))
3200 ;; Autoload org-timer.el
3202 (eval-and-compile
3203 (org-autoload
3204 "org-timer"
3205 '(org-timer-start org-timer org-timer-item
3206 org-timer-change-times-in-region
3207 org-timer-set-timer
3208 org-timer-reset-timers
3209 org-timer-show-remaining-time)))
3211 ;; Autoload org-feed.el
3213 (eval-and-compile
3214 (org-autoload
3215 "org-feed"
3216 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3219 ;; Autoload org-indent.el
3221 (eval-and-compile
3222 (org-autoload
3223 "org-indent"
3224 '(org-indent-mode)))
3226 ;; Autoload org-mobile.el
3228 (eval-and-compile
3229 (org-autoload
3230 "org-mobile"
3231 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3233 ;; Autoload archiving code
3234 ;; The stuff that is needed for cycling and tags has to be defined here.
3236 (defgroup org-archive nil
3237 "Options concerning archiving in Org-mode."
3238 :tag "Org Archive"
3239 :group 'org-structure)
3241 (defcustom org-archive-location "%s_archive::"
3242 "The location where subtrees should be archived.
3244 The value of this variable is a string, consisting of two parts,
3245 separated by a double-colon. The first part is a filename and
3246 the second part is a headline.
3248 When the filename is omitted, archiving happens in the same file.
3249 %s in the filename will be replaced by the current file
3250 name (without the directory part). Archiving to a different file
3251 is useful to keep archived entries from contributing to the
3252 Org-mode Agenda.
3254 The archived entries will be filed as subtrees of the specified
3255 headline. When the headline is omitted, the subtrees are simply
3256 filed away at the end of the file, as top-level entries. Also in
3257 the heading you can use %s to represent the file name, this can be
3258 useful when using the same archive for a number of different files.
3260 Here are a few examples:
3261 \"%s_archive::\"
3262 If the current file is Projects.org, archive in file
3263 Projects.org_archive, as top-level trees. This is the default.
3265 \"::* Archived Tasks\"
3266 Archive in the current file, under the top-level headline
3267 \"* Archived Tasks\".
3269 \"~/org/archive.org::\"
3270 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3272 \"~/org/archive.org::From %s\"
3273 Archive in file ~/org/archive.org (absolute path), und headlines
3274 \"From FILENAME\" where file name is the current file name.
3276 \"basement::** Finished Tasks\"
3277 Archive in file ./basement (relative path), as level 3 trees
3278 below the level 2 heading \"** Finished Tasks\".
3280 You may set this option on a per-file basis by adding to the buffer a
3281 line like
3283 #+ARCHIVE: basement::** Finished Tasks
3285 You may also define it locally for a subtree by setting an ARCHIVE property
3286 in the entry. If such a property is found in an entry, or anywhere up
3287 the hierarchy, it will be used."
3288 :group 'org-archive
3289 :type 'string)
3291 (defcustom org-archive-tag "ARCHIVE"
3292 "The tag that marks a subtree as archived.
3293 An archived subtree does not open during visibility cycling, and does
3294 not contribute to the agenda listings.
3295 After changing this, font-lock must be restarted in the relevant buffers to
3296 get the proper fontification."
3297 :group 'org-archive
3298 :group 'org-keywords
3299 :type 'string)
3301 (defcustom org-agenda-skip-archived-trees t
3302 "Non-nil means, the agenda will skip any items located in archived trees.
3303 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3304 variable is no longer recommended, you should leave it at the value t.
3305 Instead, use the key `v' to cycle the archives-mode in the agenda."
3306 :group 'org-archive
3307 :group 'org-agenda-skip
3308 :type 'boolean)
3310 (defcustom org-columns-skip-arrchived-trees t
3311 "Non-nil means, irgnore archived trees when creating column view."
3312 :group 'org-archive
3313 :group 'org-properties
3314 :type 'boolean)
3316 (defcustom org-cycle-open-archived-trees nil
3317 "Non-nil means, `org-cycle' will open archived trees.
3318 An archived tree is a tree marked with the tag ARCHIVE.
3319 When nil, archived trees will stay folded. You can still open them with
3320 normal outline commands like `show-all', but not with the cycling commands."
3321 :group 'org-archive
3322 :group 'org-cycle
3323 :type 'boolean)
3325 (defcustom org-sparse-tree-open-archived-trees nil
3326 "Non-nil means sparse tree construction shows matches in archived trees.
3327 When nil, matches in these trees are highlighted, but the trees are kept in
3328 collapsed state."
3329 :group 'org-archive
3330 :group 'org-sparse-trees
3331 :type 'boolean)
3333 (defun org-cycle-hide-archived-subtrees (state)
3334 "Re-hide all archived subtrees after a visibility state change."
3335 (when (and (not org-cycle-open-archived-trees)
3336 (not (memq state '(overview folded))))
3337 (save-excursion
3338 (let* ((globalp (memq state '(contents all)))
3339 (beg (if globalp (point-min) (point)))
3340 (end (if globalp (point-max) (org-end-of-subtree t))))
3341 (org-hide-archived-subtrees beg end)
3342 (goto-char beg)
3343 (if (looking-at (concat ".*:" org-archive-tag ":"))
3344 (message "%s" (substitute-command-keys
3345 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3347 (defun org-force-cycle-archived ()
3348 "Cycle subtree even if it is archived."
3349 (interactive)
3350 (setq this-command 'org-cycle)
3351 (let ((org-cycle-open-archived-trees t))
3352 (call-interactively 'org-cycle)))
3354 (defun org-hide-archived-subtrees (beg end)
3355 "Re-hide all archived subtrees after a visibility state change."
3356 (save-excursion
3357 (let* ((re (concat ":" org-archive-tag ":")))
3358 (goto-char beg)
3359 (while (re-search-forward re end t)
3360 (and (org-on-heading-p) (hide-subtree))
3361 (org-end-of-subtree t)))))
3363 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3365 (eval-and-compile
3366 (org-autoload "org-archive"
3367 '(org-add-archive-files org-archive-subtree
3368 org-archive-to-archive-sibling org-toggle-archive-tag)))
3370 ;; Autoload Column View Code
3372 (declare-function org-columns-number-to-string "org-colview")
3373 (declare-function org-columns-get-format-and-top-level "org-colview")
3374 (declare-function org-columns-compute "org-colview")
3376 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3377 '(org-columns-number-to-string org-columns-get-format-and-top-level
3378 org-columns-compute org-agenda-columns org-columns-remove-overlays
3379 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3381 ;; Autoload ID code
3383 (declare-function org-id-store-link "org-id")
3384 (declare-function org-id-locations-load "org-id")
3385 (declare-function org-id-locations-save "org-id")
3386 (defvar org-id-track-globally)
3387 (org-autoload "org-id"
3388 '(org-id-get-create org-id-new org-id-copy org-id-get
3389 org-id-get-with-outline-path-completion
3390 org-id-get-with-outline-drilling
3391 org-id-goto org-id-find org-id-store-link))
3393 ;; Autoload Plotting Code
3395 (org-autoload "org-plot"
3396 '(org-plot/gnuplot))
3398 ;;; Variables for pre-computed regular expressions, all buffer local
3400 (defvar org-drawer-regexp nil
3401 "Matches first line of a hidden block.")
3402 (make-variable-buffer-local 'org-drawer-regexp)
3403 (defvar org-todo-regexp nil
3404 "Matches any of the TODO state keywords.")
3405 (make-variable-buffer-local 'org-todo-regexp)
3406 (defvar org-not-done-regexp nil
3407 "Matches any of the TODO state keywords except the last one.")
3408 (make-variable-buffer-local 'org-not-done-regexp)
3409 (defvar org-not-done-heading-regexp nil
3410 "Matches a TODO headline that is not done.")
3411 (make-variable-buffer-local 'org-not-done-regexp)
3412 (defvar org-todo-line-regexp nil
3413 "Matches a headline and puts TODO state into group 2 if present.")
3414 (make-variable-buffer-local 'org-todo-line-regexp)
3415 (defvar org-complex-heading-regexp nil
3416 "Matches a headline and puts everything into groups:
3417 group 1: the stars
3418 group 2: The todo keyword, maybe
3419 group 3: Priority cookie
3420 group 4: True headline
3421 group 5: Tags")
3422 (make-variable-buffer-local 'org-complex-heading-regexp)
3423 (defvar org-todo-line-tags-regexp nil
3424 "Matches a headline and puts TODO state into group 2 if present.
3425 Also put tags into group 4 if tags are present.")
3426 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3427 (defvar org-nl-done-regexp nil
3428 "Matches newline followed by a headline with the DONE keyword.")
3429 (make-variable-buffer-local 'org-nl-done-regexp)
3430 (defvar org-looking-at-done-regexp nil
3431 "Matches the DONE keyword a point.")
3432 (make-variable-buffer-local 'org-looking-at-done-regexp)
3433 (defvar org-ds-keyword-length 12
3434 "Maximum length of the Deadline and SCHEDULED keywords.")
3435 (make-variable-buffer-local 'org-ds-keyword-length)
3436 (defvar org-deadline-regexp nil
3437 "Matches the DEADLINE keyword.")
3438 (make-variable-buffer-local 'org-deadline-regexp)
3439 (defvar org-deadline-time-regexp nil
3440 "Matches the DEADLINE keyword together with a time stamp.")
3441 (make-variable-buffer-local 'org-deadline-time-regexp)
3442 (defvar org-deadline-line-regexp nil
3443 "Matches the DEADLINE keyword and the rest of the line.")
3444 (make-variable-buffer-local 'org-deadline-line-regexp)
3445 (defvar org-scheduled-regexp nil
3446 "Matches the SCHEDULED keyword.")
3447 (make-variable-buffer-local 'org-scheduled-regexp)
3448 (defvar org-scheduled-time-regexp nil
3449 "Matches the SCHEDULED keyword together with a time stamp.")
3450 (make-variable-buffer-local 'org-scheduled-time-regexp)
3451 (defvar org-closed-time-regexp nil
3452 "Matches the CLOSED keyword together with a time stamp.")
3453 (make-variable-buffer-local 'org-closed-time-regexp)
3455 (defvar org-keyword-time-regexp nil
3456 "Matches any of the 4 keywords, together with the time stamp.")
3457 (make-variable-buffer-local 'org-keyword-time-regexp)
3458 (defvar org-keyword-time-not-clock-regexp nil
3459 "Matches any of the 3 keywords, together with the time stamp.")
3460 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3461 (defvar org-maybe-keyword-time-regexp nil
3462 "Matches a timestamp, possibly preceeded by a keyword.")
3463 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3464 (defvar org-planning-or-clock-line-re nil
3465 "Matches a line with planning or clock info.")
3466 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3468 (defconst org-plain-time-of-day-regexp
3469 (concat
3470 "\\(\\<[012]?[0-9]"
3471 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3472 "\\(--?"
3473 "\\(\\<[012]?[0-9]"
3474 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3475 "\\)?")
3476 "Regular expression to match a plain time or time range.
3477 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3478 groups carry important information:
3479 0 the full match
3480 1 the first time, range or not
3481 8 the second time, if it is a range.")
3483 (defconst org-plain-time-extension-regexp
3484 (concat
3485 "\\(\\<[012]?[0-9]"
3486 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3487 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3488 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3489 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3490 groups carry important information:
3491 0 the full match
3492 7 hours of duration
3493 9 minutes of duration")
3495 (defconst org-stamp-time-of-day-regexp
3496 (concat
3497 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3498 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3499 "\\(--?"
3500 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3501 "Regular expression to match a timestamp time or time range.
3502 After a match, the following groups carry important information:
3503 0 the full match
3504 1 date plus weekday, for backreferencing to make sure both times on same day
3505 2 the first time, range or not
3506 4 the second time, if it is a range.")
3508 (defconst org-startup-options
3509 '(("fold" org-startup-folded t)
3510 ("overview" org-startup-folded t)
3511 ("nofold" org-startup-folded nil)
3512 ("showall" org-startup-folded nil)
3513 ("content" org-startup-folded content)
3514 ("indent" org-startup-indented t)
3515 ("noindent" org-startup-indented nil)
3516 ("hidestars" org-hide-leading-stars t)
3517 ("showstars" org-hide-leading-stars nil)
3518 ("odd" org-odd-levels-only t)
3519 ("oddeven" org-odd-levels-only nil)
3520 ("align" org-startup-align-all-tables t)
3521 ("noalign" org-startup-align-all-tables nil)
3522 ("customtime" org-display-custom-times t)
3523 ("logdone" org-log-done time)
3524 ("lognotedone" org-log-done note)
3525 ("nologdone" org-log-done nil)
3526 ("lognoteclock-out" org-log-note-clock-out t)
3527 ("nolognoteclock-out" org-log-note-clock-out nil)
3528 ("logrepeat" org-log-repeat state)
3529 ("lognoterepeat" org-log-repeat note)
3530 ("nologrepeat" org-log-repeat nil)
3531 ("fninline" org-footnote-define-inline t)
3532 ("nofninline" org-footnote-define-inline nil)
3533 ("fnlocal" org-footnote-section nil)
3534 ("fnauto" org-footnote-auto-label t)
3535 ("fnprompt" org-footnote-auto-label nil)
3536 ("fnconfirm" org-footnote-auto-label confirm)
3537 ("fnplain" org-footnote-auto-label plain)
3538 ("fnadjust" org-footnote-auto-adjust t)
3539 ("nofnadjust" org-footnote-auto-adjust nil)
3540 ("constcgs" constants-unit-system cgs)
3541 ("constSI" constants-unit-system SI)
3542 ("noptag" org-tag-persistent-alist nil)
3543 ("hideblocks" org-hide-block-startup t)
3544 ("nohideblocks" org-hide-block-startup nil))
3545 "Variable associated with STARTUP options for org-mode.
3546 Each element is a list of three items: The startup options as written
3547 in the #+STARTUP line, the corresponding variable, and the value to
3548 set this variable to if the option is found. An optional forth element PUSH
3549 means to push this value onto the list in the variable.")
3551 (defun org-set-regexps-and-options ()
3552 "Precompute regular expressions for current buffer."
3553 (when (org-mode-p)
3554 (org-set-local 'org-todo-kwd-alist nil)
3555 (org-set-local 'org-todo-key-alist nil)
3556 (org-set-local 'org-todo-key-trigger nil)
3557 (org-set-local 'org-todo-keywords-1 nil)
3558 (org-set-local 'org-done-keywords nil)
3559 (org-set-local 'org-todo-heads nil)
3560 (org-set-local 'org-todo-sets nil)
3561 (org-set-local 'org-todo-log-states nil)
3562 (org-set-local 'org-file-properties nil)
3563 (org-set-local 'org-file-tags nil)
3564 (let ((re (org-make-options-regexp
3565 '("CATEGORY" "TODO" "COLUMNS"
3566 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3567 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3568 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3569 (splitre "[ \t]+")
3570 kwds kws0 kwsa key log value cat arch tags const links hw dws
3571 tail sep kws1 prio props ftags drawers
3572 ext-setup-or-nil setup-contents (start 0))
3573 (save-excursion
3574 (save-restriction
3575 (widen)
3576 (goto-char (point-min))
3577 (while (or (and ext-setup-or-nil
3578 (string-match re ext-setup-or-nil start)
3579 (setq start (match-end 0)))
3580 (and (setq ext-setup-or-nil nil start 0)
3581 (re-search-forward re nil t)))
3582 (setq key (upcase (match-string 1 ext-setup-or-nil))
3583 value (org-match-string-no-properties 2 ext-setup-or-nil))
3584 (cond
3585 ((equal key "CATEGORY")
3586 (if (string-match "[ \t]+$" value)
3587 (setq value (replace-match "" t t value)))
3588 (setq cat value))
3589 ((member key '("SEQ_TODO" "TODO"))
3590 (push (cons 'sequence (org-split-string value splitre)) kwds))
3591 ((equal key "TYP_TODO")
3592 (push (cons 'type (org-split-string value splitre)) kwds))
3593 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3594 ;; general TODO-like setup
3595 (push (cons (intern (downcase (match-string 1 key)))
3596 (org-split-string value splitre)) kwds))
3597 ((equal key "TAGS")
3598 (setq tags (append tags (if tags '("\\n") nil)
3599 (org-split-string value splitre))))
3600 ((equal key "COLUMNS")
3601 (org-set-local 'org-columns-default-format value))
3602 ((equal key "LINK")
3603 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3604 (push (cons (match-string 1 value)
3605 (org-trim (match-string 2 value)))
3606 links)))
3607 ((equal key "PRIORITIES")
3608 (setq prio (org-split-string value " +")))
3609 ((equal key "PROPERTY")
3610 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3611 (push (cons (match-string 1 value) (match-string 2 value))
3612 props)))
3613 ((equal key "FILETAGS")
3614 (when (string-match "\\S-" value)
3615 (setq ftags
3616 (append
3617 ftags
3618 (apply 'append
3619 (mapcar (lambda (x) (org-split-string x ":"))
3620 (org-split-string value)))))))
3621 ((equal key "DRAWERS")
3622 (setq drawers (org-split-string value splitre)))
3623 ((equal key "CONSTANTS")
3624 (setq const (append const (org-split-string value splitre))))
3625 ((equal key "STARTUP")
3626 (let ((opts (org-split-string value splitre))
3627 l var val)
3628 (while (setq l (pop opts))
3629 (when (setq l (assoc l org-startup-options))
3630 (setq var (nth 1 l) val (nth 2 l))
3631 (if (not (nth 3 l))
3632 (set (make-local-variable var) val)
3633 (if (not (listp (symbol-value var)))
3634 (set (make-local-variable var) nil))
3635 (set (make-local-variable var) (symbol-value var))
3636 (add-to-list var val))))))
3637 ((equal key "ARCHIVE")
3638 (string-match " *$" value)
3639 (setq arch (replace-match "" t t value))
3640 (remove-text-properties 0 (length arch)
3641 '(face t fontified t) arch))
3642 ((equal key "SETUPFILE")
3643 (setq setup-contents (org-file-contents
3644 (expand-file-name
3645 (org-remove-double-quotes value))
3646 'noerror))
3647 (if (not ext-setup-or-nil)
3648 (setq ext-setup-or-nil setup-contents start 0)
3649 (setq ext-setup-or-nil
3650 (concat (substring ext-setup-or-nil 0 start)
3651 "\n" setup-contents "\n"
3652 (substring ext-setup-or-nil start)))))
3653 ))))
3654 (when cat
3655 (org-set-local 'org-category (intern cat))
3656 (push (cons "CATEGORY" cat) props))
3657 (when prio
3658 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3659 (setq prio (mapcar 'string-to-char prio))
3660 (org-set-local 'org-highest-priority (nth 0 prio))
3661 (org-set-local 'org-lowest-priority (nth 1 prio))
3662 (org-set-local 'org-default-priority (nth 2 prio)))
3663 (and props (org-set-local 'org-file-properties (nreverse props)))
3664 (and ftags (org-set-local 'org-file-tags
3665 (mapcar 'org-add-prop-inherited ftags)))
3666 (and drawers (org-set-local 'org-drawers drawers))
3667 (and arch (org-set-local 'org-archive-location arch))
3668 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3669 ;; Process the TODO keywords
3670 (unless kwds
3671 ;; Use the global values as if they had been given locally.
3672 (setq kwds (default-value 'org-todo-keywords))
3673 (if (stringp (car kwds))
3674 (setq kwds (list (cons org-todo-interpretation
3675 (default-value 'org-todo-keywords)))))
3676 (setq kwds (reverse kwds)))
3677 (setq kwds (nreverse kwds))
3678 (let (inter kws kw)
3679 (while (setq kws (pop kwds))
3680 (let ((kws (or
3681 (run-hook-with-args-until-success
3682 'org-todo-setup-filter-hook kws)
3683 kws)))
3684 (setq inter (pop kws) sep (member "|" kws)
3685 kws0 (delete "|" (copy-sequence kws))
3686 kwsa nil
3687 kws1 (mapcar
3688 (lambda (x)
3689 ;; 1 2
3690 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3691 (progn
3692 (setq kw (match-string 1 x)
3693 key (and (match-end 2) (match-string 2 x))
3694 log (org-extract-log-state-settings x))
3695 (push (cons kw (and key (string-to-char key))) kwsa)
3696 (and log (push log org-todo-log-states))
3698 (error "Invalid TODO keyword %s" x)))
3699 kws0)
3700 kwsa (if kwsa (append '((:startgroup))
3701 (nreverse kwsa)
3702 '((:endgroup))))
3703 hw (car kws1)
3704 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3705 tail (list inter hw (car dws) (org-last dws))))
3706 (add-to-list 'org-todo-heads hw 'append)
3707 (push kws1 org-todo-sets)
3708 (setq org-done-keywords (append org-done-keywords dws nil))
3709 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3710 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3711 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3712 (setq org-todo-sets (nreverse org-todo-sets)
3713 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3714 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3715 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3716 ;; Process the constants
3717 (when const
3718 (let (e cst)
3719 (while (setq e (pop const))
3720 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3721 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3722 (setq org-table-formula-constants-local cst)))
3724 ;; Process the tags.
3725 (when tags
3726 (let (e tgs)
3727 (while (setq e (pop tags))
3728 (cond
3729 ((equal e "{") (push '(:startgroup) tgs))
3730 ((equal e "}") (push '(:endgroup) tgs))
3731 ((equal e "\\n") (push '(:newline) tgs))
3732 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3733 (push (cons (match-string 1 e)
3734 (string-to-char (match-string 2 e)))
3735 tgs))
3736 (t (push (list e) tgs))))
3737 (org-set-local 'org-tag-alist nil)
3738 (while (setq e (pop tgs))
3739 (or (and (stringp (car e))
3740 (assoc (car e) org-tag-alist))
3741 (push e org-tag-alist)))))
3743 ;; Compute the regular expressions and other local variables
3744 (if (not org-done-keywords)
3745 (setq org-done-keywords (and org-todo-keywords-1
3746 (list (org-last org-todo-keywords-1)))))
3747 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3748 (length org-scheduled-string)
3749 (length org-clock-string)
3750 (length org-closed-string)))
3751 org-drawer-regexp
3752 (concat "^[ \t]*:\\("
3753 (mapconcat 'regexp-quote org-drawers "\\|")
3754 "\\):[ \t]*$")
3755 org-not-done-keywords
3756 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3757 org-todo-regexp
3758 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3759 "\\|") "\\)\\>")
3760 org-not-done-regexp
3761 (concat "\\<\\("
3762 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3763 "\\)\\>")
3764 org-not-done-heading-regexp
3765 (concat "^\\(\\*+\\)[ \t]+\\("
3766 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3767 "\\)\\>")
3768 org-todo-line-regexp
3769 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3770 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3771 "\\)\\>\\)?[ \t]*\\(.*\\)")
3772 org-complex-heading-regexp
3773 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3774 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3775 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3776 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3777 org-nl-done-regexp
3778 (concat "\n\\*+[ \t]+"
3779 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3780 "\\)" "\\>")
3781 org-todo-line-tags-regexp
3782 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3783 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3784 (org-re
3785 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3786 org-looking-at-done-regexp
3787 (concat "^" "\\(?:"
3788 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3789 "\\>")
3790 org-deadline-regexp (concat "\\<" org-deadline-string)
3791 org-deadline-time-regexp
3792 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3793 org-deadline-line-regexp
3794 (concat "\\<\\(" org-deadline-string "\\).*")
3795 org-scheduled-regexp
3796 (concat "\\<" org-scheduled-string)
3797 org-scheduled-time-regexp
3798 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3799 org-closed-time-regexp
3800 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3801 org-keyword-time-regexp
3802 (concat "\\<\\(" org-scheduled-string
3803 "\\|" org-deadline-string
3804 "\\|" org-closed-string
3805 "\\|" org-clock-string "\\)"
3806 " *[[<]\\([^]>]+\\)[]>]")
3807 org-keyword-time-not-clock-regexp
3808 (concat "\\<\\(" org-scheduled-string
3809 "\\|" org-deadline-string
3810 "\\|" org-closed-string
3811 "\\)"
3812 " *[[<]\\([^]>]+\\)[]>]")
3813 org-maybe-keyword-time-regexp
3814 (concat "\\(\\<\\(" org-scheduled-string
3815 "\\|" org-deadline-string
3816 "\\|" org-closed-string
3817 "\\|" org-clock-string "\\)\\)?"
3818 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3819 org-planning-or-clock-line-re
3820 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3821 "\\|" org-deadline-string
3822 "\\|" org-closed-string "\\|" org-clock-string
3823 "\\)\\>\\)")
3825 (org-compute-latex-and-specials-regexp)
3826 (org-set-font-lock-defaults))))
3828 (defun org-file-contents (file &optional noerror)
3829 "Return the contents of FILE, as a string."
3830 (if (or (not file)
3831 (not (file-readable-p file)))
3832 (if noerror
3833 (progn
3834 (message "Cannot read file %s" file)
3835 (ding) (sit-for 2)
3837 (error "Cannot read file %s" file))
3838 (with-temp-buffer
3839 (insert-file-contents file)
3840 (buffer-string))))
3842 (defun org-extract-log-state-settings (x)
3843 "Extract the log state setting from a TODO keyword string.
3844 This will extract info from a string like \"WAIT(w@/!)\"."
3845 (let (kw key log1 log2)
3846 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3847 (setq kw (match-string 1 x)
3848 key (and (match-end 2) (match-string 2 x))
3849 log1 (and (match-end 3) (match-string 3 x))
3850 log2 (and (match-end 4) (match-string 4 x)))
3851 (and (or log1 log2)
3852 (list kw
3853 (and log1 (if (equal log1 "!") 'time 'note))
3854 (and log2 (if (equal log2 "!") 'time 'note)))))))
3856 (defun org-remove-keyword-keys (list)
3857 "Remove a pair of parenthesis at the end of each string in LIST."
3858 (mapcar (lambda (x)
3859 (if (string-match "(.*)$" x)
3860 (substring x 0 (match-beginning 0))
3862 list))
3864 ;; FIXME: this could be done much better, using second characters etc.
3865 (defun org-assign-fast-keys (alist)
3866 "Assign fast keys to a keyword-key alist.
3867 Respect keys that are already there."
3868 (let (new e k c c1 c2 (char ?a))
3869 (while (setq e (pop alist))
3870 (cond
3871 ((equal e '(:startgroup)) (push e new))
3872 ((equal e '(:endgroup)) (push e new))
3873 ((equal e '(:newline)) (push e new))
3875 (setq k (car e) c2 nil)
3876 (if (cdr e)
3877 (setq c (cdr e))
3878 ;; automatically assign a character.
3879 (setq c1 (string-to-char
3880 (downcase (substring
3881 k (if (= (string-to-char k) ?@) 1 0)))))
3882 (if (or (rassoc c1 new) (rassoc c1 alist))
3883 (while (or (rassoc char new) (rassoc char alist))
3884 (setq char (1+ char)))
3885 (setq c2 c1))
3886 (setq c (or c2 char)))
3887 (push (cons k c) new))))
3888 (nreverse new)))
3890 ;;; Some variables used in various places
3892 (defvar org-window-configuration nil
3893 "Used in various places to store a window configuration.")
3894 (defvar org-selected-window nil
3895 "Used in various places to store a window configuration.")
3896 (defvar org-finish-function nil
3897 "Function to be called when `C-c C-c' is used.
3898 This is for getting out of special buffers like remember.")
3901 ;; FIXME: Occasionally check by commenting these, to make sure
3902 ;; no other functions uses these, forgetting to let-bind them.
3903 (defvar entry)
3904 (defvar last-state)
3905 (defvar date)
3907 ;; Defined somewhere in this file, but used before definition.
3908 (defvar org-html-entities)
3909 (defvar org-struct-menu)
3910 (defvar org-org-menu)
3911 (defvar org-tbl-menu)
3912 (defvar org-agenda-keymap)
3914 ;;;; Define the Org-mode
3916 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3917 (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."))
3920 ;; We use a before-change function to check if a table might need
3921 ;; an update.
3922 (defvar org-table-may-need-update t
3923 "Indicates that a table might need an update.
3924 This variable is set by `org-before-change-function'.
3925 `org-table-align' sets it back to nil.")
3926 (defun org-before-change-function (beg end)
3927 "Every change indicates that a table might need an update."
3928 (setq org-table-may-need-update t))
3929 (defvar org-mode-map)
3930 (defvar org-mode-hook nil
3931 "Mode hook for Org-mode, run after the mode was turned on.")
3932 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3933 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3934 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3935 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3936 (defvar org-table-buffer-is-an nil)
3937 (defconst org-outline-regexp "\\*+ ")
3939 ;;;###autoload
3940 (define-derived-mode org-mode outline-mode "Org"
3941 "Outline-based notes management and organizer, alias
3942 \"Carsten's outline-mode for keeping track of everything.\"
3944 Org-mode develops organizational tasks around a NOTES file which
3945 contains information about projects as plain text. Org-mode is
3946 implemented on top of outline-mode, which is ideal to keep the content
3947 of large files well structured. It supports ToDo items, deadlines and
3948 time stamps, which magically appear in the diary listing of the Emacs
3949 calendar. Tables are easily created with a built-in table editor.
3950 Plain text URL-like links connect to websites, emails (VM), Usenet
3951 messages (Gnus), BBDB entries, and any files related to the project.
3952 For printing and sharing of notes, an Org-mode file (or a part of it)
3953 can be exported as a structured ASCII or HTML file.
3955 The following commands are available:
3957 \\{org-mode-map}"
3959 ;; Get rid of Outline menus, they are not needed
3960 ;; Need to do this here because define-derived-mode sets up
3961 ;; the keymap so late. Still, it is a waste to call this each time
3962 ;; we switch another buffer into org-mode.
3963 (if (featurep 'xemacs)
3964 (when (boundp 'outline-mode-menu-heading)
3965 ;; Assume this is Greg's port, it used easymenu
3966 (easy-menu-remove outline-mode-menu-heading)
3967 (easy-menu-remove outline-mode-menu-show)
3968 (easy-menu-remove outline-mode-menu-hide))
3969 (define-key org-mode-map [menu-bar headings] 'undefined)
3970 (define-key org-mode-map [menu-bar hide] 'undefined)
3971 (define-key org-mode-map [menu-bar show] 'undefined))
3973 (org-load-modules-maybe)
3974 (easy-menu-add org-org-menu)
3975 (easy-menu-add org-tbl-menu)
3976 (org-install-agenda-files-menu)
3977 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3978 (org-add-to-invisibility-spec '(org-cwidth))
3979 (org-add-to-invisibility-spec '(org-hide-block . t))
3980 (when (featurep 'xemacs)
3981 (org-set-local 'line-move-ignore-invisible t))
3982 (org-set-local 'outline-regexp org-outline-regexp)
3983 (org-set-local 'outline-level 'org-outline-level)
3984 (when (and org-ellipsis
3985 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3986 (fboundp 'make-glyph-code))
3987 (unless org-display-table
3988 (setq org-display-table (make-display-table)))
3989 (set-display-table-slot
3990 org-display-table 4
3991 (vconcat (mapcar
3992 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3993 org-ellipsis)))
3994 (if (stringp org-ellipsis) org-ellipsis "..."))))
3995 (setq buffer-display-table org-display-table))
3996 (org-set-regexps-and-options)
3997 (when (and org-tag-faces (not org-tags-special-faces-re))
3998 ;; tag faces set outside customize.... force initialization.
3999 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4000 ;; Calc embedded
4001 (org-set-local 'calc-embedded-open-mode "# ")
4002 (modify-syntax-entry ?# "<")
4003 (modify-syntax-entry ?@ "w")
4004 (if org-startup-truncated (setq truncate-lines t))
4005 (org-set-local 'font-lock-unfontify-region-function
4006 'org-unfontify-region)
4007 ;; Activate before-change-function
4008 (org-set-local 'org-table-may-need-update t)
4009 (org-add-hook 'before-change-functions 'org-before-change-function nil
4010 'local)
4011 ;; Check for running clock before killing a buffer
4012 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4013 ;; Paragraphs and auto-filling
4014 (org-set-autofill-regexps)
4015 (setq indent-line-function 'org-indent-line-function)
4016 (org-update-radio-target-regexp)
4017 ;; Make sure dependence stuff works reliably, even for users who set it
4018 ;; too late :-(
4019 (if org-enforce-todo-dependencies
4020 (add-hook 'org-blocker-hook
4021 'org-block-todo-from-children-or-siblings-or-parent)
4022 (remove-hook 'org-blocker-hook
4023 'org-block-todo-from-children-or-siblings-or-parent))
4024 (if org-enforce-todo-checkbox-dependencies
4025 (add-hook 'org-blocker-hook
4026 'org-block-todo-from-checkboxes)
4027 (remove-hook 'org-blocker-hook
4028 'org-block-todo-from-checkboxes))
4030 ;; Comment characters
4031 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4032 (org-set-local 'comment-padding " ")
4034 ;; Align options lines
4035 (org-set-local
4036 'align-mode-rules-list
4037 '((org-in-buffer-settings
4038 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4039 (modes . '(org-mode)))))
4041 ;; Imenu
4042 (org-set-local 'imenu-create-index-function
4043 'org-imenu-get-tree)
4045 ;; Make isearch reveal context
4046 (if (or (featurep 'xemacs)
4047 (not (boundp 'outline-isearch-open-invisible-function)))
4048 ;; Emacs 21 and XEmacs make use of the hook
4049 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4050 ;; Emacs 22 deals with this through a special variable
4051 (org-set-local 'outline-isearch-open-invisible-function
4052 (lambda (&rest ignore) (org-show-context 'isearch))))
4054 ;; If empty file that did not turn on org-mode automatically, make it to.
4055 (if (and org-insert-mode-line-in-empty-file
4056 (interactive-p)
4057 (= (point-min) (point-max)))
4058 (insert "# -*- mode: org -*-\n\n"))
4060 (unless org-inhibit-startup
4061 (when org-startup-align-all-tables
4062 (let ((bmp (buffer-modified-p)))
4063 (org-table-map-tables 'org-table-align)
4064 (set-buffer-modified-p bmp)))
4065 (when org-startup-indented
4066 (require 'org-indent)
4067 (org-indent-mode 1))
4068 (org-set-startup-visibility)))
4070 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4072 (defun org-current-time ()
4073 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4074 (if (> (car org-time-stamp-rounding-minutes) 1)
4075 (let ((r (car org-time-stamp-rounding-minutes))
4076 (time (decode-time)))
4077 (apply 'encode-time
4078 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4079 (nthcdr 2 time))))
4080 (current-time)))
4082 ;;;; Font-Lock stuff, including the activators
4084 (defvar org-mouse-map (make-sparse-keymap))
4085 (org-defkey org-mouse-map
4086 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4087 (org-defkey org-mouse-map
4088 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4089 (when org-mouse-1-follows-link
4090 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4091 (when org-tab-follows-link
4092 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4093 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4095 (require 'font-lock)
4097 (defconst org-non-link-chars "]\t\n\r<>")
4098 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4099 "shell" "elisp"))
4100 (defvar org-link-types-re nil
4101 "Matches a link that has a url-like prefix like \"http:\"")
4102 (defvar org-link-re-with-space nil
4103 "Matches a link with spaces, optional angular brackets around it.")
4104 (defvar org-link-re-with-space2 nil
4105 "Matches a link with spaces, optional angular brackets around it.")
4106 (defvar org-link-re-with-space3 nil
4107 "Matches a link with spaces, only for internal part in bracket links.")
4108 (defvar org-angle-link-re nil
4109 "Matches link with angular brackets, spaces are allowed.")
4110 (defvar org-plain-link-re nil
4111 "Matches plain link, without spaces.")
4112 (defvar org-bracket-link-regexp nil
4113 "Matches a link in double brackets.")
4114 (defvar org-bracket-link-analytic-regexp nil
4115 "Regular expression used to analyze links.
4116 Here is what the match groups contain after a match:
4117 1: http:
4118 2: http
4119 3: path
4120 4: [desc]
4121 5: desc")
4122 (defvar org-bracket-link-analytic-regexp++ nil
4123 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4124 (defvar org-any-link-re nil
4125 "Regular expression matching any link.")
4127 (defun org-make-link-regexps ()
4128 "Update the link regular expressions.
4129 This should be called after the variable `org-link-types' has changed."
4130 (setq org-link-types-re
4131 (concat
4132 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4133 org-link-re-with-space
4134 (concat
4135 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4136 "\\([^" org-non-link-chars " ]"
4137 "[^" org-non-link-chars "]*"
4138 "[^" org-non-link-chars " ]\\)>?")
4139 org-link-re-with-space2
4140 (concat
4141 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4142 "\\([^" org-non-link-chars " ]"
4143 "[^\t\n\r]*"
4144 "[^" org-non-link-chars " ]\\)>?")
4145 org-link-re-with-space3
4146 (concat
4147 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4148 "\\([^" org-non-link-chars " ]"
4149 "[^\t\n\r]*\\)")
4150 org-angle-link-re
4151 (concat
4152 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4153 "\\([^" org-non-link-chars " ]"
4154 "[^" org-non-link-chars "]*"
4155 "\\)>")
4156 org-plain-link-re
4157 (concat
4158 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4159 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4160 org-bracket-link-regexp
4161 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4162 org-bracket-link-analytic-regexp
4163 (concat
4164 "\\[\\["
4165 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4166 "\\([^]]+\\)"
4167 "\\]"
4168 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4169 "\\]")
4170 org-bracket-link-analytic-regexp++
4171 (concat
4172 "\\[\\["
4173 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4174 "\\([^]]+\\)"
4175 "\\]"
4176 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4177 "\\]")
4178 org-any-link-re
4179 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4180 org-angle-link-re "\\)\\|\\("
4181 org-plain-link-re "\\)")))
4183 (org-make-link-regexps)
4185 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4186 "Regular expression for fast time stamp matching.")
4187 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4188 "Regular expression for fast time stamp matching.")
4189 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4190 "Regular expression matching time strings for analysis.
4191 This one does not require the space after the date, so it can be used
4192 on a string that terminates immediately after the date.")
4193 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4194 "Regular expression matching time strings for analysis.")
4195 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4196 "Regular expression matching time stamps, with groups.")
4197 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4198 "Regular expression matching time stamps (also [..]), with groups.")
4199 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4200 "Regular expression matching a time stamp range.")
4201 (defconst org-tr-regexp-both
4202 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4203 "Regular expression matching a time stamp range.")
4204 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4205 org-ts-regexp "\\)?")
4206 "Regular expression matching a time stamp or time stamp range.")
4207 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4208 org-ts-regexp-both "\\)?")
4209 "Regular expression matching a time stamp or time stamp range.
4210 The time stamps may be either active or inactive.")
4212 (defvar org-emph-face nil)
4214 (defun org-do-emphasis-faces (limit)
4215 "Run through the buffer and add overlays to links."
4216 (let (rtn a)
4217 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4218 (if (not (= (char-after (match-beginning 3))
4219 (char-after (match-beginning 4))))
4220 (progn
4221 (setq rtn t)
4222 (setq a (assoc (match-string 3) org-emphasis-alist))
4223 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4224 'face
4225 (nth 1 a))
4226 (and (nth 4 a)
4227 (org-remove-flyspell-overlays-in
4228 (match-beginning 0) (match-end 0)))
4229 (add-text-properties (match-beginning 2) (match-end 2)
4230 '(font-lock-multiline t))
4231 (when org-hide-emphasis-markers
4232 (add-text-properties (match-end 4) (match-beginning 5)
4233 '(invisible org-link))
4234 (add-text-properties (match-beginning 3) (match-end 3)
4235 '(invisible org-link)))))
4236 (backward-char 1))
4237 rtn))
4239 (defun org-emphasize (&optional char)
4240 "Insert or change an emphasis, i.e. a font like bold or italic.
4241 If there is an active region, change that region to a new emphasis.
4242 If there is no region, just insert the marker characters and position
4243 the cursor between them.
4244 CHAR should be either the marker character, or the first character of the
4245 HTML tag associated with that emphasis. If CHAR is a space, the means
4246 to remove the emphasis of the selected region.
4247 If char is not given (for example in an interactive call) it
4248 will be prompted for."
4249 (interactive)
4250 (let ((eal org-emphasis-alist) e det
4251 (erc org-emphasis-regexp-components)
4252 (prompt "")
4253 (string "") beg end move tag c s)
4254 (if (org-region-active-p)
4255 (setq beg (region-beginning) end (region-end)
4256 string (buffer-substring beg end))
4257 (setq move t))
4259 (while (setq e (pop eal))
4260 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4261 c (aref tag 0))
4262 (push (cons c (string-to-char (car e))) det)
4263 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4264 (substring tag 1)))))
4265 (setq det (nreverse det))
4266 (unless char
4267 (message "%s" (concat "Emphasis marker or tag:" prompt))
4268 (setq char (read-char-exclusive)))
4269 (setq char (or (cdr (assoc char det)) char))
4270 (if (equal char ?\ )
4271 (setq s "" move nil)
4272 (unless (assoc (char-to-string char) org-emphasis-alist)
4273 (error "No such emphasis marker: \"%c\"" char))
4274 (setq s (char-to-string char)))
4275 (while (and (> (length string) 1)
4276 (equal (substring string 0 1) (substring string -1))
4277 (assoc (substring string 0 1) org-emphasis-alist))
4278 (setq string (substring string 1 -1)))
4279 (setq string (concat s string s))
4280 (if beg (delete-region beg end))
4281 (unless (or (bolp)
4282 (string-match (concat "[" (nth 0 erc) "\n]")
4283 (char-to-string (char-before (point)))))
4284 (insert " "))
4285 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4286 (char-to-string (char-after (point))))
4287 (insert " ") (backward-char 1))
4288 (insert string)
4289 (and move (backward-char 1))))
4291 (defconst org-nonsticky-props
4292 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4294 (defsubst org-rear-nonsticky-at (pos)
4295 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4297 (defun org-activate-plain-links (limit)
4298 "Run through the buffer and add overlays to links."
4299 (catch 'exit
4300 (let (f)
4301 (if (re-search-forward org-plain-link-re limit t)
4302 (progn
4303 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4304 (setq f (get-text-property (match-beginning 0) 'face))
4305 (if (or (eq f 'org-tag)
4306 (and (listp f) (memq 'org-tag f)))
4308 (add-text-properties (match-beginning 0) (match-end 0)
4309 (list 'mouse-face 'highlight
4310 'keymap org-mouse-map))
4311 (org-rear-nonsticky-at (match-end 0)))
4312 t)))))
4314 (defun org-activate-code (limit)
4315 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4316 (progn
4317 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4318 (remove-text-properties (match-beginning 0) (match-end 0)
4319 '(display t invisible t intangible t))
4320 t)))
4322 (defun org-fontify-meta-lines-and-blocks (limit)
4323 "Fontify #+ lines and blocks, in the correct ways."
4324 (let ((case-fold-search t))
4325 (if (re-search-forward
4326 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4327 limit t)
4328 (let ((beg (match-beginning 0))
4329 (beg1 (line-beginning-position 2))
4330 (dc1 (downcase (match-string 2)))
4331 (dc3 (downcase (match-string 3)))
4332 end end1 quoting)
4333 (cond
4334 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4335 ;; a single line of backend-specific content
4336 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4337 (remove-text-properties (match-beginning 0) (match-end 0)
4338 '(display t invisible t intangible t))
4339 (add-text-properties (match-beginning 1) (match-end 3)
4340 '(font-lock-fontified t face org-meta-line))
4341 (add-text-properties (match-beginning 6) (match-end 6)
4342 '(font-lock-fontified t face org-block))
4344 ((and (match-end 4) (equal dc3 "begin"))
4345 ;; Truely a block
4346 (setq quoting (member (downcase (match-string 5))
4347 org-protecting-blocks))
4348 (when (re-search-forward
4349 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4350 nil t) ;; on purpose, we look further than LIMIT
4351 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4352 (when quoting
4353 (remove-text-properties beg end
4354 '(display t invisible t intangible t)))
4355 (add-text-properties
4356 beg end
4357 '(font-lock-fontified t font-lock-multiline t))
4358 (add-text-properties beg beg1 '(face org-meta-line))
4359 (add-text-properties end1 end '(face org-meta-line))
4360 (when quoting
4361 (add-text-properties beg1 end1 '(face org-block)))
4363 ((not (member (char-after beg) '(?\ ?\t)))
4364 ;; just any other in-buffer setting, but not indented
4365 (add-text-properties
4366 beg (match-end 0)
4367 '(font-lock-fontified t face org-meta-line))
4369 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:" "tblname:"))
4370 (and (match-end 4) (equal dc3 "attr")))
4371 (add-text-properties
4372 beg (match-end 0)
4373 '(font-lock-fontified t face org-meta-line))
4375 (t nil))))))
4377 (defun org-activate-angle-links (limit)
4378 "Run through the buffer and add overlays to links."
4379 (if (re-search-forward org-angle-link-re limit t)
4380 (progn
4381 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4382 (add-text-properties (match-beginning 0) (match-end 0)
4383 (list 'mouse-face 'highlight
4384 'keymap org-mouse-map))
4385 (org-rear-nonsticky-at (match-end 0))
4386 t)))
4388 (defun org-activate-footnote-links (limit)
4389 "Run through the buffer and add overlays to links."
4390 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4391 limit t)
4392 (progn
4393 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4394 (add-text-properties (match-beginning 2) (match-end 2)
4395 (list 'mouse-face 'highlight
4396 'keymap org-mouse-map
4397 'help-echo
4398 (if (= (point-at-bol) (match-beginning 2))
4399 "Footnote definition"
4400 "Footnote reference")
4402 (org-rear-nonsticky-at (match-end 2))
4403 t)))
4405 (defun org-activate-bracket-links (limit)
4406 "Run through the buffer and add overlays to bracketed links."
4407 (if (re-search-forward org-bracket-link-regexp limit t)
4408 (let* ((help (concat "LINK: "
4409 (org-match-string-no-properties 1)))
4410 ;; FIXME: above we should remove the escapes.
4411 ;; but that requires another match, protecting match data,
4412 ;; a lot of overhead for font-lock.
4413 (ip (org-maybe-intangible
4414 (list 'invisible 'org-link
4415 'keymap org-mouse-map 'mouse-face 'highlight
4416 'font-lock-multiline t 'help-echo help)))
4417 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4418 'font-lock-multiline t 'help-echo help)))
4419 ;; We need to remove the invisible property here. Table narrowing
4420 ;; may have made some of this invisible.
4421 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4422 (remove-text-properties (match-beginning 0) (match-end 0)
4423 '(invisible nil))
4424 (if (match-end 3)
4425 (progn
4426 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4427 (org-rear-nonsticky-at (match-beginning 3))
4428 (add-text-properties (match-beginning 3) (match-end 3) vp)
4429 (org-rear-nonsticky-at (match-end 3))
4430 (add-text-properties (match-end 3) (match-end 0) ip)
4431 (org-rear-nonsticky-at (match-end 0)))
4432 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4433 (org-rear-nonsticky-at (match-beginning 1))
4434 (add-text-properties (match-beginning 1) (match-end 1) vp)
4435 (org-rear-nonsticky-at (match-end 1))
4436 (add-text-properties (match-end 1) (match-end 0) ip)
4437 (org-rear-nonsticky-at (match-end 0)))
4438 t)))
4440 (defun org-activate-dates (limit)
4441 "Run through the buffer and add overlays to dates."
4442 (if (re-search-forward org-tsr-regexp-both limit t)
4443 (progn
4444 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4445 (add-text-properties (match-beginning 0) (match-end 0)
4446 (list 'mouse-face 'highlight
4447 'keymap org-mouse-map))
4448 (org-rear-nonsticky-at (match-end 0))
4449 (when org-display-custom-times
4450 (if (match-end 3)
4451 (org-display-custom-time (match-beginning 3) (match-end 3)))
4452 (org-display-custom-time (match-beginning 1) (match-end 1)))
4453 t)))
4455 (defvar org-target-link-regexp nil
4456 "Regular expression matching radio targets in plain text.")
4457 (make-variable-buffer-local 'org-target-link-regexp)
4458 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4459 "Regular expression matching a link target.")
4460 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4461 "Regular expression matching a radio target.")
4462 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4463 "Regular expression matching any target.")
4465 (defun org-activate-target-links (limit)
4466 "Run through the buffer and add overlays to target matches."
4467 (when org-target-link-regexp
4468 (let ((case-fold-search t))
4469 (if (re-search-forward org-target-link-regexp limit t)
4470 (progn
4471 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4472 (add-text-properties (match-beginning 0) (match-end 0)
4473 (list 'mouse-face 'highlight
4474 'keymap org-mouse-map
4475 'help-echo "Radio target link"
4476 'org-linked-text t))
4477 (org-rear-nonsticky-at (match-end 0))
4478 t)))))
4480 (defun org-update-radio-target-regexp ()
4481 "Find all radio targets in this file and update the regular expression."
4482 (interactive)
4483 (when (memq 'radio org-activate-links)
4484 (setq org-target-link-regexp
4485 (org-make-target-link-regexp (org-all-targets 'radio)))
4486 (org-restart-font-lock)))
4488 (defun org-hide-wide-columns (limit)
4489 (let (s e)
4490 (setq s (text-property-any (point) (or limit (point-max))
4491 'org-cwidth t))
4492 (when s
4493 (setq e (next-single-property-change s 'org-cwidth))
4494 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4495 (goto-char e)
4496 t)))
4498 (defvar org-latex-and-specials-regexp nil
4499 "Regular expression for highlighting export special stuff.")
4500 (defvar org-match-substring-regexp)
4501 (defvar org-match-substring-with-braces-regexp)
4503 ;; This should be with the exporter code, but we also use if for font-locking
4504 (defconst org-export-html-special-string-regexps
4505 '(("\\\\-" . "&shy;")
4506 ("---\\([^-]\\)" . "&mdash;\\1")
4507 ("--\\([^-]\\)" . "&ndash;\\1")
4508 ("\\.\\.\\." . "&hellip;"))
4509 "Regular expressions for special string conversion.")
4512 (defun org-compute-latex-and-specials-regexp ()
4513 "Compute regular expression for stuff treated specially by exporters."
4514 (if (not org-highlight-latex-fragments-and-specials)
4515 (org-set-local 'org-latex-and-specials-regexp nil)
4516 (require 'org-exp)
4517 (let*
4518 ((matchers (plist-get org-format-latex-options :matchers))
4519 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4520 org-latex-regexps)))
4521 (options (org-combine-plists (org-default-export-plist)
4522 (org-infile-export-plist)))
4523 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4524 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4525 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4526 (org-export-html-expand (plist-get options :expand-quoted-html))
4527 (org-export-with-special-strings (plist-get options :special-strings))
4528 (re-sub
4529 (cond
4530 ((equal org-export-with-sub-superscripts '{})
4531 (list org-match-substring-with-braces-regexp))
4532 (org-export-with-sub-superscripts
4533 (list org-match-substring-regexp))
4534 (t nil)))
4535 (re-latex
4536 (if org-export-with-LaTeX-fragments
4537 (mapcar (lambda (x) (nth 1 x)) latexs)))
4538 (re-macros
4539 (if org-export-with-TeX-macros
4540 (list (concat "\\\\"
4541 (regexp-opt
4542 (append (mapcar 'car org-html-entities)
4543 (if (boundp 'org-latex-entities)
4544 (mapcar (lambda (x)
4545 (or (car-safe x) x))
4546 org-latex-entities)
4547 nil))
4548 'words))) ; FIXME
4550 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4551 (re-special (if org-export-with-special-strings
4552 (mapcar (lambda (x) (car x))
4553 org-export-html-special-string-regexps)))
4554 (re-rest
4555 (delq nil
4556 (list
4557 (if org-export-html-expand "@<[^>\n]+>")
4558 ))))
4559 (org-set-local
4560 'org-latex-and-specials-regexp
4561 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4562 re-rest) "\\|")))))
4564 (defun org-do-latex-and-special-faces (limit)
4565 "Run through the buffer and add overlays to links."
4566 (when org-latex-and-specials-regexp
4567 (let (rtn d)
4568 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4569 limit t))
4570 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4571 'face))
4572 '(org-code org-verbatim underline)))
4573 (progn
4574 (setq rtn t
4575 d (cond ((member (char-after (1+ (match-beginning 0)))
4576 '(?_ ?^)) 1)
4577 (t 0)))
4578 (font-lock-prepend-text-property
4579 (+ d (match-beginning 0)) (match-end 0)
4580 'face 'org-latex-and-export-specials)
4581 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4582 '(font-lock-multiline t)))))
4583 rtn)))
4585 (defun org-restart-font-lock ()
4586 "Restart font-lock-mode, to force refontification."
4587 (when (and (boundp 'font-lock-mode) font-lock-mode)
4588 (font-lock-mode -1)
4589 (font-lock-mode 1)))
4591 (defun org-all-targets (&optional radio)
4592 "Return a list of all targets in this file.
4593 With optional argument RADIO, only find radio targets."
4594 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4595 rtn)
4596 (save-excursion
4597 (goto-char (point-min))
4598 (while (re-search-forward re nil t)
4599 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4600 rtn)))
4602 (defun org-make-target-link-regexp (targets)
4603 "Make regular expression matching all strings in TARGETS.
4604 The regular expression finds the targets also if there is a line break
4605 between words."
4606 (and targets
4607 (concat
4608 "\\<\\("
4609 (mapconcat
4610 (lambda (x)
4611 (while (string-match " +" x)
4612 (setq x (replace-match "\\s-+" t t x)))
4614 targets
4615 "\\|")
4616 "\\)\\>")))
4618 (defun org-activate-tags (limit)
4619 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4620 (progn
4621 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4622 (add-text-properties (match-beginning 1) (match-end 1)
4623 (list 'mouse-face 'highlight
4624 'keymap org-mouse-map))
4625 (org-rear-nonsticky-at (match-end 1))
4626 t)))
4628 (defun org-outline-level ()
4629 (save-excursion
4630 (looking-at outline-regexp)
4631 (if (match-beginning 1)
4632 (+ (org-get-string-indentation (match-string 1)) 1000)
4633 (1- (- (match-end 0) (match-beginning 0))))))
4635 (defvar org-font-lock-keywords nil)
4637 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4638 "Regular expression matching a property line.")
4640 (defvar org-font-lock-hook nil
4641 "Functions to be called for special font lock stuff.")
4643 (defun org-font-lock-hook (limit)
4644 (run-hook-with-args 'org-font-lock-hook limit))
4646 (defun org-set-font-lock-defaults ()
4647 (let* ((em org-fontify-emphasized-text)
4648 (lk org-activate-links)
4649 (org-font-lock-extra-keywords
4650 (list
4651 ;; Call the hook
4652 '(org-font-lock-hook)
4653 ;; Headlines
4654 `(,(if org-fontify-whole-heading-line
4655 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4656 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4657 (1 (org-get-level-face 1))
4658 (2 (org-get-level-face 2))
4659 (3 (org-get-level-face 3)))
4660 ;; Table lines
4661 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4662 (1 'org-table t))
4663 ;; Table internals
4664 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4665 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4666 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4667 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4668 ;; Drawers
4669 (list org-drawer-regexp '(0 'org-special-keyword t))
4670 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4671 ;; Properties
4672 (list org-property-re
4673 '(1 'org-special-keyword t)
4674 '(3 'org-property-value t))
4675 ;; Links
4676 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4677 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4678 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4679 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4680 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4681 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4682 (if (memq 'footnote lk) '(org-activate-footnote-links
4683 (2 'org-footnote t)))
4684 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4685 '(org-hide-wide-columns (0 nil append))
4686 ;; TODO lines
4687 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4688 '(1 (org-get-todo-face 1) t))
4689 ;; DONE
4690 (if org-fontify-done-headline
4691 (list (concat "^[*]+ +\\<\\("
4692 (mapconcat 'regexp-quote org-done-keywords "\\|")
4693 "\\)\\(.*\\)")
4694 '(2 'org-headline-done t))
4695 nil)
4696 ;; Priorities
4697 '(org-font-lock-add-priority-faces)
4698 ;; Tags
4699 '(org-font-lock-add-tag-faces)
4700 ;; Special keywords
4701 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4702 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4703 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4704 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4705 ;; Emphasis
4706 (if em
4707 (if (featurep 'xemacs)
4708 '(org-do-emphasis-faces (0 nil append))
4709 '(org-do-emphasis-faces)))
4710 ;; Checkboxes
4711 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4712 2 'org-checkbox prepend)
4713 (if org-provide-checkbox-statistics
4714 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4715 (0 (org-get-checkbox-statistics-face) t)))
4716 ;; Description list items
4717 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4718 2 'bold prepend)
4719 ;; ARCHIVEd headings
4720 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4721 '(1 'org-archived prepend))
4722 ;; Specials
4723 '(org-do-latex-and-special-faces)
4724 ;; Code
4725 '(org-activate-code (1 'org-code t))
4726 ;; COMMENT
4727 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4728 "\\|" org-quote-string "\\)\\>")
4729 '(1 'org-special-keyword t))
4730 '("^#.*" (0 'font-lock-comment-face t))
4731 ;; Blocks and meta lines
4732 '(org-fontify-meta-lines-and-blocks)
4734 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4735 ;; Now set the full font-lock-keywords
4736 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4737 (org-set-local 'font-lock-defaults
4738 '(org-font-lock-keywords t nil nil backward-paragraph))
4739 (kill-local-variable 'font-lock-keywords) nil))
4741 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4742 "Fontify string S like in Org-mode"
4743 (with-temp-buffer
4744 (insert s)
4745 (let ((org-odd-levels-only odd-levels))
4746 (org-mode)
4747 (font-lock-fontify-buffer)
4748 (buffer-string))))
4750 (defvar org-m nil)
4751 (defvar org-l nil)
4752 (defvar org-f nil)
4753 (defun org-get-level-face (n)
4754 "Get the right face for match N in font-lock matching of headlines."
4755 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4756 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4757 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4758 (cond
4759 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4760 ((eq n 2) org-f)
4761 (t (if org-level-color-stars-only nil org-f))))
4763 (defun org-get-todo-face (kwd)
4764 "Get the right face for a TODO keyword KWD.
4765 If KWD is a number, get the corresponding match group."
4766 (if (numberp kwd) (setq kwd (match-string kwd)))
4767 (or (cdr (assoc kwd org-todo-keyword-faces))
4768 (and (member kwd org-done-keywords) 'org-done)
4769 'org-todo))
4771 (defun org-font-lock-add-tag-faces (limit)
4772 "Add the special tag faces."
4773 (when (and org-tag-faces org-tags-special-faces-re)
4774 (while (re-search-forward org-tags-special-faces-re limit t)
4775 (add-text-properties (match-beginning 1) (match-end 1)
4776 (list 'face (org-get-tag-face 1)
4777 'font-lock-fontified t))
4778 (backward-char 1))))
4780 (defun org-font-lock-add-priority-faces (limit)
4781 "Add the special priority faces."
4782 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4783 (add-text-properties
4784 (match-beginning 0) (match-end 0)
4785 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4786 org-priority-faces))
4787 'org-special-keyword)
4788 'font-lock-fontified t))))
4790 (defun org-get-tag-face (kwd)
4791 "Get the right face for a TODO keyword KWD.
4792 If KWD is a number, get the corresponding match group."
4793 (if (numberp kwd) (setq kwd (match-string kwd)))
4794 (or (cdr (assoc kwd org-tag-faces))
4795 'org-tag))
4797 (defun org-unfontify-region (beg end &optional maybe_loudly)
4798 "Remove fontification and activation overlays from links."
4799 (font-lock-default-unfontify-region beg end)
4800 (let* ((buffer-undo-list t)
4801 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4802 (inhibit-modification-hooks t)
4803 deactivate-mark buffer-file-name buffer-file-truename)
4804 (remove-text-properties beg end
4805 '(mouse-face t keymap t org-linked-text t
4806 invisible t intangible t
4807 line-prefix t wrap-prefix t
4808 org-no-flyspell t))))
4810 ;;;; Visibility cycling, including org-goto and indirect buffer
4812 ;;; Cycling
4814 (defvar org-cycle-global-status nil)
4815 (make-variable-buffer-local 'org-cycle-global-status)
4816 (defvar org-cycle-subtree-status nil)
4817 (make-variable-buffer-local 'org-cycle-subtree-status)
4819 ;;;###autoload
4821 (defvar org-inlinetask-min-level)
4823 (defun org-cycle (&optional arg)
4824 "TAB-action and visibility cycling for Org-mode.
4826 This is the command invoked in Org-mode by the TAB key. Its main purpose
4827 is outine visibility cycling, but it also invokes other actions
4828 in special contexts.
4830 - When this function is called with a prefix argument, rotate the entire
4831 buffer through 3 states (global cycling)
4832 1. OVERVIEW: Show only top-level headlines.
4833 2. CONTENTS: Show all headlines of all levels, but no body text.
4834 3. SHOW ALL: Show everything.
4835 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4836 determined by the variable `org-startup-folded', and by any VISIBILITY
4837 properties in the buffer.
4838 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4839 including any drawers.
4841 - When inside a table, re-align the table and move to the next field.
4843 - When point is at the beginning of a headline, rotate the subtree started
4844 by this line through 3 different states (local cycling)
4845 1. FOLDED: Only the main headline is shown.
4846 2. CHILDREN: The main headline and the direct children are shown.
4847 From this state, you can move to one of the children
4848 and zoom in further.
4849 3. SUBTREE: Show the entire subtree, including body text.
4850 If there is no subtree, switch directly from CHILDREN to FOLDED.
4852 - When there is a numeric prefix, go up to a heading with level ARG, do
4853 a `show-subtree' and return to the previous cursor position. If ARG
4854 is negative, go up that many levels.
4856 - When point is not at the beginning of a headline, execute the global
4857 binding for TAB, which is re-indenting the line. See the option
4858 `org-cycle-emulate-tab' for details.
4860 - Special case: if point is at the beginning of the buffer and there is
4861 no headline in line 1, this function will act as if called with prefix arg.
4862 But only if also the variable `org-cycle-global-at-bob' is t."
4863 (interactive "P")
4864 (org-load-modules-maybe)
4865 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4866 (let* ((limit-level
4867 (or org-cycle-max-level
4868 (and (boundp 'org-inlinetask-min-level)
4869 org-inlinetask-min-level
4870 (1- org-inlinetask-min-level))))
4871 (nstars (and limit-level
4872 (if org-odd-levels-only
4873 (and limit-level (1- (* limit-level 2)))
4874 limit-level)))
4875 (outline-regexp
4876 (cond
4877 ((not (org-mode-p)) outline-regexp)
4878 ((or (eq org-cycle-include-plain-lists 'integrate)
4879 (and org-cycle-include-plain-lists (org-at-item-p)))
4880 (concat "\\(?:\\*"
4881 (if nstars (format "\\{1,%d\\}" nstars) "+")
4882 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4883 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4884 (bob-special (and org-cycle-global-at-bob (bobp)
4885 (not (looking-at outline-regexp))))
4886 (org-cycle-hook
4887 (if bob-special
4888 (delq 'org-optimize-window-after-visibility-change
4889 (copy-sequence org-cycle-hook))
4890 org-cycle-hook))
4891 (pos (point)))
4893 (if (or bob-special (equal arg '(4)))
4894 ;; special case: use global cycling
4895 (setq arg t))
4897 (cond
4899 ((equal arg '(16))
4900 (org-set-startup-visibility)
4901 (message "Startup visibility, plus VISIBILITY properties"))
4903 ((equal arg '(64))
4904 (show-all)
4905 (message "Entire buffer visible, including drawers"))
4907 ((org-at-table-p 'any)
4908 ;; Enter the table or move to the next field in the table
4909 (or (org-table-recognize-table.el)
4910 (progn
4911 (if arg (org-table-edit-field t)
4912 (org-table-justify-field-maybe)
4913 (call-interactively 'org-table-next-field)))))
4915 ((run-hook-with-args-until-success
4916 'org-tab-after-check-for-table-hook))
4918 ((eq arg t) ;; Global cycling
4919 (org-cycle-internal-global))
4921 ((and org-drawers org-drawer-regexp
4922 (save-excursion
4923 (beginning-of-line 1)
4924 (looking-at org-drawer-regexp)))
4925 ;; Toggle block visibility
4926 (org-flag-drawer
4927 (not (get-char-property (match-end 0) 'invisible))))
4929 ((integerp arg)
4930 ;; Show-subtree, ARG levels up from here.
4931 (save-excursion
4932 (org-back-to-heading)
4933 (outline-up-heading (if (< arg 0) (- arg)
4934 (- (funcall outline-level) arg)))
4935 (org-show-subtree)))
4937 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4938 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4940 (org-cycle-internal-local))
4942 ;; TAB emulation and template completion
4943 (buffer-read-only (org-back-to-heading))
4945 ((run-hook-with-args-until-success
4946 'org-tab-after-check-for-cycling-hook))
4948 ((org-try-structure-completion))
4950 ((org-try-cdlatex-tab))
4952 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4953 (or (not (bolp))
4954 (not (looking-at outline-regexp))))
4955 (call-interactively (global-key-binding "\t")))
4957 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4958 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4959 (or (and (eq org-cycle-emulate-tab 'white)
4960 (= (match-end 0) (point-at-eol)))
4961 (and (eq org-cycle-emulate-tab 'whitestart)
4962 (>= (match-end 0) pos))))
4964 (eq org-cycle-emulate-tab t))
4965 (call-interactively (global-key-binding "\t")))
4967 (t (save-excursion
4968 (org-back-to-heading)
4969 (org-cycle)))))))
4971 (defun org-cycle-internal-global ()
4972 "Do the global cycling action."
4973 (cond
4974 ((and (eq last-command this-command)
4975 (eq org-cycle-global-status 'overview))
4976 ;; We just created the overview - now do table of contents
4977 ;; This can be slow in very large buffers, so indicate action
4978 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4979 (message "CONTENTS...")
4980 (org-content)
4981 (message "CONTENTS...done")
4982 (setq org-cycle-global-status 'contents)
4983 (run-hook-with-args 'org-cycle-hook 'contents))
4985 ((and (eq last-command this-command)
4986 (eq org-cycle-global-status 'contents))
4987 ;; We just showed the table of contents - now show everything
4988 (run-hook-with-args 'org-pre-cycle-hook 'all)
4989 (show-all)
4990 (message "SHOW ALL")
4991 (setq org-cycle-global-status 'all)
4992 (run-hook-with-args 'org-cycle-hook 'all))
4995 ;; Default action: go to overview
4996 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4997 (org-overview)
4998 (message "OVERVIEW")
4999 (setq org-cycle-global-status 'overview)
5000 (run-hook-with-args 'org-cycle-hook 'overview))))
5002 (defun org-cycle-internal-local ()
5003 "Do the local cycling action."
5004 (org-back-to-heading)
5005 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5006 ;; First, some boundaries
5007 (save-excursion
5008 (org-back-to-heading)
5009 (setq level (funcall outline-level))
5010 (save-excursion
5011 (beginning-of-line 2)
5012 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5013 ; XEmacs does not have `next-single-char-property-change'
5014 ; I'm not sure about Emacs 21.
5015 (while (and (not (eobp)) ;; this is like `next-line'
5016 (get-char-property (1- (point)) 'invisible))
5017 (beginning-of-line 2))
5018 (while (and (not (eobp)) ;; this is like `next-line'
5019 (get-char-property (1- (point)) 'invisible))
5020 (goto-char (next-single-char-property-change (point) 'invisible))
5021 ;;;??? (or (bolp) (beginning-of-line 2))))
5022 (and (eolp) (beginning-of-line 2))))
5023 (setq eol (point)))
5024 (outline-end-of-heading) (setq eoh (point))
5025 (save-excursion
5026 (outline-next-heading)
5027 (setq has-children (and (org-at-heading-p t)
5028 (> (funcall outline-level) level))))
5029 (org-end-of-subtree t)
5030 (unless (eobp)
5031 (skip-chars-forward " \t\n")
5032 (beginning-of-line 1) ; in case this is an item
5034 (setq eos (if (eobp) (point) (1- (point)))))
5035 ;; Find out what to do next and set `this-command'
5036 (cond
5037 ((= eos eoh)
5038 ;; Nothing is hidden behind this heading
5039 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5040 (message "EMPTY ENTRY")
5041 (setq org-cycle-subtree-status nil)
5042 (save-excursion
5043 (goto-char eos)
5044 (outline-next-heading)
5045 (if (org-invisible-p) (org-flag-heading nil))))
5046 ((and (or (>= eol eos)
5047 (not (string-match "\\S-" (buffer-substring eol eos))))
5048 (or has-children
5049 (not (setq children-skipped
5050 org-cycle-skip-children-state-if-no-children))))
5051 ;; Entire subtree is hidden in one line: children view
5052 (run-hook-with-args 'org-pre-cycle-hook 'children)
5053 (org-show-entry)
5054 (show-children)
5055 (message "CHILDREN")
5056 (save-excursion
5057 (goto-char eos)
5058 (outline-next-heading)
5059 (if (org-invisible-p) (org-flag-heading nil)))
5060 (setq org-cycle-subtree-status 'children)
5061 (run-hook-with-args 'org-cycle-hook 'children))
5062 ((or children-skipped
5063 (and (eq last-command this-command)
5064 (eq org-cycle-subtree-status 'children)))
5065 ;; We just showed the children, or no children are there,
5066 ;; now show everything.
5067 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5068 (org-show-subtree)
5069 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5070 (setq org-cycle-subtree-status 'subtree)
5071 (run-hook-with-args 'org-cycle-hook 'subtree))
5073 ;; Default action: hide the subtree.
5074 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5075 (hide-subtree)
5076 (message "FOLDED")
5077 (setq org-cycle-subtree-status 'folded)
5078 (run-hook-with-args 'org-cycle-hook 'folded)))))
5080 ;;;###autoload
5081 (defun org-global-cycle (&optional arg)
5082 "Cycle the global visibility. For details see `org-cycle'.
5083 With C-u prefix arg, switch to startup visibility.
5084 With a numeric prefix, show all headlines up to that level."
5085 (interactive "P")
5086 (let ((org-cycle-include-plain-lists
5087 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5088 (cond
5089 ((integerp arg)
5090 (show-all)
5091 (hide-sublevels arg)
5092 (setq org-cycle-global-status 'contents))
5093 ((equal arg '(4))
5094 (org-set-startup-visibility)
5095 (message "Startup visibility, plus VISIBILITY properties."))
5097 (org-cycle '(4))))))
5099 (defun org-set-startup-visibility ()
5100 "Set the visibility required by startup options and properties."
5101 (cond
5102 ((eq org-startup-folded t)
5103 (org-cycle '(4)))
5104 ((eq org-startup-folded 'content)
5105 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5106 (org-cycle '(4)) (org-cycle '(4)))))
5107 (if org-hide-block-startup (org-hide-block-all))
5108 (org-set-visibility-according-to-property 'no-cleanup)
5109 (org-cycle-hide-archived-subtrees 'all)
5110 (org-cycle-hide-drawers 'all)
5111 (org-cycle-show-empty-lines 'all))
5113 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5114 "Switch subtree visibilities according to :VISIBILITY: property."
5115 (interactive)
5116 (let (org-show-entry-below state)
5117 (save-excursion
5118 (goto-char (point-min))
5119 (while (re-search-forward
5120 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5121 nil t)
5122 (setq state (match-string 1))
5123 (save-excursion
5124 (org-back-to-heading t)
5125 (hide-subtree)
5126 (org-reveal)
5127 (cond
5128 ((equal state '("fold" "folded"))
5129 (hide-subtree))
5130 ((equal state "children")
5131 (org-show-hidden-entry)
5132 (show-children))
5133 ((equal state "content")
5134 (save-excursion
5135 (save-restriction
5136 (org-narrow-to-subtree)
5137 (org-content))))
5138 ((member state '("all" "showall"))
5139 (show-subtree)))))
5140 (unless no-cleanup
5141 (org-cycle-hide-archived-subtrees 'all)
5142 (org-cycle-hide-drawers 'all)
5143 (org-cycle-show-empty-lines 'all)))))
5145 (defun org-overview ()
5146 "Switch to overview mode, showing only top-level headlines.
5147 Really, this shows all headlines with level equal or greater than the level
5148 of the first headline in the buffer. This is important, because if the
5149 first headline is not level one, then (hide-sublevels 1) gives confusing
5150 results."
5151 (interactive)
5152 (let ((level (save-excursion
5153 (goto-char (point-min))
5154 (if (re-search-forward (concat "^" outline-regexp) nil t)
5155 (progn
5156 (goto-char (match-beginning 0))
5157 (funcall outline-level))))))
5158 (and level (hide-sublevels level))))
5160 (defun org-content (&optional arg)
5161 "Show all headlines in the buffer, like a table of contents.
5162 With numerical argument N, show content up to level N."
5163 (interactive "P")
5164 (save-excursion
5165 ;; Visit all headings and show their offspring
5166 (and (integerp arg) (org-overview))
5167 (goto-char (point-max))
5168 (catch 'exit
5169 (while (and (progn (condition-case nil
5170 (outline-previous-visible-heading 1)
5171 (error (goto-char (point-min))))
5173 (looking-at outline-regexp))
5174 (if (integerp arg)
5175 (show-children (1- arg))
5176 (show-branches))
5177 (if (bobp) (throw 'exit nil))))))
5180 (defun org-optimize-window-after-visibility-change (state)
5181 "Adjust the window after a change in outline visibility.
5182 This function is the default value of the hook `org-cycle-hook'."
5183 (when (get-buffer-window (current-buffer))
5184 (cond
5185 ((eq state 'content) nil)
5186 ((eq state 'all) nil)
5187 ((eq state 'folded) nil)
5188 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5189 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5191 ;; FIXME: no longer in use
5192 (defun org-compact-display-after-subtree-move ()
5193 "Show a compacter version of the tree of the entry's parent."
5194 (save-excursion
5195 (if (org-up-heading-safe)
5196 (progn
5197 (hide-subtree)
5198 (show-entry)
5199 (show-children)
5200 (org-cycle-show-empty-lines 'children)
5201 (org-cycle-hide-drawers 'children))
5202 (org-overview))))
5204 (defun org-remove-empty-overlays-at (pos)
5205 "Remove outline overlays that do not contain non-white stuff."
5206 (mapc
5207 (lambda (o)
5208 (and (eq 'outline (org-overlay-get o 'invisible))
5209 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5210 (org-overlay-end o))))
5211 (org-delete-overlay o)))
5212 (org-overlays-at pos)))
5214 (defun org-clean-visibility-after-subtree-move ()
5215 "Fix visibility issues after moving a subtree."
5216 ;; First, find a reasonable region to look at:
5217 ;; Start two siblings above, end three below
5218 (let* ((beg (save-excursion
5219 (and (org-get-last-sibling)
5220 (org-get-last-sibling))
5221 (point)))
5222 (end (save-excursion
5223 (and (org-get-next-sibling)
5224 (org-get-next-sibling)
5225 (org-get-next-sibling))
5226 (if (org-at-heading-p)
5227 (point-at-eol)
5228 (point))))
5229 (level (looking-at "\\*+"))
5230 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5231 (save-excursion
5232 (save-restriction
5233 (narrow-to-region beg end)
5234 (when re
5235 ;; Properly fold already folded siblings
5236 (goto-char (point-min))
5237 (while (re-search-forward re nil t)
5238 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5239 (hide-entry))))
5240 (org-cycle-show-empty-lines 'overview)
5241 (org-cycle-hide-drawers 'overview)))))
5243 (defun org-cycle-show-empty-lines (state)
5244 "Show empty lines above all visible headlines.
5245 The region to be covered depends on STATE when called through
5246 `org-cycle-hook'. Lisp program can use t for STATE to get the
5247 entire buffer covered. Note that an empty line is only shown if there
5248 are at least `org-cycle-separator-lines' empty lines before the headline."
5249 (when (not (= org-cycle-separator-lines 0))
5250 (save-excursion
5251 (let* ((n (abs org-cycle-separator-lines))
5252 (re (cond
5253 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5254 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5255 (t (let ((ns (number-to-string (- n 2))))
5256 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5257 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5258 beg end b e)
5259 (cond
5260 ((memq state '(overview contents t))
5261 (setq beg (point-min) end (point-max)))
5262 ((memq state '(children folded))
5263 (setq beg (point) end (progn (org-end-of-subtree t t)
5264 (beginning-of-line 2)
5265 (point)))))
5266 (when beg
5267 (goto-char beg)
5268 (while (re-search-forward re end t)
5269 (unless (get-char-property (match-end 1) 'invisible)
5270 (setq e (match-end 1))
5271 (if (< org-cycle-separator-lines 0)
5272 (setq b (save-excursion
5273 (goto-char (match-beginning 0))
5274 (org-back-over-empty-lines)
5275 (if (save-excursion
5276 (goto-char (max (point-min) (1- (point))))
5277 (org-on-heading-p))
5278 (1- (point))
5279 (point))))
5280 (setq b (match-beginning 1)))
5281 (outline-flag-region b e nil)))))))
5282 ;; Never hide empty lines at the end of the file.
5283 (save-excursion
5284 (goto-char (point-max))
5285 (outline-previous-heading)
5286 (outline-end-of-heading)
5287 (if (and (looking-at "[ \t\n]+")
5288 (= (match-end 0) (point-max)))
5289 (outline-flag-region (point) (match-end 0) nil))))
5291 (defun org-show-empty-lines-in-parent ()
5292 "Move to the parent and re-show empty lines before visible headlines."
5293 (save-excursion
5294 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5295 (org-cycle-show-empty-lines context))))
5297 (defun org-cycle-hide-drawers (state)
5298 "Re-hide all drawers after a visibility state change."
5299 (when (and (org-mode-p)
5300 (not (memq state '(overview folded contents))))
5301 (save-excursion
5302 (let* ((globalp (memq state '(contents all)))
5303 (beg (if globalp (point-min) (point)))
5304 (end (if globalp (point-max)
5305 (if (eq state 'children)
5306 (save-excursion (outline-next-heading) (point))
5307 (org-end-of-subtree t)))))
5308 (goto-char beg)
5309 (while (re-search-forward org-drawer-regexp end t)
5310 (org-flag-drawer t))))))
5312 (defun org-flag-drawer (flag)
5313 (save-excursion
5314 (beginning-of-line 1)
5315 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5316 (let ((b (match-end 0))
5317 (outline-regexp org-outline-regexp))
5318 (if (re-search-forward
5319 "^[ \t]*:END:"
5320 (save-excursion (outline-next-heading) (point)) t)
5321 (outline-flag-region b (point-at-eol) flag)
5322 (error ":END: line missing at position %s" b))))))
5324 (defun org-subtree-end-visible-p ()
5325 "Is the end of the current subtree visible?"
5326 (pos-visible-in-window-p
5327 (save-excursion (org-end-of-subtree t) (point))))
5329 (defun org-first-headline-recenter (&optional N)
5330 "Move cursor to the first headline and recenter the headline.
5331 Optional argument N means, put the headline into the Nth line of the window."
5332 (goto-char (point-min))
5333 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5334 (beginning-of-line)
5335 (recenter (prefix-numeric-value N))))
5337 ;;; Folding of blocks
5339 (defconst org-block-regexp
5341 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5342 "Regular expression for hiding blocks.")
5344 (defvar org-hide-block-overlays nil
5345 "Overays hiding blocks.")
5346 (make-variable-buffer-local 'org-hide-block-overlays)
5348 (defun org-block-map (function &optional start end)
5349 "Call func at the head of all source blocks in the current
5350 buffer. Optional arguments START and END can be used to limit
5351 the range."
5352 (let ((start (or start (point-min)))
5353 (end (or end (point-max))))
5354 (save-excursion
5355 (goto-char start)
5356 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5357 (save-excursion
5358 (save-match-data
5359 (goto-char (match-beginning 0))
5360 (funcall function)))))))
5362 (defun org-hide-block-toggle-all ()
5363 "Toggle the visibility of all blocks in the current buffer."
5364 (org-block-map #'org-hide-block-toggle))
5366 (defun org-hide-block-all ()
5367 "Fold all blocks in the current buffer."
5368 (interactive)
5369 (org-show-block-all)
5370 (org-block-map #'org-hide-block-toggle-maybe))
5372 (defun org-show-block-all ()
5373 "Unfold all blocks in the current buffer."
5374 (mapc 'org-delete-overlay org-hide-block-overlays)
5375 (setq org-hide-block-overlays nil))
5377 (defun org-hide-block-toggle-maybe ()
5378 "Toggle visibility of block at point."
5379 (interactive)
5380 (let ((case-fold-search t))
5381 (if (save-excursion
5382 (beginning-of-line 1)
5383 (looking-at org-block-regexp))
5384 (progn (org-hide-block-toggle)
5385 t) ;; to signal that we took action
5386 nil))) ;; to signal that we did not
5388 (defun org-hide-block-toggle (&optional force)
5389 "Toggle the visibility of the current block."
5390 (interactive)
5391 (save-excursion
5392 (beginning-of-line)
5393 (if (re-search-forward org-block-regexp nil t)
5394 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5395 (end (match-end 0)) ;; end of entire body
5397 (if (memq t (mapcar (lambda (overlay)
5398 (eq (org-overlay-get overlay 'invisible)
5399 'org-hide-block))
5400 (org-overlays-at start)))
5401 (if (or (not force) (eq force 'off))
5402 (mapc (lambda (ov)
5403 (when (member ov org-hide-block-overlays)
5404 (setq org-hide-block-overlays
5405 (delq ov org-hide-block-overlays)))
5406 (when (eq (org-overlay-get ov 'invisible)
5407 'org-hide-block)
5408 (org-delete-overlay ov)))
5409 (org-overlays-at start)))
5410 (setq ov (org-make-overlay start end))
5411 (org-overlay-put ov 'invisible 'org-hide-block)
5412 ;; make the block accessible to isearch
5413 (org-overlay-put
5414 ov 'isearch-open-invisible
5415 (lambda (ov)
5416 (when (member ov org-hide-block-overlays)
5417 (setq org-hide-block-overlays
5418 (delq ov org-hide-block-overlays)))
5419 (when (eq (org-overlay-get ov 'invisible)
5420 'org-hide-block)
5421 (org-delete-overlay ov))))
5422 (push ov org-hide-block-overlays)))
5423 (error "Not looking at a source block"))))
5425 ;; org-tab-after-check-for-cycling-hook
5426 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5427 ;; Remove overlays when changing major mode
5428 (add-hook 'org-mode-hook
5429 (lambda () (org-add-hook 'change-major-mode-hook
5430 'org-show-block-all 'append 'local)))
5432 ;;; Org-goto
5434 (defvar org-goto-window-configuration nil)
5435 (defvar org-goto-marker nil)
5436 (defvar org-goto-map
5437 (let ((map (make-sparse-keymap)))
5438 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5439 (while (setq cmd (pop cmds))
5440 (substitute-key-definition cmd cmd map global-map)))
5441 (suppress-keymap map)
5442 (org-defkey map "\C-m" 'org-goto-ret)
5443 (org-defkey map [(return)] 'org-goto-ret)
5444 (org-defkey map [(left)] 'org-goto-left)
5445 (org-defkey map [(right)] 'org-goto-right)
5446 (org-defkey map [(control ?g)] 'org-goto-quit)
5447 (org-defkey map "\C-i" 'org-cycle)
5448 (org-defkey map [(tab)] 'org-cycle)
5449 (org-defkey map [(down)] 'outline-next-visible-heading)
5450 (org-defkey map [(up)] 'outline-previous-visible-heading)
5451 (if org-goto-auto-isearch
5452 (if (fboundp 'define-key-after)
5453 (define-key-after map [t] 'org-goto-local-auto-isearch)
5454 nil)
5455 (org-defkey map "q" 'org-goto-quit)
5456 (org-defkey map "n" 'outline-next-visible-heading)
5457 (org-defkey map "p" 'outline-previous-visible-heading)
5458 (org-defkey map "f" 'outline-forward-same-level)
5459 (org-defkey map "b" 'outline-backward-same-level)
5460 (org-defkey map "u" 'outline-up-heading))
5461 (org-defkey map "/" 'org-occur)
5462 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5463 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5464 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5465 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5466 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5467 map))
5469 (defconst org-goto-help
5470 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5471 RET=jump to location [Q]uit and return to previous location
5472 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5474 (defvar org-goto-start-pos) ; dynamically scoped parameter
5476 ;; FIXME: Docstring doe not mention both interfaces
5477 (defun org-goto (&optional alternative-interface)
5478 "Look up a different location in the current file, keeping current visibility.
5480 When you want look-up or go to a different location in a document, the
5481 fastest way is often to fold the entire buffer and then dive into the tree.
5482 This method has the disadvantage, that the previous location will be folded,
5483 which may not be what you want.
5485 This command works around this by showing a copy of the current buffer
5486 in an indirect buffer, in overview mode. You can dive into the tree in
5487 that copy, use org-occur and incremental search to find a location.
5488 When pressing RET or `Q', the command returns to the original buffer in
5489 which the visibility is still unchanged. After RET is will also jump to
5490 the location selected in the indirect buffer and expose the
5491 the headline hierarchy above."
5492 (interactive "P")
5493 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5494 (org-refile-use-outline-path t)
5495 (org-refile-target-verify-function nil)
5496 (interface
5497 (if (not alternative-interface)
5498 org-goto-interface
5499 (if (eq org-goto-interface 'outline)
5500 'outline-path-completion
5501 'outline)))
5502 (org-goto-start-pos (point))
5503 (selected-point
5504 (if (eq interface 'outline)
5505 (car (org-get-location (current-buffer) org-goto-help))
5506 (nth 3 (org-refile-get-location "Goto: ")))))
5507 (if selected-point
5508 (progn
5509 (org-mark-ring-push org-goto-start-pos)
5510 (goto-char selected-point)
5511 (if (or (org-invisible-p) (org-invisible-p2))
5512 (org-show-context 'org-goto)))
5513 (message "Quit"))))
5515 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5516 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5517 (defvar org-goto-local-auto-isearch-map) ; defined below
5519 (defun org-get-location (buf help)
5520 "Let the user select a location in the Org-mode buffer BUF.
5521 This function uses a recursive edit. It returns the selected position
5522 or nil."
5523 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5524 (isearch-hide-immediately nil)
5525 (isearch-search-fun-function
5526 (lambda () 'org-goto-local-search-headings))
5527 (org-goto-selected-point org-goto-exit-command))
5528 (save-excursion
5529 (save-window-excursion
5530 (delete-other-windows)
5531 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5532 (switch-to-buffer
5533 (condition-case nil
5534 (make-indirect-buffer (current-buffer) "*org-goto*")
5535 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5536 (with-output-to-temp-buffer "*Help*"
5537 (princ help))
5538 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5539 (setq buffer-read-only nil)
5540 (let ((org-startup-truncated t)
5541 (org-startup-folded nil)
5542 (org-startup-align-all-tables nil))
5543 (org-mode)
5544 (org-overview))
5545 (setq buffer-read-only t)
5546 (if (and (boundp 'org-goto-start-pos)
5547 (integer-or-marker-p org-goto-start-pos))
5548 (let ((org-show-hierarchy-above t)
5549 (org-show-siblings t)
5550 (org-show-following-heading t))
5551 (goto-char org-goto-start-pos)
5552 (and (org-invisible-p) (org-show-context)))
5553 (goto-char (point-min)))
5554 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5555 (message "Select location and press RET")
5556 (use-local-map org-goto-map)
5557 (recursive-edit)
5559 (kill-buffer "*org-goto*")
5560 (cons org-goto-selected-point org-goto-exit-command)))
5562 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5563 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5564 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5565 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5567 (defun org-goto-local-search-headings (string bound noerror)
5568 "Search and make sure that any matches are in headlines."
5569 (catch 'return
5570 (while (if isearch-forward
5571 (search-forward string bound noerror)
5572 (search-backward string bound noerror))
5573 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5574 (and (member :headline context)
5575 (not (member :tags context))))
5576 (throw 'return (point))))))
5578 (defun org-goto-local-auto-isearch ()
5579 "Start isearch."
5580 (interactive)
5581 (goto-char (point-min))
5582 (let ((keys (this-command-keys)))
5583 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5584 (isearch-mode t)
5585 (isearch-process-search-char (string-to-char keys)))))
5587 (defun org-goto-ret (&optional arg)
5588 "Finish `org-goto' by going to the new location."
5589 (interactive "P")
5590 (setq org-goto-selected-point (point)
5591 org-goto-exit-command 'return)
5592 (throw 'exit nil))
5594 (defun org-goto-left ()
5595 "Finish `org-goto' by going to the new location."
5596 (interactive)
5597 (if (org-on-heading-p)
5598 (progn
5599 (beginning-of-line 1)
5600 (setq org-goto-selected-point (point)
5601 org-goto-exit-command 'left)
5602 (throw 'exit nil))
5603 (error "Not on a heading")))
5605 (defun org-goto-right ()
5606 "Finish `org-goto' by going to the new location."
5607 (interactive)
5608 (if (org-on-heading-p)
5609 (progn
5610 (setq org-goto-selected-point (point)
5611 org-goto-exit-command 'right)
5612 (throw 'exit nil))
5613 (error "Not on a heading")))
5615 (defun org-goto-quit ()
5616 "Finish `org-goto' without cursor motion."
5617 (interactive)
5618 (setq org-goto-selected-point nil)
5619 (setq org-goto-exit-command 'quit)
5620 (throw 'exit nil))
5622 ;;; Indirect buffer display of subtrees
5624 (defvar org-indirect-dedicated-frame nil
5625 "This is the frame being used for indirect tree display.")
5626 (defvar org-last-indirect-buffer nil)
5628 (defun org-tree-to-indirect-buffer (&optional arg)
5629 "Create indirect buffer and narrow it to current subtree.
5630 With numerical prefix ARG, go up to this level and then take that tree.
5631 If ARG is negative, go up that many levels.
5632 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5633 indirect buffer previously made with this command, to avoid proliferation of
5634 indirect buffers. However, when you call the command with a `C-u' prefix, or
5635 when `org-indirect-buffer-display' is `new-frame', the last buffer
5636 is kept so that you can work with several indirect buffers at the same time.
5637 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5638 requests that a new frame be made for the new buffer, so that the dedicated
5639 frame is not changed."
5640 (interactive "P")
5641 (let ((cbuf (current-buffer))
5642 (cwin (selected-window))
5643 (pos (point))
5644 beg end level heading ibuf)
5645 (save-excursion
5646 (org-back-to-heading t)
5647 (when (numberp arg)
5648 (setq level (org-outline-level))
5649 (if (< arg 0) (setq arg (+ level arg)))
5650 (while (> (setq level (org-outline-level)) arg)
5651 (outline-up-heading 1 t)))
5652 (setq beg (point)
5653 heading (org-get-heading))
5654 (org-end-of-subtree t) (setq end (point)))
5655 (if (and (buffer-live-p org-last-indirect-buffer)
5656 (not (eq org-indirect-buffer-display 'new-frame))
5657 (not arg))
5658 (kill-buffer org-last-indirect-buffer))
5659 (setq ibuf (org-get-indirect-buffer cbuf)
5660 org-last-indirect-buffer ibuf)
5661 (cond
5662 ((or (eq org-indirect-buffer-display 'new-frame)
5663 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5664 (select-frame (make-frame))
5665 (delete-other-windows)
5666 (switch-to-buffer ibuf)
5667 (org-set-frame-title heading))
5668 ((eq org-indirect-buffer-display 'dedicated-frame)
5669 (raise-frame
5670 (select-frame (or (and org-indirect-dedicated-frame
5671 (frame-live-p org-indirect-dedicated-frame)
5672 org-indirect-dedicated-frame)
5673 (setq org-indirect-dedicated-frame (make-frame)))))
5674 (delete-other-windows)
5675 (switch-to-buffer ibuf)
5676 (org-set-frame-title (concat "Indirect: " heading)))
5677 ((eq org-indirect-buffer-display 'current-window)
5678 (switch-to-buffer ibuf))
5679 ((eq org-indirect-buffer-display 'other-window)
5680 (pop-to-buffer ibuf))
5681 (t (error "Invalid value.")))
5682 (if (featurep 'xemacs)
5683 (save-excursion (org-mode) (turn-on-font-lock)))
5684 (narrow-to-region beg end)
5685 (show-all)
5686 (goto-char pos)
5687 (and (window-live-p cwin) (select-window cwin))))
5689 (defun org-get-indirect-buffer (&optional buffer)
5690 (setq buffer (or buffer (current-buffer)))
5691 (let ((n 1) (base (buffer-name buffer)) bname)
5692 (while (buffer-live-p
5693 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5694 (setq n (1+ n)))
5695 (condition-case nil
5696 (make-indirect-buffer buffer bname 'clone)
5697 (error (make-indirect-buffer buffer bname)))))
5699 (defun org-set-frame-title (title)
5700 "Set the title of the current frame to the string TITLE."
5701 ;; FIXME: how to name a single frame in XEmacs???
5702 (unless (featurep 'xemacs)
5703 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5705 ;;;; Structure editing
5707 ;;; Inserting headlines
5709 (defun org-previous-line-empty-p ()
5710 (save-excursion
5711 (and (not (bobp))
5712 (or (beginning-of-line 0) t)
5713 (save-match-data
5714 (looking-at "[ \t]*$")))))
5716 (defun org-insert-heading (&optional force-heading)
5717 "Insert a new heading or item with same depth at point.
5718 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5719 If point is at the beginning of a headline, insert a sibling before the
5720 current headline. If point is not at the beginning, do not split the line,
5721 but create the new headline after the current line."
5722 (interactive "P")
5723 (if (= (buffer-size) 0)
5724 (insert "\n* ")
5725 (when (or force-heading (not (org-insert-item)))
5726 (let* ((empty-line-p nil)
5727 (head (save-excursion
5728 (condition-case nil
5729 (progn
5730 (org-back-to-heading)
5731 (setq empty-line-p (org-previous-line-empty-p))
5732 (match-string 0))
5733 (error "*"))))
5734 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5735 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5736 pos hide-previous previous-pos)
5737 (cond
5738 ((and (org-on-heading-p) (bolp)
5739 (or (bobp)
5740 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5741 ;; insert before the current line
5742 (open-line (if blank 2 1)))
5743 ((and (bolp)
5744 (not org-insert-heading-respect-content)
5745 (or (bobp)
5746 (save-excursion
5747 (backward-char 1) (not (org-invisible-p)))))
5748 ;; insert right here
5749 nil)
5751 ;; somewhere in the line
5752 (save-excursion
5753 (setq previous-pos (point-at-bol))
5754 (end-of-line)
5755 (setq hide-previous (org-invisible-p)))
5756 (and org-insert-heading-respect-content (org-show-subtree))
5757 (let ((split
5758 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5759 (save-excursion
5760 (let ((p (point)))
5761 (goto-char (point-at-bol))
5762 (and (looking-at org-complex-heading-regexp)
5763 (> p (match-beginning 4)))))))
5764 tags pos)
5765 (cond
5766 (org-insert-heading-respect-content
5767 (org-end-of-subtree nil t)
5768 (or (bolp) (newline))
5769 (or (org-previous-line-empty-p)
5770 (and blank (newline)))
5771 (open-line 1))
5772 ((org-on-heading-p)
5773 (when hide-previous
5774 (show-children)
5775 (org-show-entry))
5776 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5777 (setq tags (and (match-end 2) (match-string 2)))
5778 (and (match-end 1)
5779 (delete-region (match-beginning 1) (match-end 1)))
5780 (setq pos (point-at-bol))
5781 (or split (end-of-line 1))
5782 (delete-horizontal-space)
5783 (newline (if blank 2 1))
5784 (when tags
5785 (save-excursion
5786 (goto-char pos)
5787 (end-of-line 1)
5788 (insert " " tags)
5789 (org-set-tags nil 'align))))
5791 (or split (end-of-line 1))
5792 (newline (if blank 2 1)))))))
5793 (insert head) (just-one-space)
5794 (setq pos (point))
5795 (end-of-line 1)
5796 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5797 (when (and org-insert-heading-respect-content hide-previous)
5798 (save-excursion
5799 (goto-char previous-pos)
5800 (hide-subtree)))
5801 (run-hooks 'org-insert-heading-hook)))))
5803 (defun org-get-heading (&optional no-tags)
5804 "Return the heading of the current entry, without the stars."
5805 (save-excursion
5806 (org-back-to-heading t)
5807 (if (looking-at
5808 (if no-tags
5809 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5810 "\\*+[ \t]+\\([^\r\n]*\\)"))
5811 (match-string 1) "")))
5813 (defun org-heading-components ()
5814 "Return the components of the current heading.
5815 This is a list with the following elements:
5816 - the level as an integer
5817 - the reduced level, different if `org-odd-levels-only' is set.
5818 - the TODO keyword, or nil
5819 - the priority character, like ?A, or nil if no priority is given
5820 - the headline text itself, or the tags string if no headline text
5821 - the tags string, or nil."
5822 (save-excursion
5823 (org-back-to-heading t)
5824 (if (looking-at org-complex-heading-regexp)
5825 (list (length (match-string 1))
5826 (org-reduced-level (length (match-string 1)))
5827 (org-match-string-no-properties 2)
5828 (and (match-end 3) (aref (match-string 3) 2))
5829 (org-match-string-no-properties 4)
5830 (org-match-string-no-properties 5)))))
5832 (defun org-get-entry ()
5833 "Get the entry text, after heading, entire subtree."
5834 (save-excursion
5835 (org-back-to-heading t)
5836 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5838 (defun org-insert-heading-after-current ()
5839 "Insert a new heading with same level as current, after current subtree."
5840 (interactive)
5841 (org-back-to-heading)
5842 (org-insert-heading)
5843 (org-move-subtree-down)
5844 (end-of-line 1))
5846 (defun org-insert-heading-respect-content ()
5847 (interactive)
5848 (let ((org-insert-heading-respect-content t))
5849 (org-insert-heading t)))
5851 (defun org-insert-todo-heading-respect-content (&optional force-state)
5852 (interactive "P")
5853 (let ((org-insert-heading-respect-content t))
5854 (org-insert-todo-heading force-state t)))
5856 (defun org-insert-todo-heading (arg &optional force-heading)
5857 "Insert a new heading with the same level and TODO state as current heading.
5858 If the heading has no TODO state, or if the state is DONE, use the first
5859 state (TODO by default). Also with prefix arg, force first state."
5860 (interactive "P")
5861 (when (or force-heading (not (org-insert-item 'checkbox)))
5862 (org-insert-heading force-heading)
5863 (save-excursion
5864 (org-back-to-heading)
5865 (outline-previous-heading)
5866 (looking-at org-todo-line-regexp))
5867 (let*
5868 ((new-mark-x
5869 (if (or arg
5870 (not (match-beginning 2))
5871 (member (match-string 2) org-done-keywords))
5872 (car org-todo-keywords-1)
5873 (match-string 2)))
5874 (new-mark
5876 (run-hook-with-args-until-success
5877 'org-todo-get-default-hook new-mark-x nil)
5878 new-mark-x)))
5879 (beginning-of-line 1)
5880 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5881 (if org-treat-insert-todo-heading-as-state-change
5882 (org-todo new-mark)
5883 (insert new-mark " "))))
5884 (when org-provide-todo-statistics
5885 (org-update-parent-todo-statistics))))
5887 (defun org-insert-subheading (arg)
5888 "Insert a new subheading and demote it.
5889 Works for outline headings and for plain lists alike."
5890 (interactive "P")
5891 (org-insert-heading arg)
5892 (cond
5893 ((org-on-heading-p) (org-do-demote))
5894 ((org-at-item-p) (org-indent-item 1))))
5896 (defun org-insert-todo-subheading (arg)
5897 "Insert a new subheading with TODO keyword or checkbox and demote it.
5898 Works for outline headings and for plain lists alike."
5899 (interactive "P")
5900 (org-insert-todo-heading arg)
5901 (cond
5902 ((org-on-heading-p) (org-do-demote))
5903 ((org-at-item-p) (org-indent-item 1))))
5905 ;;; Promotion and Demotion
5907 (defvar org-after-demote-entry-hook nil
5908 "Hook run after an entry has been demoted.
5909 The cursor will be at the beginning of the entry.
5910 When a subtree is being demoted, the hook will be called for each node.")
5912 (defvar org-after-promote-entry-hook nil
5913 "Hook run after an entry has been promoted.
5914 The cursor will be at the beginning of the entry.
5915 When a subtree is being promoted, the hook will be called for each node.")
5917 (defun org-promote-subtree ()
5918 "Promote the entire subtree.
5919 See also `org-promote'."
5920 (interactive)
5921 (save-excursion
5922 (org-map-tree 'org-promote))
5923 (org-fix-position-after-promote))
5925 (defun org-demote-subtree ()
5926 "Demote the entire subtree. See `org-demote'.
5927 See also `org-promote'."
5928 (interactive)
5929 (save-excursion
5930 (org-map-tree 'org-demote))
5931 (org-fix-position-after-promote))
5934 (defun org-do-promote ()
5935 "Promote the current heading higher up the tree.
5936 If the region is active in `transient-mark-mode', promote all headings
5937 in the region."
5938 (interactive)
5939 (save-excursion
5940 (if (org-region-active-p)
5941 (org-map-region 'org-promote (region-beginning) (region-end))
5942 (org-promote)))
5943 (org-fix-position-after-promote))
5945 (defun org-do-demote ()
5946 "Demote the current heading lower down the tree.
5947 If the region is active in `transient-mark-mode', demote all headings
5948 in the region."
5949 (interactive)
5950 (save-excursion
5951 (if (org-region-active-p)
5952 (org-map-region 'org-demote (region-beginning) (region-end))
5953 (org-demote)))
5954 (org-fix-position-after-promote))
5956 (defun org-fix-position-after-promote ()
5957 "Make sure that after pro/demotion cursor position is right."
5958 (let ((pos (point)))
5959 (when (save-excursion
5960 (beginning-of-line 1)
5961 (looking-at org-todo-line-regexp)
5962 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5963 (cond ((eobp) (insert " "))
5964 ((eolp) (insert " "))
5965 ((equal (char-after) ?\ ) (forward-char 1))))))
5967 (defun org-reduced-level (l)
5968 "Compute the effective level of a heading.
5969 This takes into account the setting of `org-odd-levels-only'."
5970 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5972 (defun org-get-valid-level (level &optional change)
5973 "Rectify a level change under the influence of `org-odd-levels-only'
5974 LEVEL is a current level, CHANGE is by how much the level should be
5975 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5976 even level numbers will become the next higher odd number."
5977 (if org-odd-levels-only
5978 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5979 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5980 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5981 (max 1 (+ level (or change 0)))))
5983 (if (boundp 'define-obsolete-function-alias)
5984 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5985 (define-obsolete-function-alias 'org-get-legal-level
5986 'org-get-valid-level)
5987 (define-obsolete-function-alias 'org-get-legal-level
5988 'org-get-valid-level "23.1")))
5990 (defun org-promote ()
5991 "Promote the current heading higher up the tree.
5992 If the region is active in `transient-mark-mode', promote all headings
5993 in the region."
5994 (org-back-to-heading t)
5995 (let* ((level (save-match-data (funcall outline-level)))
5996 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5997 (diff (abs (- level (length up-head) -1))))
5998 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5999 (replace-match up-head nil t)
6000 ;; Fixup tag positioning
6001 (and org-auto-align-tags (org-set-tags nil t))
6002 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6003 (run-hooks 'org-after-promote-entry-hook)))
6005 (defun org-demote ()
6006 "Demote the current heading lower down the tree.
6007 If the region is active in `transient-mark-mode', demote all headings
6008 in the region."
6009 (org-back-to-heading t)
6010 (let* ((level (save-match-data (funcall outline-level)))
6011 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6012 (diff (abs (- level (length down-head) -1))))
6013 (replace-match down-head nil t)
6014 ;; Fixup tag positioning
6015 (and org-auto-align-tags (org-set-tags nil t))
6016 (if org-adapt-indentation (org-fixup-indentation diff))
6017 (run-hooks 'org-after-demote-entry-hook)))
6019 (defun org-map-tree (fun)
6020 "Call FUN for every heading underneath the current one."
6021 (org-back-to-heading)
6022 (let ((level (funcall outline-level)))
6023 (save-excursion
6024 (funcall fun)
6025 (while (and (progn
6026 (outline-next-heading)
6027 (> (funcall outline-level) level))
6028 (not (eobp)))
6029 (funcall fun)))))
6031 (defun org-map-region (fun beg end)
6032 "Call FUN for every heading between BEG and END."
6033 (let ((org-ignore-region t))
6034 (save-excursion
6035 (setq end (copy-marker end))
6036 (goto-char beg)
6037 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6038 (< (point) end))
6039 (funcall fun))
6040 (while (and (progn
6041 (outline-next-heading)
6042 (< (point) end))
6043 (not (eobp)))
6044 (funcall fun)))))
6046 (defun org-fixup-indentation (diff)
6047 "Change the indentation in the current entry by DIFF
6048 However, if any line in the current entry has no indentation, or if it
6049 would end up with no indentation after the change, nothing at all is done."
6050 (save-excursion
6051 (let ((end (save-excursion (outline-next-heading)
6052 (point-marker)))
6053 (prohibit (if (> diff 0)
6054 "^\\S-"
6055 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6056 col)
6057 (unless (save-excursion (end-of-line 1)
6058 (re-search-forward prohibit end t))
6059 (while (and (< (point) end)
6060 (re-search-forward "^[ \t]+" end t))
6061 (goto-char (match-end 0))
6062 (setq col (current-column))
6063 (if (< diff 0) (replace-match ""))
6064 (org-indent-to-column (+ diff col))))
6065 (move-marker end nil))))
6067 (defun org-convert-to-odd-levels ()
6068 "Convert an org-mode file with all levels allowed to one with odd levels.
6069 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6070 level 5 etc."
6071 (interactive)
6072 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6073 (let ((outline-regexp org-outline-regexp)
6074 (outline-level 'org-outline-level)
6075 (org-odd-levels-only nil) n)
6076 (save-excursion
6077 (goto-char (point-min))
6078 (while (re-search-forward "^\\*\\*+ " nil t)
6079 (setq n (- (length (match-string 0)) 2))
6080 (while (>= (setq n (1- n)) 0)
6081 (org-demote))
6082 (end-of-line 1))))))
6084 (defun org-convert-to-oddeven-levels ()
6085 "Convert an org-mode file with only odd levels to one with odd and even levels.
6086 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6087 section with an even level, conversion would destroy the structure of the file. An error
6088 is signaled in this case."
6089 (interactive)
6090 (goto-char (point-min))
6091 ;; First check if there are no even levels
6092 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6093 (org-show-context t)
6094 (error "Not all levels are odd in this file. Conversion not possible."))
6095 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6096 (let ((outline-regexp org-outline-regexp)
6097 (outline-level 'org-outline-level)
6098 (org-odd-levels-only nil) n)
6099 (save-excursion
6100 (goto-char (point-min))
6101 (while (re-search-forward "^\\*\\*+ " nil t)
6102 (setq n (/ (1- (length (match-string 0))) 2))
6103 (while (>= (setq n (1- n)) 0)
6104 (org-promote))
6105 (end-of-line 1))))))
6107 (defun org-tr-level (n)
6108 "Make N odd if required."
6109 (if org-odd-levels-only (1+ (/ n 2)) n))
6111 ;;; Vertical tree motion, cutting and pasting of subtrees
6113 (defun org-move-subtree-up (&optional arg)
6114 "Move the current subtree up past ARG headlines of the same level."
6115 (interactive "p")
6116 (org-move-subtree-down (- (prefix-numeric-value arg))))
6118 (defun org-move-subtree-down (&optional arg)
6119 "Move the current subtree down past ARG headlines of the same level."
6120 (interactive "p")
6121 (setq arg (prefix-numeric-value arg))
6122 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6123 'org-get-last-sibling))
6124 (ins-point (make-marker))
6125 (cnt (abs arg))
6126 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6127 ;; Select the tree
6128 (org-back-to-heading)
6129 (setq beg0 (point))
6130 (save-excursion
6131 (setq ne-beg (org-back-over-empty-lines))
6132 (setq beg (point)))
6133 (save-match-data
6134 (save-excursion (outline-end-of-heading)
6135 (setq folded (org-invisible-p)))
6136 (outline-end-of-subtree))
6137 (outline-next-heading)
6138 (setq ne-end (org-back-over-empty-lines))
6139 (setq end (point))
6140 (goto-char beg0)
6141 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6142 ;; include less whitespace
6143 (save-excursion
6144 (goto-char beg)
6145 (forward-line (- ne-beg ne-end))
6146 (setq beg (point))))
6147 ;; Find insertion point, with error handling
6148 (while (> cnt 0)
6149 (or (and (funcall movfunc) (looking-at outline-regexp))
6150 (progn (goto-char beg0)
6151 (error "Cannot move past superior level or buffer limit")))
6152 (setq cnt (1- cnt)))
6153 (if (> arg 0)
6154 ;; Moving forward - still need to move over subtree
6155 (progn (org-end-of-subtree t t)
6156 (save-excursion
6157 (org-back-over-empty-lines)
6158 (or (bolp) (newline)))))
6159 (setq ne-ins (org-back-over-empty-lines))
6160 (move-marker ins-point (point))
6161 (setq txt (buffer-substring beg end))
6162 (org-save-markers-in-region beg end)
6163 (delete-region beg end)
6164 (org-remove-empty-overlays-at beg)
6165 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6166 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6167 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6168 (let ((bbb (point)))
6169 (insert-before-markers txt)
6170 (org-reinstall-markers-in-region bbb)
6171 (move-marker ins-point bbb))
6172 (or (bolp) (insert "\n"))
6173 (setq ins-end (point))
6174 (goto-char ins-point)
6175 (org-skip-whitespace)
6176 (when (and (< arg 0)
6177 (org-first-sibling-p)
6178 (> ne-ins ne-beg))
6179 ;; Move whitespace back to beginning
6180 (save-excursion
6181 (goto-char ins-end)
6182 (let ((kill-whole-line t))
6183 (kill-line (- ne-ins ne-beg)) (point)))
6184 (insert (make-string (- ne-ins ne-beg) ?\n)))
6185 (move-marker ins-point nil)
6186 (if folded
6187 (hide-subtree)
6188 (org-show-entry)
6189 (show-children)
6190 (org-cycle-hide-drawers 'children))
6191 (org-clean-visibility-after-subtree-move)))
6193 (defvar org-subtree-clip ""
6194 "Clipboard for cut and paste of subtrees.
6195 This is actually only a copy of the kill, because we use the normal kill
6196 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6198 (defvar org-subtree-clip-folded nil
6199 "Was the last copied subtree folded?
6200 This is used to fold the tree back after pasting.")
6202 (defun org-cut-subtree (&optional n)
6203 "Cut the current subtree into the clipboard.
6204 With prefix arg N, cut this many sequential subtrees.
6205 This is a short-hand for marking the subtree and then cutting it."
6206 (interactive "p")
6207 (org-copy-subtree n 'cut))
6209 (defun org-copy-subtree (&optional n cut force-store-markers)
6210 "Cut the current subtree into the clipboard.
6211 With prefix arg N, cut this many sequential subtrees.
6212 This is a short-hand for marking the subtree and then copying it.
6213 If CUT is non-nil, actually cut the subtree.
6214 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6215 of some markers in the region, even if CUT is non-nil. This is
6216 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6217 (interactive "p")
6218 (let (beg end folded (beg0 (point)))
6219 (if (interactive-p)
6220 (org-back-to-heading nil) ; take what looks like a subtree
6221 (org-back-to-heading t)) ; take what is really there
6222 (org-back-over-empty-lines)
6223 (setq beg (point))
6224 (skip-chars-forward " \t\r\n")
6225 (save-match-data
6226 (save-excursion (outline-end-of-heading)
6227 (setq folded (org-invisible-p)))
6228 (condition-case nil
6229 (org-forward-same-level (1- n) t)
6230 (error nil))
6231 (org-end-of-subtree t t))
6232 (org-back-over-empty-lines)
6233 (setq end (point))
6234 (goto-char beg0)
6235 (when (> end beg)
6236 (setq org-subtree-clip-folded folded)
6237 (when (or cut force-store-markers)
6238 (org-save-markers-in-region beg end))
6239 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6240 (setq org-subtree-clip (current-kill 0))
6241 (message "%s: Subtree(s) with %d characters"
6242 (if cut "Cut" "Copied")
6243 (length org-subtree-clip)))))
6245 (defun org-paste-subtree (&optional level tree for-yank)
6246 "Paste the clipboard as a subtree, with modification of headline level.
6247 The entire subtree is promoted or demoted in order to match a new headline
6248 level.
6250 If the cursor is at the beginning of a headline, the same level as
6251 that headline is used to paste the tree
6253 If not, the new level is derived from the *visible* headings
6254 before and after the insertion point, and taken to be the inferior headline
6255 level of the two. So if the previous visible heading is level 3 and the
6256 next is level 4 (or vice versa), level 4 will be used for insertion.
6257 This makes sure that the subtree remains an independent subtree and does
6258 not swallow low level entries.
6260 You can also force a different level, either by using a numeric prefix
6261 argument, or by inserting the heading marker by hand. For example, if the
6262 cursor is after \"*****\", then the tree will be shifted to level 5.
6264 If optional TREE is given, use this text instead of the kill ring.
6266 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6267 move back over whitespace before inserting, and move point to the end of
6268 the inserted text when done."
6269 (interactive "P")
6270 (setq tree (or tree (and kill-ring (current-kill 0))))
6271 (unless (org-kill-is-subtree-p tree)
6272 (error "%s"
6273 (substitute-command-keys
6274 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6275 (let* ((visp (not (org-invisible-p)))
6276 (txt tree)
6277 (^re (concat "^\\(" outline-regexp "\\)"))
6278 (re (concat "\\(" outline-regexp "\\)"))
6279 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6281 (old-level (if (string-match ^re txt)
6282 (- (match-end 0) (match-beginning 0) 1)
6283 -1))
6284 (force-level (cond (level (prefix-numeric-value level))
6285 ((and (looking-at "[ \t]*$")
6286 (string-match
6287 ^re_ (buffer-substring
6288 (point-at-bol) (point))))
6289 (- (match-end 1) (match-beginning 1)))
6290 ((and (bolp)
6291 (looking-at org-outline-regexp))
6292 (- (match-end 0) (point) 1))
6293 (t nil)))
6294 (previous-level (save-excursion
6295 (condition-case nil
6296 (progn
6297 (outline-previous-visible-heading 1)
6298 (if (looking-at re)
6299 (- (match-end 0) (match-beginning 0) 1)
6301 (error 1))))
6302 (next-level (save-excursion
6303 (condition-case nil
6304 (progn
6305 (or (looking-at outline-regexp)
6306 (outline-next-visible-heading 1))
6307 (if (looking-at re)
6308 (- (match-end 0) (match-beginning 0) 1)
6310 (error 1))))
6311 (new-level (or force-level (max previous-level next-level)))
6312 (shift (if (or (= old-level -1)
6313 (= new-level -1)
6314 (= old-level new-level))
6316 (- new-level old-level)))
6317 (delta (if (> shift 0) -1 1))
6318 (func (if (> shift 0) 'org-demote 'org-promote))
6319 (org-odd-levels-only nil)
6320 beg end newend)
6321 ;; Remove the forced level indicator
6322 (if force-level
6323 (delete-region (point-at-bol) (point)))
6324 ;; Paste
6325 (beginning-of-line 1)
6326 (unless for-yank (org-back-over-empty-lines))
6327 (setq beg (point))
6328 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6329 (insert-before-markers txt)
6330 (unless (string-match "\n\\'" txt) (insert "\n"))
6331 (setq newend (point))
6332 (org-reinstall-markers-in-region beg)
6333 (setq end (point))
6334 (goto-char beg)
6335 (skip-chars-forward " \t\n\r")
6336 (setq beg (point))
6337 (if (and (org-invisible-p) visp)
6338 (save-excursion (outline-show-heading)))
6339 ;; Shift if necessary
6340 (unless (= shift 0)
6341 (save-restriction
6342 (narrow-to-region beg end)
6343 (while (not (= shift 0))
6344 (org-map-region func (point-min) (point-max))
6345 (setq shift (+ delta shift)))
6346 (goto-char (point-min))
6347 (setq newend (point-max))))
6348 (when (or (interactive-p) for-yank)
6349 (message "Clipboard pasted as level %d subtree" new-level))
6350 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6351 kill-ring
6352 (eq org-subtree-clip (current-kill 0))
6353 org-subtree-clip-folded)
6354 ;; The tree was folded before it was killed/copied
6355 (hide-subtree))
6356 (and for-yank (goto-char newend))))
6358 (defun org-kill-is-subtree-p (&optional txt)
6359 "Check if the current kill is an outline subtree, or a set of trees.
6360 Returns nil if kill does not start with a headline, or if the first
6361 headline level is not the largest headline level in the tree.
6362 So this will actually accept several entries of equal levels as well,
6363 which is OK for `org-paste-subtree'.
6364 If optional TXT is given, check this string instead of the current kill."
6365 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6366 (start-level (and kill
6367 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6368 org-outline-regexp "\\)")
6369 kill)
6370 (- (match-end 2) (match-beginning 2) 1)))
6371 (re (concat "^" org-outline-regexp))
6372 (start (1+ (or (match-beginning 2) -1))))
6373 (if (not start-level)
6374 (progn
6375 nil) ;; does not even start with a heading
6376 (catch 'exit
6377 (while (setq start (string-match re kill (1+ start)))
6378 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6379 (throw 'exit nil)))
6380 t))))
6382 (defvar org-markers-to-move nil
6383 "Markers that should be moved with a cut-and-paste operation.
6384 Those markers are stored together with their positions relative to
6385 the start of the region.")
6387 (defun org-save-markers-in-region (beg end)
6388 "Check markers in region.
6389 If these markers are between BEG and END, record their position relative
6390 to BEG, so that after moving the block of text, we can put the markers back
6391 into place.
6392 This function gets called just before an entry or tree gets cut from the
6393 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6394 called immediately, to move the markers with the entries."
6395 (setq org-markers-to-move nil)
6396 (when (featurep 'org-clock)
6397 (org-clock-save-markers-for-cut-and-paste beg end))
6398 (when (featurep 'org-agenda)
6399 (org-agenda-save-markers-for-cut-and-paste beg end)))
6401 (defun org-check-and-save-marker (marker beg end)
6402 "Check if MARKER is between BEG and END.
6403 If yes, remember the marker and the distance to BEG."
6404 (when (and (marker-buffer marker)
6405 (equal (marker-buffer marker) (current-buffer)))
6406 (if (and (>= marker beg) (< marker end))
6407 (push (cons marker (- marker beg)) org-markers-to-move))))
6409 (defun org-reinstall-markers-in-region (beg)
6410 "Move all remembered markers to their position relative to BEG."
6411 (mapc (lambda (x)
6412 (move-marker (car x) (+ beg (cdr x))))
6413 org-markers-to-move)
6414 (setq org-markers-to-move nil))
6416 (defun org-narrow-to-subtree ()
6417 "Narrow buffer to the current subtree."
6418 (interactive)
6419 (save-excursion
6420 (save-match-data
6421 (narrow-to-region
6422 (progn (org-back-to-heading t) (point))
6423 (progn (org-end-of-subtree t) (point))))))
6425 (defun org-clone-subtree-with-time-shift (n &optional shift)
6426 "Clone the task (subtree) at point N times.
6427 The clones will be inserted as siblings.
6429 In interactive use, the user will be prompted for the number of clones
6430 to be produced, and for a time SHIFT, which may be a repeater as used
6431 in time stamps, for example `+3d'.
6433 When a valid repeater is given and the entry contains any time stamps,
6434 the clones will become a sequence in time, with time stamps in the
6435 subtree shifted for each clone produced. If SHIFT is nil or the
6436 empty string, time stamps will be left alone.
6438 If the original subtree did contain time stamps with a repeater,
6439 the following will happen:
6440 - the repeater will be removed in each clone
6441 - an additional clone will be produced, with the current, unshifted
6442 date(s) in the entry.
6443 - the original entry will be placed *after* all the clones, with
6444 repeater intact.
6445 - the start days in the repeater in the original entry will be shifted
6446 to past the last clone.
6447 I this way you can spell out a number of instances of a repeating task,
6448 and still retain the repeater to cover future instances of the task."
6449 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6450 (let (beg end template task
6451 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6452 (if (not (and (integerp n) (> n 0)))
6453 (error "Invalid number of replications %s" n))
6454 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6455 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6456 shift)))
6457 (error "Invalid shift specification %s" shift))
6458 (when doshift
6459 (setq shift-n (string-to-number (match-string 1 shift))
6460 shift-what (cdr (assoc (match-string 2 shift)
6461 '(("d" . day) ("w" . week)
6462 ("m" . month) ("y" . year))))))
6463 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6464 (setq nmin 1 nmax n)
6465 (org-back-to-heading t)
6466 (setq beg (point))
6467 (org-end-of-subtree t t)
6468 (setq end (point))
6469 (setq template (buffer-substring beg end))
6470 (when (and doshift
6471 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6472 (delete-region beg end)
6473 (setq end beg)
6474 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6475 (goto-char end)
6476 (loop for n from nmin to nmax do
6477 (if (not doshift)
6478 (setq task template)
6479 (with-temp-buffer
6480 (insert template)
6481 (org-mode)
6482 (goto-char (point-min))
6483 (while (re-search-forward org-ts-regexp-both nil t)
6484 (org-timestamp-change (* n shift-n) shift-what))
6485 (unless (= n n-no-remove)
6486 (goto-char (point-min))
6487 (while (re-search-forward org-ts-regexp nil t)
6488 (save-excursion
6489 (goto-char (match-beginning 0))
6490 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6491 (delete-region (match-beginning 1) (match-end 1))))))
6492 (setq task (buffer-string))))
6493 (insert task))
6494 (goto-char beg)))
6496 ;;; Outline Sorting
6498 (defun org-sort (with-case)
6499 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6500 Optional argument WITH-CASE means sort case-sensitively.
6501 With a double prefix argument, also remove duplicate entries."
6502 (interactive "P")
6503 (if (org-at-table-p)
6504 (org-call-with-arg 'org-table-sort-lines with-case)
6505 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6507 (defun org-sort-remove-invisible (s)
6508 (remove-text-properties 0 (length s) org-rm-props s)
6509 (while (string-match org-bracket-link-regexp s)
6510 (setq s (replace-match (if (match-end 2)
6511 (match-string 3 s)
6512 (match-string 1 s)) t t s)))
6515 (defvar org-priority-regexp) ; defined later in the file
6517 (defvar org-after-sorting-entries-or-items-hook nil
6518 "Hook that is run after a bunch of entries or items have been sorted.
6519 When children are sorted, the cursor is in the parent line when this
6520 hook gets called. When a region or a plain list is sorted, the cursor
6521 will be in the first entry of the sorted region/list.")
6523 (defun org-sort-entries-or-items
6524 (&optional with-case sorting-type getkey-func compare-func property)
6525 "Sort entries on a certain level of an outline tree, or plain list items.
6526 If there is an active region, the entries in the region are sorted.
6527 Else, if the cursor is before the first entry, sort the top-level items.
6528 Else, the children of the entry at point are sorted.
6529 If the cursor is at the first item in a plain list, the list items will be
6530 sorted.
6532 Sorting can be alphabetically, numerically, by date/time as given by
6533 a time stamp, by a property or by priority.
6535 The command prompts for the sorting type unless it has been given to the
6536 function through the SORTING-TYPE argument, which needs to a character,
6537 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6538 precise meaning of each character:
6540 n Numerically, by converting the beginning of the entry/item to a number.
6541 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6542 t By date/time, either the first active time stamp in the entry, or, if
6543 none exist, by the first inactive one.
6544 In items, only the first line will be chekced.
6545 s By the scheduled date/time.
6546 d By deadline date/time.
6547 c By creation time, which is assumed to be the first inactive time stamp
6548 at the beginning of a line.
6549 p By priority according to the cookie.
6550 r By the value of a property.
6552 Capital letters will reverse the sort order.
6554 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6555 called with point at the beginning of the record. It must return either
6556 a string or a number that should serve as the sorting key for that record.
6558 Comparing entries ignores case by default. However, with an optional argument
6559 WITH-CASE, the sorting considers case as well."
6560 (interactive "P")
6561 (let ((case-func (if with-case 'identity 'downcase))
6562 start beg end stars re re2
6563 txt what tmp plain-list-p)
6564 ;; Find beginning and end of region to sort
6565 (cond
6566 ((org-region-active-p)
6567 ;; we will sort the region
6568 (setq end (region-end)
6569 what "region")
6570 (goto-char (region-beginning))
6571 (if (not (org-on-heading-p)) (outline-next-heading))
6572 (setq start (point)))
6573 ((org-at-item-p)
6574 ;; we will sort this plain list
6575 (org-beginning-of-item-list) (setq start (point))
6576 (org-end-of-item-list) (setq end (point))
6577 (goto-char start)
6578 (setq plain-list-p t
6579 what "plain list"))
6580 ((or (org-on-heading-p)
6581 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6582 ;; we will sort the children of the current headline
6583 (org-back-to-heading)
6584 (setq start (point)
6585 end (progn (org-end-of-subtree t t)
6586 (org-back-over-empty-lines)
6587 (point))
6588 what "children")
6589 (goto-char start)
6590 (show-subtree)
6591 (outline-next-heading))
6593 ;; we will sort the top-level entries in this file
6594 (goto-char (point-min))
6595 (or (org-on-heading-p) (outline-next-heading))
6596 (setq start (point) end (point-max) what "top-level")
6597 (goto-char start)
6598 (show-all)))
6600 (setq beg (point))
6601 (if (>= beg end) (error "Nothing to sort"))
6603 (unless plain-list-p
6604 (looking-at "\\(\\*+\\)")
6605 (setq stars (match-string 1)
6606 re (concat "^" (regexp-quote stars) " +")
6607 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6608 txt (buffer-substring beg end))
6609 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6610 (if (and (not (equal stars "*")) (string-match re2 txt))
6611 (error "Region to sort contains a level above the first entry")))
6613 (unless sorting-type
6614 (message
6615 (if plain-list-p
6616 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6617 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6618 [t]ime [s]cheduled [d]eadline [c]reated
6619 A/N/T/S/D/C/P/O/F means reversed:")
6620 what)
6621 (setq sorting-type (read-char-exclusive))
6623 (and (= (downcase sorting-type) ?f)
6624 (setq getkey-func
6625 (org-icompleting-read "Sort using function: "
6626 obarray 'fboundp t nil nil))
6627 (setq getkey-func (intern getkey-func)))
6629 (and (= (downcase sorting-type) ?r)
6630 (setq property
6631 (org-icompleting-read "Property: "
6632 (mapcar 'list (org-buffer-property-keys t))
6633 nil t))))
6635 (message "Sorting entries...")
6637 (save-restriction
6638 (narrow-to-region start end)
6640 (let ((dcst (downcase sorting-type))
6641 (case-fold-search nil)
6642 (now (current-time)))
6643 (sort-subr
6644 (/= dcst sorting-type)
6645 ;; This function moves to the beginning character of the "record" to
6646 ;; be sorted.
6647 (if plain-list-p
6648 (lambda nil
6649 (if (org-at-item-p) t (goto-char (point-max))))
6650 (lambda nil
6651 (if (re-search-forward re nil t)
6652 (goto-char (match-beginning 0))
6653 (goto-char (point-max)))))
6654 ;; This function moves to the last character of the "record" being
6655 ;; sorted.
6656 (if plain-list-p
6657 'org-end-of-item
6658 (lambda nil
6659 (save-match-data
6660 (condition-case nil
6661 (outline-forward-same-level 1)
6662 (error
6663 (goto-char (point-max)))))))
6665 ;; This function returns the value that gets sorted against.
6666 (if plain-list-p
6667 (lambda nil
6668 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6669 (cond
6670 ((= dcst ?n)
6671 (string-to-number (buffer-substring (match-end 0)
6672 (point-at-eol))))
6673 ((= dcst ?a)
6674 (buffer-substring (match-end 0) (point-at-eol)))
6675 ((= dcst ?t)
6676 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6677 (re-search-forward org-ts-regexp-both
6678 (point-at-eol) t))
6679 (org-time-string-to-seconds (match-string 0))
6680 (org-float-time now)))
6681 ((= dcst ?f)
6682 (if getkey-func
6683 (progn
6684 (setq tmp (funcall getkey-func))
6685 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6686 tmp)
6687 (error "Invalid key function `%s'" getkey-func)))
6688 (t (error "Invalid sorting type `%c'" sorting-type)))))
6689 (lambda nil
6690 (cond
6691 ((= dcst ?n)
6692 (if (looking-at org-complex-heading-regexp)
6693 (string-to-number (match-string 4))
6694 nil))
6695 ((= dcst ?a)
6696 (if (looking-at org-complex-heading-regexp)
6697 (funcall case-func (match-string 4))
6698 nil))
6699 ((= dcst ?t)
6700 (let ((end (save-excursion (outline-next-heading) (point))))
6701 (if (or (re-search-forward org-ts-regexp end t)
6702 (re-search-forward org-ts-regexp-both end t))
6703 (org-time-string-to-seconds (match-string 0))
6704 (org-float-time now))))
6705 ((= dcst ?c)
6706 (let ((end (save-excursion (outline-next-heading) (point))))
6707 (if (re-search-forward
6708 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6709 end t)
6710 (org-time-string-to-seconds (match-string 0))
6711 (org-float-time now))))
6712 ((= dcst ?s)
6713 (let ((end (save-excursion (outline-next-heading) (point))))
6714 (if (re-search-forward org-scheduled-time-regexp end t)
6715 (org-time-string-to-seconds (match-string 1))
6716 (org-float-time now))))
6717 ((= dcst ?d)
6718 (let ((end (save-excursion (outline-next-heading) (point))))
6719 (if (re-search-forward org-deadline-time-regexp end t)
6720 (org-time-string-to-seconds (match-string 1))
6721 (org-float-time now))))
6722 ((= dcst ?p)
6723 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6724 (string-to-char (match-string 2))
6725 org-default-priority))
6726 ((= dcst ?r)
6727 (or (org-entry-get nil property) ""))
6728 ((= dcst ?o)
6729 (if (looking-at org-complex-heading-regexp)
6730 (- 9999 (length (member (match-string 2)
6731 org-todo-keywords-1)))))
6732 ((= dcst ?f)
6733 (if getkey-func
6734 (progn
6735 (setq tmp (funcall getkey-func))
6736 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6737 tmp)
6738 (error "Invalid key function `%s'" getkey-func)))
6739 (t (error "Invalid sorting type `%c'" sorting-type)))))
6741 (cond
6742 ((= dcst ?a) 'string<)
6743 ((= dcst ?f) compare-func)
6744 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6745 (t nil)))))
6746 (run-hooks 'org-after-sorting-entries-or-items-hook)
6747 (message "Sorting entries...done")))
6749 (defun org-do-sort (table what &optional with-case sorting-type)
6750 "Sort TABLE of WHAT according to SORTING-TYPE.
6751 The user will be prompted for the SORTING-TYPE if the call to this
6752 function does not specify it. WHAT is only for the prompt, to indicate
6753 what is being sorted. The sorting key will be extracted from
6754 the car of the elements of the table.
6755 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6756 (unless sorting-type
6757 (message
6758 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6759 what)
6760 (setq sorting-type (read-char-exclusive)))
6761 (let ((dcst (downcase sorting-type))
6762 extractfun comparefun)
6763 ;; Define the appropriate functions
6764 (cond
6765 ((= dcst ?n)
6766 (setq extractfun 'string-to-number
6767 comparefun (if (= dcst sorting-type) '< '>)))
6768 ((= dcst ?a)
6769 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6770 (lambda(x) (downcase (org-sort-remove-invisible x))))
6771 comparefun (if (= dcst sorting-type)
6772 'string<
6773 (lambda (a b) (and (not (string< a b))
6774 (not (string= a b)))))))
6775 ((= dcst ?t)
6776 (setq extractfun
6777 (lambda (x)
6778 (if (or (string-match org-ts-regexp x)
6779 (string-match org-ts-regexp-both x))
6780 (org-float-time
6781 (org-time-string-to-time (match-string 0 x)))
6783 comparefun (if (= dcst sorting-type) '< '>)))
6784 (t (error "Invalid sorting type `%c'" sorting-type)))
6786 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6787 table)
6788 (lambda (a b) (funcall comparefun (car a) (car b))))))
6791 ;;; The orgstruct minor mode
6793 ;; Define a minor mode which can be used in other modes in order to
6794 ;; integrate the org-mode structure editing commands.
6796 ;; This is really a hack, because the org-mode structure commands use
6797 ;; keys which normally belong to the major mode. Here is how it
6798 ;; works: The minor mode defines all the keys necessary to operate the
6799 ;; structure commands, but wraps the commands into a function which
6800 ;; tests if the cursor is currently at a headline or a plain list
6801 ;; item. If that is the case, the structure command is used,
6802 ;; temporarily setting many Org-mode variables like regular
6803 ;; expressions for filling etc. However, when any of those keys is
6804 ;; used at a different location, function uses `key-binding' to look
6805 ;; up if the key has an associated command in another currently active
6806 ;; keymap (minor modes, major mode, global), and executes that
6807 ;; command. There might be problems if any of the keys is otherwise
6808 ;; used as a prefix key.
6810 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6811 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6812 ;; addresses this by checking explicitly for both bindings.
6814 (defvar orgstruct-mode-map (make-sparse-keymap)
6815 "Keymap for the minor `orgstruct-mode'.")
6817 (defvar org-local-vars nil
6818 "List of local variables, for use by `orgstruct-mode'")
6820 ;;;###autoload
6821 (define-minor-mode orgstruct-mode
6822 "Toggle the minor more `orgstruct-mode'.
6823 This mode is for using Org-mode structure commands in other modes.
6824 The following key behave as if Org-mode was active, if the cursor
6825 is on a headline, or on a plain list item (both in the definition
6826 of Org-mode).
6828 M-up Move entry/item up
6829 M-down Move entry/item down
6830 M-left Promote
6831 M-right Demote
6832 M-S-up Move entry/item up
6833 M-S-down Move entry/item down
6834 M-S-left Promote subtree
6835 M-S-right Demote subtree
6836 M-q Fill paragraph and items like in Org-mode
6837 C-c ^ Sort entries
6838 C-c - Cycle list bullet
6839 TAB Cycle item visibility
6840 M-RET Insert new heading/item
6841 S-M-RET Insert new TODO heading / Checkbox item
6842 C-c C-c Set tags / toggle checkbox"
6843 nil " OrgStruct" nil
6844 (org-load-modules-maybe)
6845 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6847 ;;;###autoload
6848 (defun turn-on-orgstruct ()
6849 "Unconditionally turn on `orgstruct-mode'."
6850 (orgstruct-mode 1))
6852 (defun orgstruct++-mode (&optional arg)
6853 "Toggle `orgstruct-mode', the enhanced version of it.
6854 In addition to setting orgstruct-mode, this also exports all indentation
6855 and autofilling variables from org-mode into the buffer. It will also
6856 recognize item context in multiline items.
6857 Note that turning off orgstruct-mode will *not* remove the
6858 indentation/paragraph settings. This can only be done by refreshing the
6859 major mode, for example with \\[normal-mode]."
6860 (interactive "P")
6861 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6862 (if (< arg 1)
6863 (orgstruct-mode -1)
6864 (orgstruct-mode 1)
6865 (let (var val)
6866 (mapc
6867 (lambda (x)
6868 (when (string-match
6869 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6870 (symbol-name (car x)))
6871 (setq var (car x) val (nth 1 x))
6872 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6873 org-local-vars)
6874 (org-set-local 'orgstruct-is-++ t))))
6876 (defvar orgstruct-is-++ nil
6877 "Is orgstruct-mode in ++ version in the current-buffer?")
6878 (make-variable-buffer-local 'orgstruct-is-++)
6880 ;;;###autoload
6881 (defun turn-on-orgstruct++ ()
6882 "Unconditionally turn on `orgstruct++-mode'."
6883 (orgstruct++-mode 1))
6885 (defun orgstruct-error ()
6886 "Error when there is no default binding for a structure key."
6887 (interactive)
6888 (error "This key has no function outside structure elements"))
6890 (defun orgstruct-setup ()
6891 "Setup orgstruct keymaps."
6892 (let ((nfunc 0)
6893 (bindings
6894 (list
6895 '([(meta up)] org-metaup)
6896 '([(meta down)] org-metadown)
6897 '([(meta left)] org-metaleft)
6898 '([(meta right)] org-metaright)
6899 '([(meta shift up)] org-shiftmetaup)
6900 '([(meta shift down)] org-shiftmetadown)
6901 '([(meta shift left)] org-shiftmetaleft)
6902 '([(meta shift right)] org-shiftmetaright)
6903 '([?\e (up)] org-metaup)
6904 '([?\e (down)] org-metadown)
6905 '([?\e (left)] org-metaleft)
6906 '([?\e (right)] org-metaright)
6907 '([?\e (shift up)] org-shiftmetaup)
6908 '([?\e (shift down)] org-shiftmetadown)
6909 '([?\e (shift left)] org-shiftmetaleft)
6910 '([?\e (shift right)] org-shiftmetaright)
6911 '([(shift up)] org-shiftup)
6912 '([(shift down)] org-shiftdown)
6913 '([(shift left)] org-shiftleft)
6914 '([(shift right)] org-shiftright)
6915 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6916 '("\M-q" fill-paragraph)
6917 '("\C-c^" org-sort)
6918 '("\C-c-" org-cycle-list-bullet)))
6919 elt key fun cmd)
6920 (while (setq elt (pop bindings))
6921 (setq nfunc (1+ nfunc))
6922 (setq key (org-key (car elt))
6923 fun (nth 1 elt)
6924 cmd (orgstruct-make-binding fun nfunc key))
6925 (org-defkey orgstruct-mode-map key cmd))
6927 ;; Special treatment needed for TAB and RET
6928 (org-defkey orgstruct-mode-map [(tab)]
6929 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6930 (org-defkey orgstruct-mode-map "\C-i"
6931 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6933 (org-defkey orgstruct-mode-map "\M-\C-m"
6934 (orgstruct-make-binding 'org-insert-heading 105
6935 "\M-\C-m" [(meta return)]))
6936 (org-defkey orgstruct-mode-map [(meta return)]
6937 (orgstruct-make-binding 'org-insert-heading 106
6938 [(meta return)] "\M-\C-m"))
6940 (org-defkey orgstruct-mode-map [(shift meta return)]
6941 (orgstruct-make-binding 'org-insert-todo-heading 107
6942 [(meta return)] "\M-\C-m"))
6944 (org-defkey orgstruct-mode-map "\e\C-m"
6945 (orgstruct-make-binding 'org-insert-heading 108
6946 "\e\C-m" [?\e (return)]))
6947 (org-defkey orgstruct-mode-map [?\e (return)]
6948 (orgstruct-make-binding 'org-insert-heading 109
6949 [?\e (return)] "\e\C-m"))
6950 (org-defkey orgstruct-mode-map [?\e (shift return)]
6951 (orgstruct-make-binding 'org-insert-todo-heading 110
6952 [?\e (return)] "\e\C-m"))
6954 (unless org-local-vars
6955 (setq org-local-vars (org-get-local-variables)))
6959 (defun orgstruct-make-binding (fun n &rest keys)
6960 "Create a function for binding in the structure minor mode.
6961 FUN is the command to call inside a table. N is used to create a unique
6962 command name. KEYS are keys that should be checked in for a command
6963 to execute outside of tables."
6964 (eval
6965 (list 'defun
6966 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6967 '(arg)
6968 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6969 "Outside of structure, run the binding of `"
6970 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6971 "'.")
6972 '(interactive "p")
6973 (list 'if
6974 `(org-context-p 'headline 'item
6975 (and orgstruct-is-++
6976 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6977 'item-body))
6978 (list 'org-run-like-in-org-mode (list 'quote fun))
6979 (list 'let '(orgstruct-mode)
6980 (list 'call-interactively
6981 (append '(or)
6982 (mapcar (lambda (k)
6983 (list 'key-binding k))
6984 keys)
6985 '('orgstruct-error))))))))
6987 (defun org-context-p (&rest contexts)
6988 "Check if local context is any of CONTEXTS.
6989 Possible values in the list of contexts are `table', `headline', and `item'."
6990 (let ((pos (point)))
6991 (goto-char (point-at-bol))
6992 (prog1 (or (and (memq 'table contexts)
6993 (looking-at "[ \t]*|"))
6994 (and (memq 'headline contexts)
6995 ;;????????? (looking-at "\\*+"))
6996 (looking-at outline-regexp))
6997 (and (memq 'item contexts)
6998 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6999 (and (memq 'item-body contexts)
7000 (org-in-item-p)))
7001 (goto-char pos))))
7003 (defun org-get-local-variables ()
7004 "Return a list of all local variables in an org-mode buffer."
7005 (let (varlist)
7006 (with-current-buffer (get-buffer-create "*Org tmp*")
7007 (erase-buffer)
7008 (org-mode)
7009 (setq varlist (buffer-local-variables)))
7010 (kill-buffer "*Org tmp*")
7011 (delq nil
7012 (mapcar
7013 (lambda (x)
7014 (setq x
7015 (if (symbolp x)
7016 (list x)
7017 (list (car x) (list 'quote (cdr x)))))
7018 (if (string-match
7019 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7020 (symbol-name (car x)))
7021 x nil))
7022 varlist))))
7024 ;;;###autoload
7025 (defun org-run-like-in-org-mode (cmd)
7026 "Run a command, pretending that the current buffer is in Org-mode.
7027 This will temporarily bind local variables that are typically bound in
7028 Org-mode to the values they have in Org-mode, and then interactively
7029 call CMD."
7030 (org-load-modules-maybe)
7031 (unless org-local-vars
7032 (setq org-local-vars (org-get-local-variables)))
7033 (eval (list 'let org-local-vars
7034 (list 'call-interactively (list 'quote cmd)))))
7036 ;;;; Archiving
7038 (defun org-get-category (&optional pos)
7039 "Get the category applying to position POS."
7040 (get-text-property (or pos (point)) 'org-category))
7042 (defun org-refresh-category-properties ()
7043 "Refresh category text properties in the buffer."
7044 (let ((def-cat (cond
7045 ((null org-category)
7046 (if buffer-file-name
7047 (file-name-sans-extension
7048 (file-name-nondirectory buffer-file-name))
7049 "???"))
7050 ((symbolp org-category) (symbol-name org-category))
7051 (t org-category)))
7052 beg end cat pos optionp)
7053 (org-unmodified
7054 (save-excursion
7055 (save-restriction
7056 (widen)
7057 (goto-char (point-min))
7058 (put-text-property (point) (point-max) 'org-category def-cat)
7059 (while (re-search-forward
7060 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7061 (setq pos (match-end 0)
7062 optionp (equal (char-after (match-beginning 0)) ?#)
7063 cat (org-trim (match-string 2)))
7064 (if optionp
7065 (setq beg (point-at-bol) end (point-max))
7066 (org-back-to-heading t)
7067 (setq beg (point) end (org-end-of-subtree t t)))
7068 (put-text-property beg end 'org-category cat)
7069 (goto-char pos)))))))
7072 ;;;; Link Stuff
7074 ;;; Link abbreviations
7076 (defun org-link-expand-abbrev (link)
7077 "Apply replacements as defined in `org-link-abbrev-alist."
7078 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7079 (let* ((key (match-string 1 link))
7080 (as (or (assoc key org-link-abbrev-alist-local)
7081 (assoc key org-link-abbrev-alist)))
7082 (tag (and (match-end 2) (match-string 3 link)))
7083 rpl)
7084 (if (not as)
7085 link
7086 (setq rpl (cdr as))
7087 (cond
7088 ((symbolp rpl) (funcall rpl tag))
7089 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7090 ((string-match "%h" rpl)
7091 (replace-match (url-hexify-string (or tag "")) t t rpl))
7092 (t (concat rpl tag)))))
7093 link))
7095 ;;; Storing and inserting links
7097 (defvar org-insert-link-history nil
7098 "Minibuffer history for links inserted with `org-insert-link'.")
7100 (defvar org-stored-links nil
7101 "Contains the links stored with `org-store-link'.")
7103 (defvar org-store-link-plist nil
7104 "Plist with info about the most recently link created with `org-store-link'.")
7106 (defvar org-link-protocols nil
7107 "Link protocols added to Org-mode using `org-add-link-type'.")
7109 (defvar org-store-link-functions nil
7110 "List of functions that are called to create and store a link.
7111 Each function will be called in turn until one returns a non-nil
7112 value. Each function should check if it is responsible for creating
7113 this link (for example by looking at the major mode).
7114 If not, it must exit and return nil.
7115 If yes, it should return a non-nil value after a calling
7116 `org-store-link-props' with a list of properties and values.
7117 Special properties are:
7119 :type The link prefix. like \"http\". This must be given.
7120 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7121 This is obligatory as well.
7122 :description Optional default description for the second pair
7123 of brackets in an Org-mode link. The user can still change
7124 this when inserting this link into an Org-mode buffer.
7126 In addition to these, any additional properties can be specified
7127 and then used in remember templates.")
7129 (defun org-add-link-type (type &optional follow export)
7130 "Add TYPE to the list of `org-link-types'.
7131 Re-compute all regular expressions depending on `org-link-types'
7133 FOLLOW and EXPORT are two functions.
7135 FOLLOW should take the link path as the single argument and do whatever
7136 is necessary to follow the link, for example find a file or display
7137 a mail message.
7139 EXPORT should format the link path for export to one of the export formats.
7140 It should be a function accepting three arguments:
7142 path the path of the link, the text after the prefix (like \"http:\")
7143 desc the description of the link, if any, nil if there was no description
7144 format the export format, a symbol like `html' or `latex'.
7146 The function may use the FORMAT information to return different values
7147 depending on the format. The return value will be put literally into
7148 the exported file.
7149 Org-mode has a built-in default for exporting links. If you are happy with
7150 this default, there is no need to define an export function for the link
7151 type. For a simple example of an export function, see `org-bbdb.el'."
7152 (add-to-list 'org-link-types type t)
7153 (org-make-link-regexps)
7154 (if (assoc type org-link-protocols)
7155 (setcdr (assoc type org-link-protocols) (list follow export))
7156 (push (list type follow export) org-link-protocols)))
7158 (defvar org-agenda-buffer-name)
7160 ;;;###autoload
7161 (defun org-store-link (arg)
7162 "\\<org-mode-map>Store an org-link to the current location.
7163 This link is added to `org-stored-links' and can later be inserted
7164 into an org-buffer with \\[org-insert-link].
7166 For some link types, a prefix arg is interpreted:
7167 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7168 For file links, arg negates `org-context-in-file-links'."
7169 (interactive "P")
7170 (org-load-modules-maybe)
7171 (setq org-store-link-plist nil) ; reset
7172 (let ((outline-regexp (org-get-limited-outline-regexp))
7173 link cpltxt desc description search txt custom-id)
7174 (cond
7176 ((run-hook-with-args-until-success 'org-store-link-functions)
7177 (setq link (plist-get org-store-link-plist :link)
7178 desc (or (plist-get org-store-link-plist :description) link)))
7180 ((equal (buffer-name) "*Org Edit Src Example*")
7181 (let (label gc)
7182 (while (or (not label)
7183 (save-excursion
7184 (save-restriction
7185 (widen)
7186 (goto-char (point-min))
7187 (re-search-forward
7188 (regexp-quote (format org-coderef-label-format label))
7189 nil t))))
7190 (when label (message "Label exists already") (sit-for 2))
7191 (setq label (read-string "Code line label: " label)))
7192 (end-of-line 1)
7193 (setq link (format org-coderef-label-format label))
7194 (setq gc (- 79 (length link)))
7195 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7196 (insert link)
7197 (setq link (concat "(" label ")") desc nil)))
7199 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7200 ;; We are in the agenda, link to referenced location
7201 (let ((m (or (get-text-property (point) 'org-hd-marker)
7202 (get-text-property (point) 'org-marker))))
7203 (unless m (error "Don't know what location to link to"))
7204 (org-with-point-at m
7205 (call-interactively 'org-store-link))))
7207 ((eq major-mode 'calendar-mode)
7208 (let ((cd (calendar-cursor-to-date)))
7209 (setq link
7210 (format-time-string
7211 (car org-time-stamp-formats)
7212 (apply 'encode-time
7213 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7214 nil nil nil))))
7215 (org-store-link-props :type "calendar" :date cd)))
7217 ((eq major-mode 'w3-mode)
7218 (setq cpltxt (if (and (buffer-name)
7219 (not (string-match "Untitled" (buffer-name))))
7220 (buffer-name)
7221 (url-view-url t))
7222 link (org-make-link (url-view-url t)))
7223 (org-store-link-props :type "w3" :url (url-view-url t)))
7225 ((eq major-mode 'w3m-mode)
7226 (setq cpltxt (or w3m-current-title w3m-current-url)
7227 link (org-make-link w3m-current-url))
7228 (org-store-link-props :type "w3m" :url (url-view-url t)))
7230 ((setq search (run-hook-with-args-until-success
7231 'org-create-file-search-functions))
7232 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7233 "::" search))
7234 (setq cpltxt (or description link)))
7236 ((eq major-mode 'image-mode)
7237 (setq cpltxt (concat "file:"
7238 (abbreviate-file-name buffer-file-name))
7239 link (org-make-link cpltxt))
7240 (org-store-link-props :type "image" :file buffer-file-name))
7242 ((eq major-mode 'dired-mode)
7243 ;; link to the file in the current line
7244 (setq cpltxt (concat "file:"
7245 (abbreviate-file-name
7246 (expand-file-name
7247 (dired-get-filename nil t))))
7248 link (org-make-link cpltxt)))
7250 ((and buffer-file-name (org-mode-p))
7251 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7252 (cond
7253 ((org-in-regexp "<<\\(.*?\\)>>")
7254 (setq cpltxt
7255 (concat "file:"
7256 (abbreviate-file-name buffer-file-name)
7257 "::" (match-string 1))
7258 link (org-make-link cpltxt)))
7259 ((and (featurep 'org-id)
7260 (or (eq org-link-to-org-use-id t)
7261 (and (eq org-link-to-org-use-id 'create-if-interactive)
7262 (interactive-p))
7263 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7264 (interactive-p)
7265 (not custom-id))
7266 (and org-link-to-org-use-id
7267 (condition-case nil
7268 (org-entry-get nil "ID")
7269 (error nil)))))
7270 ;; We can make a link using the ID.
7271 (setq link (condition-case nil
7272 (prog1 (org-id-store-link)
7273 (setq desc (plist-get org-store-link-plist
7274 :description)))
7275 (error
7276 ;; probably before first headline, link to file only
7277 (concat "file:"
7278 (abbreviate-file-name buffer-file-name))))))
7280 ;; Just link to current headline
7281 (setq cpltxt (concat "file:"
7282 (abbreviate-file-name buffer-file-name)))
7283 ;; Add a context search string
7284 (when (org-xor org-context-in-file-links arg)
7285 (setq txt (cond
7286 ((org-on-heading-p) nil)
7287 ((org-region-active-p)
7288 (buffer-substring (region-beginning) (region-end)))
7289 (t nil)))
7290 (when (or (null txt) (string-match "\\S-" txt))
7291 (setq cpltxt
7292 (concat cpltxt "::"
7293 (condition-case nil
7294 (org-make-org-heading-search-string txt)
7295 (error "")))
7296 desc (or (nth 4 (ignore-errors
7297 (org-heading-components))) "NONE"))))
7298 (if (string-match "::\\'" cpltxt)
7299 (setq cpltxt (substring cpltxt 0 -2)))
7300 (setq link (org-make-link cpltxt)))))
7302 ((buffer-file-name (buffer-base-buffer))
7303 ;; Just link to this file here.
7304 (setq cpltxt (concat "file:"
7305 (abbreviate-file-name
7306 (buffer-file-name (buffer-base-buffer)))))
7307 ;; Add a context string
7308 (when (org-xor org-context-in-file-links arg)
7309 (setq txt (if (org-region-active-p)
7310 (buffer-substring (region-beginning) (region-end))
7311 (buffer-substring (point-at-bol) (point-at-eol))))
7312 ;; Only use search option if there is some text.
7313 (when (string-match "\\S-" txt)
7314 (setq cpltxt
7315 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7316 desc "NONE")))
7317 (setq link (org-make-link cpltxt)))
7319 ((interactive-p)
7320 (error "Cannot link to a buffer which is not visiting a file"))
7322 (t (setq link nil)))
7324 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7325 (setq link (or link cpltxt)
7326 desc (or desc cpltxt))
7327 (if (equal desc "NONE") (setq desc nil))
7329 (if (and (or (interactive-p) executing-kbd-macro) link)
7330 (progn
7331 (setq org-stored-links
7332 (cons (list link desc) org-stored-links))
7333 (message "Stored: %s" (or desc link))
7334 (when custom-id
7335 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7336 "::#" custom-id))
7337 (setq org-stored-links
7338 (cons (list link desc) org-stored-links))))
7339 (and link (org-make-link-string link desc)))))
7341 (defun org-store-link-props (&rest plist)
7342 "Store link properties, extract names and addresses."
7343 (let (x adr)
7344 (when (setq x (plist-get plist :from))
7345 (setq adr (mail-extract-address-components x))
7346 (setq plist (plist-put plist :fromname (car adr)))
7347 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7348 (when (setq x (plist-get plist :to))
7349 (setq adr (mail-extract-address-components x))
7350 (setq plist (plist-put plist :toname (car adr)))
7351 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7352 (let ((from (plist-get plist :from))
7353 (to (plist-get plist :to)))
7354 (when (and from to org-from-is-user-regexp)
7355 (setq plist
7356 (plist-put plist :fromto
7357 (if (string-match org-from-is-user-regexp from)
7358 (concat "to %t")
7359 (concat "from %f"))))))
7360 (setq org-store-link-plist plist))
7362 (defun org-add-link-props (&rest plist)
7363 "Add these properties to the link property list."
7364 (let (key value)
7365 (while plist
7366 (setq key (pop plist) value (pop plist))
7367 (setq org-store-link-plist
7368 (plist-put org-store-link-plist key value)))))
7370 (defun org-email-link-description (&optional fmt)
7371 "Return the description part of an email link.
7372 This takes information from `org-store-link-plist' and formats it
7373 according to FMT (default from `org-email-link-description-format')."
7374 (setq fmt (or fmt org-email-link-description-format))
7375 (let* ((p org-store-link-plist)
7376 (to (plist-get p :toaddress))
7377 (from (plist-get p :fromaddress))
7378 (table
7379 (list
7380 (cons "%c" (plist-get p :fromto))
7381 (cons "%F" (plist-get p :from))
7382 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7383 (cons "%T" (plist-get p :to))
7384 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7385 (cons "%s" (plist-get p :subject))
7386 (cons "%m" (plist-get p :message-id)))))
7387 (when (string-match "%c" fmt)
7388 ;; Check if the user wrote this message
7389 (if (and org-from-is-user-regexp from to
7390 (save-match-data (string-match org-from-is-user-regexp from)))
7391 (setq fmt (replace-match "to %t" t t fmt))
7392 (setq fmt (replace-match "from %f" t t fmt))))
7393 (org-replace-escapes fmt table)))
7395 (defun org-make-org-heading-search-string (&optional string heading)
7396 "Make search string for STRING or current headline."
7397 (interactive)
7398 (let ((s (or string (org-get-heading))))
7399 (unless (and string (not heading))
7400 ;; We are using a headline, clean up garbage in there.
7401 (if (string-match org-todo-regexp s)
7402 (setq s (replace-match "" t t s)))
7403 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7404 (setq s (replace-match "" t t s)))
7405 (setq s (org-trim s))
7406 (if (string-match (concat "^\\(" org-quote-string "\\|"
7407 org-comment-string "\\)") s)
7408 (setq s (replace-match "" t t s)))
7409 (while (string-match org-ts-regexp s)
7410 (setq s (replace-match "" t t s))))
7411 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7412 (setq s (replace-match " " t t s)))
7413 (or string (setq s (concat "*" s))) ; Add * for headlines
7414 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7416 (defun org-make-link (&rest strings)
7417 "Concatenate STRINGS."
7418 (apply 'concat strings))
7420 (defun org-make-link-string (link &optional description)
7421 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7422 (unless (string-match "\\S-" link)
7423 (error "Empty link"))
7424 (when (stringp description)
7425 ;; Remove brackets from the description, they are fatal.
7426 (while (string-match "\\[" description)
7427 (setq description (replace-match "{" t t description)))
7428 (while (string-match "\\]" description)
7429 (setq description (replace-match "}" t t description))))
7430 (when (equal (org-link-escape link) description)
7431 ;; No description needed, it is identical
7432 (setq description nil))
7433 (when (and (not description)
7434 (not (equal link (org-link-escape link))))
7435 (setq description (org-extract-attributes link)))
7436 (concat "[[" (org-link-escape link) "]"
7437 (if description (concat "[" description "]") "")
7438 "]"))
7440 (defconst org-link-escape-chars
7441 '((?\ . "%20")
7442 (?\[ . "%5B")
7443 (?\] . "%5D")
7444 (?\340 . "%E0") ; `a
7445 (?\342 . "%E2") ; ^a
7446 (?\347 . "%E7") ; ,c
7447 (?\350 . "%E8") ; `e
7448 (?\351 . "%E9") ; 'e
7449 (?\352 . "%EA") ; ^e
7450 (?\356 . "%EE") ; ^i
7451 (?\364 . "%F4") ; ^o
7452 (?\371 . "%F9") ; `u
7453 (?\373 . "%FB") ; ^u
7454 (?\; . "%3B")
7455 (?? . "%3F")
7456 (?= . "%3D")
7457 (?+ . "%2B")
7459 "Association list of escapes for some characters problematic in links.
7460 This is the list that is used for internal purposes.")
7462 (defvar org-url-encoding-use-url-hexify nil)
7464 (defconst org-link-escape-chars-browser
7465 '((?\ . "%20")) ; 32 for the SPC char
7466 "Association list of escapes for some characters problematic in links.
7467 This is the list that is used before handing over to the browser.")
7469 (defun org-link-escape (text &optional table)
7470 "Escape characters in TEXT that are problematic for links."
7471 (if org-url-encoding-use-url-hexify
7472 (url-hexify-string text)
7473 (setq table (or table org-link-escape-chars))
7474 (when text
7475 (let ((re (mapconcat (lambda (x) (regexp-quote
7476 (char-to-string (car x))))
7477 table "\\|")))
7478 (while (string-match re text)
7479 (setq text
7480 (replace-match
7481 (cdr (assoc (string-to-char (match-string 0 text))
7482 table))
7483 t t text)))
7484 text))))
7486 (defun org-link-unescape (text &optional table)
7487 "Reverse the action of `org-link-escape'."
7488 (if org-url-encoding-use-url-hexify
7489 (url-unhex-string text)
7490 (setq table (or table org-link-escape-chars))
7491 (when text
7492 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7493 table "\\|")))
7494 (while (string-match re text)
7495 (setq text
7496 (replace-match
7497 (char-to-string (car (rassoc (match-string 0 text) table)))
7498 t t text)))
7499 text))))
7501 (defun org-xor (a b)
7502 "Exclusive or."
7503 (if a (not b) b))
7505 (defun org-fixup-message-id-for-http (s)
7506 "Replace special characters in a message id, so it can be used in an http query."
7507 (while (string-match "<" s)
7508 (setq s (replace-match "%3C" t t s)))
7509 (while (string-match ">" s)
7510 (setq s (replace-match "%3E" t t s)))
7511 (while (string-match "@" s)
7512 (setq s (replace-match "%40" t t s)))
7515 ;;;###autoload
7516 (defun org-insert-link-global ()
7517 "Insert a link like Org-mode does.
7518 This command can be called in any mode to insert a link in Org-mode syntax."
7519 (interactive)
7520 (org-load-modules-maybe)
7521 (org-run-like-in-org-mode 'org-insert-link))
7523 (defun org-insert-link (&optional complete-file link-location)
7524 "Insert a link. At the prompt, enter the link.
7526 Completion can be used to insert any of the link protocol prefixes like
7527 http or ftp in use.
7529 The history can be used to select a link previously stored with
7530 `org-store-link'. When the empty string is entered (i.e. if you just
7531 press RET at the prompt), the link defaults to the most recently
7532 stored link. As SPC triggers completion in the minibuffer, you need to
7533 use M-SPC or C-q SPC to force the insertion of a space character.
7535 You will also be prompted for a description, and if one is given, it will
7536 be displayed in the buffer instead of the link.
7538 If there is already a link at point, this command will allow you to edit link
7539 and description parts.
7541 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7542 be selected using completion. The path to the file will be relative to the
7543 current directory if the file is in the current directory or a subdirectory.
7544 Otherwise, the link will be the absolute path as completed in the minibuffer
7545 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7546 option `org-link-file-path-type'.
7548 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7549 the current directory or below.
7551 With three \\[universal-argument] prefixes, negate the meaning of
7552 `org-keep-stored-link-after-insertion'.
7554 If `org-make-link-description-function' is non-nil, this function will be
7555 called with the link target, and the result will be the default
7556 link description.
7558 If the LINK-LOCATION parameter is non-nil, this value will be
7559 used as the link location instead of reading one interactively."
7560 (interactive "P")
7561 (let* ((wcf (current-window-configuration))
7562 (region (if (org-region-active-p)
7563 (buffer-substring (region-beginning) (region-end))))
7564 (remove (and region (list (region-beginning) (region-end))))
7565 (desc region)
7566 tmphist ; byte-compile incorrectly complains about this
7567 (link link-location)
7568 entry file all-prefixes)
7569 (cond
7570 (link-location) ; specified by arg, just use it.
7571 ((org-in-regexp org-bracket-link-regexp 1)
7572 ;; We do have a link at point, and we are going to edit it.
7573 (setq remove (list (match-beginning 0) (match-end 0)))
7574 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7575 (setq link (read-string "Link: "
7576 (org-link-unescape
7577 (org-match-string-no-properties 1)))))
7578 ((or (org-in-regexp org-angle-link-re)
7579 (org-in-regexp org-plain-link-re))
7580 ;; Convert to bracket link
7581 (setq remove (list (match-beginning 0) (match-end 0))
7582 link (read-string "Link: "
7583 (org-remove-angle-brackets (match-string 0)))))
7584 ((member complete-file '((4) (16)))
7585 ;; Completing read for file names.
7586 (setq link (org-file-complete-link complete-file)))
7588 ;; Read link, with completion for stored links.
7589 (with-output-to-temp-buffer "*Org Links*"
7590 (princ "Insert a link.
7591 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7592 (when org-stored-links
7593 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7594 (princ (mapconcat
7595 (lambda (x)
7596 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7597 (reverse org-stored-links) "\n"))))
7598 (let ((cw (selected-window)))
7599 (select-window (get-buffer-window "*Org Links*"))
7600 (setq truncate-lines t)
7601 (unless (pos-visible-in-window-p (point-max))
7602 (org-fit-window-to-buffer))
7603 (and (window-live-p cw) (select-window cw)))
7604 ;; Fake a link history, containing the stored links.
7605 (setq tmphist (append (mapcar 'car org-stored-links)
7606 org-insert-link-history))
7607 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7608 (mapcar 'car org-link-abbrev-alist)
7609 org-link-types))
7610 (unwind-protect
7611 (progn
7612 (setq link
7613 (let ((org-completion-use-ido nil)
7614 (org-completion-use-iswitchb nil))
7615 (org-completing-read
7616 "Link: "
7617 (append
7618 (mapcar (lambda (x) (list (concat x ":")))
7619 all-prefixes)
7620 (mapcar 'car org-stored-links))
7621 nil nil nil
7622 'tmphist
7623 (car (car org-stored-links)))))
7624 (if (or (member link all-prefixes)
7625 (and (equal ":" (substring link -1))
7626 (member (substring link 0 -1) all-prefixes)
7627 (setq link (substring link 0 -1))))
7628 (setq link (org-link-try-special-completion link))))
7629 (set-window-configuration wcf)
7630 (kill-buffer "*Org Links*"))
7631 (setq entry (assoc link org-stored-links))
7632 (or entry (push link org-insert-link-history))
7633 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7634 (not org-keep-stored-link-after-insertion))
7635 (setq org-stored-links (delq (assoc link org-stored-links)
7636 org-stored-links)))
7637 (setq desc (or desc (nth 1 entry)))))
7639 (if (string-match org-plain-link-re link)
7640 ;; URL-like link, normalize the use of angular brackets.
7641 (setq link (org-make-link (org-remove-angle-brackets link))))
7643 ;; Check if we are linking to the current file with a search option
7644 ;; If yes, simplify the link by using only the search option.
7645 (when (and buffer-file-name
7646 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7647 (let* ((path (match-string 1 link))
7648 (case-fold-search nil)
7649 (search (match-string 2 link)))
7650 (save-match-data
7651 (if (equal (file-truename buffer-file-name) (file-truename path))
7652 ;; We are linking to this same file, with a search option
7653 (setq link search)))))
7655 ;; Check if we can/should use a relative path. If yes, simplify the link
7656 (when (string-match "^file:\\(.*\\)" link)
7657 (let* ((path (match-string 1 link))
7658 (origpath path)
7659 (case-fold-search nil))
7660 (cond
7661 ((or (eq org-link-file-path-type 'absolute)
7662 (equal complete-file '(16)))
7663 (setq path (abbreviate-file-name (expand-file-name path))))
7664 ((eq org-link-file-path-type 'noabbrev)
7665 (setq path (expand-file-name path)))
7666 ((eq org-link-file-path-type 'relative)
7667 (setq path (file-relative-name path)))
7669 (save-match-data
7670 (if (string-match (concat "^" (regexp-quote
7671 (file-name-as-directory
7672 (expand-file-name "."))))
7673 (expand-file-name path))
7674 ;; We are linking a file with relative path name.
7675 (setq path (substring (expand-file-name path)
7676 (match-end 0)))
7677 (setq path (abbreviate-file-name (expand-file-name path)))))))
7678 (setq link (concat "file:" path))
7679 (if (equal desc origpath)
7680 (setq desc path))))
7682 (if org-make-link-description-function
7683 (setq desc (funcall org-make-link-description-function link desc)))
7685 (setq desc (read-string "Description: " desc))
7686 (unless (string-match "\\S-" desc) (setq desc nil))
7687 (if remove (apply 'delete-region remove))
7688 (insert (org-make-link-string link desc))))
7690 (defun org-link-try-special-completion (type)
7691 "If there is completion support for link type TYPE, offer it."
7692 (let ((fun (intern (concat "org-" type "-complete-link"))))
7693 (if (functionp fun)
7694 (funcall fun)
7695 (read-string "Link (no completion support): " (concat type ":")))))
7697 (defun org-file-complete-link (&optional arg)
7698 "Create a file link using completion."
7699 (let (file link)
7700 (setq file (read-file-name "File: "))
7701 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7702 (pwd1 (file-name-as-directory (abbreviate-file-name
7703 (expand-file-name ".")))))
7704 (cond
7705 ((equal arg '(16))
7706 (setq link (org-make-link
7707 "file:"
7708 (abbreviate-file-name (expand-file-name file)))))
7709 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7710 (setq link (org-make-link "file:" (match-string 1 file))))
7711 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7712 (expand-file-name file))
7713 (setq link (org-make-link
7714 "file:" (match-string 1 (expand-file-name file)))))
7715 (t (setq link (org-make-link "file:" file)))))
7716 link))
7718 (defun org-completing-read (&rest args)
7719 "Completing-read with SPACE being a normal character."
7720 (let ((minibuffer-local-completion-map
7721 (copy-keymap minibuffer-local-completion-map)))
7722 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7723 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7724 (apply 'org-icompleting-read args)))
7726 (defun org-completing-read-no-i (&rest args)
7727 (let (org-completion-use-ido org-completion-use-iswitchb)
7728 (apply 'org-completing-read args)))
7730 (defun org-iswitchb-completing-read (prompt choices &rest args)
7731 "Use iswitch as a completing-read replacement to choose from choices.
7732 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7733 from."
7734 (let* ((iswitchb-use-virtual-buffers nil)
7735 (iswitchb-make-buflist-hook
7736 (lambda ()
7737 (setq iswitchb-temp-buflist choices))))
7738 (iswitchb-read-buffer prompt)))
7740 (defun org-icompleting-read (&rest args)
7741 "Completing-read using `ido-mode' or `iswitchb' speedups if available"
7742 (if (and org-completion-use-ido
7743 (fboundp 'ido-completing-read)
7744 (boundp 'ido-mode) ido-mode
7745 (listp (second args)))
7746 (let ((ido-enter-matching-directory nil))
7747 (apply 'ido-completing-read (concat (car args))
7748 (if (consp (car (nth 1 args)))
7749 (mapcar (lambda (x) (car x)) (nth 1 args))
7750 (nth 1 args))
7751 (cddr args)))
7752 (if (and org-completion-use-iswitchb
7753 (boundp 'iswitchb-mode) iswitchb-mode
7754 (listp (second args)))
7755 (apply 'org-iswitchb-completing-read (concat (car args))
7756 (mapcar (lambda (x) (car x)) (nth 1 args))
7757 (cddr args))
7758 (apply 'completing-read args))))
7760 (defun org-extract-attributes (s)
7761 "Extract the attributes cookie from a string and set as text property."
7762 (let (a attr (start 0) key value)
7763 (save-match-data
7764 (when (string-match "{{\\([^}]+\\)}}$" s)
7765 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7766 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7767 (setq key (match-string 1 a) value (match-string 2 a)
7768 start (match-end 0)
7769 attr (plist-put attr (intern key) value))))
7770 (org-add-props s nil 'org-attr attr))
7773 (defun org-extract-attributes-from-string (tag)
7774 (let (key value attr)
7775 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7776 (setq key (match-string 1 tag) value (match-string 2 tag)
7777 tag (replace-match "" t t tag)
7778 attr (plist-put attr (intern key) value)))
7779 (cons tag attr)))
7781 (defun org-attributes-to-string (plist)
7782 "Format a property list into an HTML attribute list."
7783 (let ((s "") key value)
7784 (while plist
7785 (setq key (pop plist) value (pop plist))
7786 (and value
7787 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7790 ;;; Opening/following a link
7792 (defvar org-link-search-failed nil)
7794 (defun org-next-link ()
7795 "Move forward to the next link.
7796 If the link is in hidden text, expose it."
7797 (interactive)
7798 (when (and org-link-search-failed (eq this-command last-command))
7799 (goto-char (point-min))
7800 (message "Link search wrapped back to beginning of buffer"))
7801 (setq org-link-search-failed nil)
7802 (let* ((pos (point))
7803 (ct (org-context))
7804 (a (assoc :link ct)))
7805 (if a (goto-char (nth 2 a)))
7806 (if (re-search-forward org-any-link-re nil t)
7807 (progn
7808 (goto-char (match-beginning 0))
7809 (if (org-invisible-p) (org-show-context)))
7810 (goto-char pos)
7811 (setq org-link-search-failed t)
7812 (error "No further link found"))))
7814 (defun org-previous-link ()
7815 "Move backward to the previous link.
7816 If the link is in hidden text, expose it."
7817 (interactive)
7818 (when (and org-link-search-failed (eq this-command last-command))
7819 (goto-char (point-max))
7820 (message "Link search wrapped back to end of buffer"))
7821 (setq org-link-search-failed nil)
7822 (let* ((pos (point))
7823 (ct (org-context))
7824 (a (assoc :link ct)))
7825 (if a (goto-char (nth 1 a)))
7826 (if (re-search-backward org-any-link-re nil t)
7827 (progn
7828 (goto-char (match-beginning 0))
7829 (if (org-invisible-p) (org-show-context)))
7830 (goto-char pos)
7831 (setq org-link-search-failed t)
7832 (error "No further link found"))))
7834 (defun org-translate-link (s)
7835 "Translate a link string if a translation function has been defined."
7836 (if (and org-link-translation-function
7837 (fboundp org-link-translation-function)
7838 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7839 (progn
7840 (setq s (funcall org-link-translation-function
7841 (match-string 1) (match-string 2)))
7842 (concat (car s) ":" (cdr s)))
7845 (defun org-translate-link-from-planner (type path)
7846 "Translate a link from Emacs Planner syntax so that Org can follow it.
7847 This is still an experimental function, your mileage may vary."
7848 (cond
7849 ((member type '("http" "https" "news" "ftp"))
7850 ;; standard Internet links are the same.
7851 nil)
7852 ((and (equal type "irc") (string-match "^//" path))
7853 ;; Planner has two / at the beginning of an irc link, we have 1.
7854 ;; We should have zero, actually....
7855 (setq path (substring path 1)))
7856 ((and (equal type "lisp") (string-match "^/" path))
7857 ;; Planner has a slash, we do not.
7858 (setq type "elisp" path (substring path 1)))
7859 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7860 ;; A typical message link. Planner has the id after the fina slash,
7861 ;; we separate it with a hash mark
7862 (setq path (concat (match-string 1 path) "#"
7863 (org-remove-angle-brackets (match-string 2 path)))))
7865 (cons type path))
7867 (defun org-find-file-at-mouse (ev)
7868 "Open file link or URL at mouse."
7869 (interactive "e")
7870 (mouse-set-point ev)
7871 (org-open-at-point 'in-emacs))
7873 (defun org-open-at-mouse (ev)
7874 "Open file link or URL at mouse."
7875 (interactive "e")
7876 (mouse-set-point ev)
7877 (if (eq major-mode 'org-agenda-mode)
7878 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7879 (org-open-at-point))
7881 (defvar org-window-config-before-follow-link nil
7882 "The window configuration before following a link.
7883 This is saved in case the need arises to restore it.")
7885 (defvar org-open-link-marker (make-marker)
7886 "Marker pointing to the location where `org-open-at-point; was called.")
7888 ;;;###autoload
7889 (defun org-open-at-point-global ()
7890 "Follow a link like Org-mode does.
7891 This command can be called in any mode to follow a link that has
7892 Org-mode syntax."
7893 (interactive)
7894 (org-run-like-in-org-mode 'org-open-at-point))
7896 ;;;###autoload
7897 (defun org-open-link-from-string (s &optional arg reference-buffer)
7898 "Open a link in the string S, as if it was in Org-mode."
7899 (interactive "sLink: \nP")
7900 (let ((reference-buffer (or reference-buffer (current-buffer))))
7901 (with-temp-buffer
7902 (let ((org-inhibit-startup t))
7903 (org-mode)
7904 (insert s)
7905 (goto-char (point-min))
7906 (org-open-at-point arg reference-buffer)))))
7908 (defun org-open-at-point (&optional in-emacs reference-buffer)
7909 "Open link at or after point.
7910 If there is no link at point, this function will search forward up to
7911 the end of the current line.
7912 Normally, files will be opened by an appropriate application. If the
7913 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7914 With a double prefix argument, try to open outside of Emacs, in the
7915 application the system uses for this file type."
7916 (interactive "P")
7917 (org-load-modules-maybe)
7918 (move-marker org-open-link-marker (point))
7919 (setq org-window-config-before-follow-link (current-window-configuration))
7920 (org-remove-occur-highlights nil nil t)
7921 (cond
7922 ((and (org-on-heading-p)
7923 (not (org-in-regexp
7924 (concat org-plain-link-re "\\|"
7925 org-bracket-link-regexp "\\|"
7926 org-angle-link-re "\\|"
7927 "[ \t]:[^ \t\n]+:[ \t]*$"))))
7928 (org-offer-links-in-entry in-emacs))
7929 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7930 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7931 (org-footnote-action))
7933 (let (type path link line search (pos (point)))
7934 (catch 'match
7935 (save-excursion
7936 (skip-chars-forward "^]\n\r")
7937 (when (org-in-regexp org-bracket-link-regexp)
7938 (setq link (org-extract-attributes
7939 (org-link-unescape (org-match-string-no-properties 1))))
7940 (while (string-match " *\n *" link)
7941 (setq link (replace-match " " t t link)))
7942 (setq link (org-link-expand-abbrev link))
7943 (cond
7944 ((or (file-name-absolute-p link)
7945 (string-match "^\\.\\.?/" link))
7946 (setq type "file" path link))
7947 ((string-match org-link-re-with-space3 link)
7948 (setq type (match-string 1 link) path (match-string 2 link)))
7949 (t (setq type "thisfile" path link)))
7950 (throw 'match t)))
7952 (when (get-text-property (point) 'org-linked-text)
7953 (setq type "thisfile"
7954 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7955 (1+ (point)) (point))
7956 path (buffer-substring
7957 (previous-single-property-change pos 'org-linked-text)
7958 (next-single-property-change pos 'org-linked-text)))
7959 (throw 'match t))
7961 (save-excursion
7962 (when (or (org-in-regexp org-angle-link-re)
7963 (org-in-regexp org-plain-link-re))
7964 (setq type (match-string 1) path (match-string 2))
7965 (throw 'match t)))
7966 (save-excursion
7967 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7968 (setq type "tags"
7969 path (match-string 1))
7970 (while (string-match ":" path)
7971 (setq path (replace-match "+" t t path)))
7972 (throw 'match t)))
7973 (when (org-in-regexp "<\\([^><\n]+\\)>")
7974 (setq type "tree-match"
7975 path (match-string 1))
7976 (throw 'match t)))
7977 (unless path
7978 (error "No link found"))
7980 ;; switch back to reference buffer
7981 ;; needed when if called in a temporary buffer through
7982 ;; org-open-link-from-string
7983 (with-current-buffer (or reference-buffer (current-buffer))
7985 ;; Remove any trailing spaces in path
7986 (if (string-match " +\\'" path)
7987 (setq path (replace-match "" t t path)))
7988 (if (and org-link-translation-function
7989 (fboundp org-link-translation-function))
7990 ;; Check if we need to translate the link
7991 (let ((tmp (funcall org-link-translation-function type path)))
7992 (setq type (car tmp) path (cdr tmp))))
7994 (cond
7996 ((assoc type org-link-protocols)
7997 (funcall (nth 1 (assoc type org-link-protocols)) path))
7999 ((equal type "mailto")
8000 (let ((cmd (car org-link-mailto-program))
8001 (args (cdr org-link-mailto-program)) args1
8002 (address path) (subject "") a)
8003 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8004 (setq address (match-string 1 path)
8005 subject (org-link-escape (match-string 2 path))))
8006 (while args
8007 (cond
8008 ((not (stringp (car args))) (push (pop args) args1))
8009 (t (setq a (pop args))
8010 (if (string-match "%a" a)
8011 (setq a (replace-match address t t a)))
8012 (if (string-match "%s" a)
8013 (setq a (replace-match subject t t a)))
8014 (push a args1))))
8015 (apply cmd (nreverse args1))))
8017 ((member type '("http" "https" "ftp" "news"))
8018 (browse-url (concat type ":" (org-link-escape
8019 path org-link-escape-chars-browser))))
8021 ((member type '("message"))
8022 (browse-url (concat type ":" path)))
8024 ((string= type "tags")
8025 (org-tags-view in-emacs path))
8026 ((string= type "thisfile")
8027 (if in-emacs
8028 (switch-to-buffer-other-window
8029 (org-get-buffer-for-internal-link (current-buffer)))
8030 (org-mark-ring-push))
8031 (let ((cmd `(org-link-search
8032 ,path
8033 ,(cond ((equal in-emacs '(4)) 'occur)
8034 ((equal in-emacs '(16)) 'org-occur)
8035 (t nil))
8036 ,pos)))
8037 (condition-case nil (eval cmd)
8038 (error (progn (widen) (eval cmd))))))
8040 ((string= type "tree-match")
8041 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8043 ((string= type "file")
8044 (if (string-match "::\\([0-9]+\\)\\'" path)
8045 (setq line (string-to-number (match-string 1 path))
8046 path (substring path 0 (match-beginning 0)))
8047 (if (string-match "::\\(.+\\)\\'" path)
8048 (setq search (match-string 1 path)
8049 path (substring path 0 (match-beginning 0)))))
8050 (if (string-match "[*?{]" (file-name-nondirectory path))
8051 (dired path)
8052 (org-open-file path in-emacs line search)))
8054 ((string= type "news")
8055 (require 'org-gnus)
8056 (org-gnus-follow-link path))
8058 ((string= type "shell")
8059 (let ((cmd path))
8060 (if (or (not org-confirm-shell-link-function)
8061 (funcall org-confirm-shell-link-function
8062 (format "Execute \"%s\" in shell? "
8063 (org-add-props cmd nil
8064 'face 'org-warning))))
8065 (progn
8066 (message "Executing %s" cmd)
8067 (shell-command cmd))
8068 (error "Abort"))))
8070 ((string= type "elisp")
8071 (let ((cmd path))
8072 (if (or (not org-confirm-elisp-link-function)
8073 (funcall org-confirm-elisp-link-function
8074 (format "Execute \"%s\" as elisp? "
8075 (org-add-props cmd nil
8076 'face 'org-warning))))
8077 (message "%s => %s" cmd
8078 (if (equal (string-to-char cmd) ?\()
8079 (eval (read cmd))
8080 (call-interactively (read cmd))))
8081 (error "Abort"))))
8084 (browse-url-at-point))))))
8085 (move-marker org-open-link-marker nil)
8086 (run-hook-with-args 'org-follow-link-hook)))
8088 (defun org-offer-links-in-entry (&optional nth zero)
8089 "Offer links in the curren entry and follow the selected link.
8090 If there is only one link, follow it immediately as well.
8091 If NTH is an integer, immediately pick the NTH link found.
8092 If ZERO is a string, check also this string for a link, and if
8093 there is one, offer it as link number zero."
8094 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8095 "\\(" org-angle-link-re "\\)\\|"
8096 "\\(" org-plain-link-re "\\)"))
8097 (cnt ?0)
8098 (in-emacs (if (integerp nth) nil nth))
8099 have-zero end links link c)
8100 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8101 (push (match-string 0 zero) links)
8102 (setq cnt (1- cnt) have-zero t))
8103 (save-excursion
8104 (org-back-to-heading t)
8105 (setq end (save-excursion (outline-next-heading) (point)))
8106 (while (re-search-forward re end t)
8107 (push (match-string 0) links))
8108 (setq links (org-uniquify (reverse links))))
8110 (cond
8111 ((null links) (error "No links"))
8112 ((equal (length links) 1)
8113 (setq link (car links)))
8114 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8115 (setq link (nth (if have-zero nth (1- nth)) links)))
8116 (t ; we have to select a link
8117 (save-excursion
8118 (save-window-excursion
8119 (delete-other-windows)
8120 (with-output-to-temp-buffer "*Select Link*"
8121 (mapc (lambda (l)
8122 (if (not (string-match org-bracket-link-regexp l))
8123 (princ (format "[%c] %s\n" (incf cnt)
8124 (org-remove-angle-brackets l)))
8125 (if (match-end 3)
8126 (princ (format "[%c] %s (%s)\n" (incf cnt)
8127 (match-string 3 l) (match-string 1 l)))
8128 (princ (format "[%c] %s\n" (incf cnt)
8129 (match-string 1 l))))))
8130 links))
8131 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8132 (message "Select link to open:")
8133 (setq c (read-char-exclusive))
8134 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8135 (when (equal c ?q) (error "Abort"))
8136 (setq nth (- c ?0))
8137 (if have-zero (setq nth (1+ nth)))
8138 (unless (and (integerp nth) (>= (length links) nth))
8139 (error "Invalid link selection"))
8140 (setq link (nth (1- nth) links))))
8141 (org-open-link-from-string link in-emacs (current-buffer))))
8143 ;;;; Time estimates
8145 (defun org-get-effort (&optional pom)
8146 "Get the effort estimate for the current entry."
8147 (org-entry-get pom org-effort-property))
8149 ;;; File search
8151 (defvar org-create-file-search-functions nil
8152 "List of functions to construct the right search string for a file link.
8153 These functions are called in turn with point at the location to
8154 which the link should point.
8156 A function in the hook should first test if it would like to
8157 handle this file type, for example by checking the major-mode or
8158 the file extension. If it decides not to handle this file, it
8159 should just return nil to give other functions a chance. If it
8160 does handle the file, it must return the search string to be used
8161 when following the link. The search string will be part of the
8162 file link, given after a double colon, and `org-open-at-point'
8163 will automatically search for it. If special measures must be
8164 taken to make the search successful, another function should be
8165 added to the companion hook `org-execute-file-search-functions',
8166 which see.
8168 A function in this hook may also use `setq' to set the variable
8169 `description' to provide a suggestion for the descriptive text to
8170 be used for this link when it gets inserted into an Org-mode
8171 buffer with \\[org-insert-link].")
8173 (defvar org-execute-file-search-functions nil
8174 "List of functions to execute a file search triggered by a link.
8176 Functions added to this hook must accept a single argument, the
8177 search string that was part of the file link, the part after the
8178 double colon. The function must first check if it would like to
8179 handle this search, for example by checking the major-mode or the
8180 file extension. If it decides not to handle this search, it
8181 should just return nil to give other functions a chance. If it
8182 does handle the search, it must return a non-nil value to keep
8183 other functions from trying.
8185 Each function can access the current prefix argument through the
8186 variable `current-prefix-argument'. Note that a single prefix is
8187 used to force opening a link in Emacs, so it may be good to only
8188 use a numeric or double prefix to guide the search function.
8190 In case this is needed, a function in this hook can also restore
8191 the window configuration before `org-open-at-point' was called using:
8193 (set-window-configuration org-window-config-before-follow-link)")
8195 (defun org-link-search (s &optional type avoid-pos)
8196 "Search for a link search option.
8197 If S is surrounded by forward slashes, it is interpreted as a
8198 regular expression. In org-mode files, this will create an `org-occur'
8199 sparse tree. In ordinary files, `occur' will be used to list matches.
8200 If the current buffer is in `dired-mode', grep will be used to search
8201 in all files. If AVOID-POS is given, ignore matches near that position."
8202 (let ((case-fold-search t)
8203 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8204 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8205 (append '(("") (" ") ("\t") ("\n"))
8206 org-emphasis-alist)
8207 "\\|") "\\)"))
8208 (pos (point))
8209 (pre nil) (post nil)
8210 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8211 (cond
8212 ;; First check if there are any special
8213 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8214 ;; Now try the builtin stuff
8215 ((and (equal (string-to-char s0) ?#)
8216 (> (length s0) 1)
8217 (save-excursion
8218 (goto-char (point-min))
8219 (and
8220 (re-search-forward
8221 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8222 (setq type 'dedicated
8223 pos (match-beginning 0))))
8224 ;; There is an exact target for this
8225 (goto-char pos)
8226 (org-back-to-heading t)))
8227 ((save-excursion
8228 (goto-char (point-min))
8229 (and
8230 (re-search-forward
8231 (concat "<<" (regexp-quote s0) ">>") nil t)
8232 (setq type 'dedicated
8233 pos (match-beginning 0))))
8234 ;; There is an exact target for this
8235 (goto-char pos))
8236 ((and (string-match "^(\\(.*\\))$" s0)
8237 (save-excursion
8238 (goto-char (point-min))
8239 (and
8240 (re-search-forward
8241 (concat "[^[]" (regexp-quote
8242 (format org-coderef-label-format
8243 (match-string 1 s0))))
8244 nil t)
8245 (setq type 'dedicated
8246 pos (1+ (match-beginning 0))))))
8247 ;; There is a coderef target for this
8248 (goto-char pos))
8249 ((string-match "^/\\(.*\\)/$" s)
8250 ;; A regular expression
8251 (cond
8252 ((org-mode-p)
8253 (org-occur (match-string 1 s)))
8254 ;;((eq major-mode 'dired-mode)
8255 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8256 (t (org-do-occur (match-string 1 s)))))
8258 ;; A normal search strings
8259 (when (equal (string-to-char s) ?*)
8260 ;; Anchor on headlines, post may include tags.
8261 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8262 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8263 s (substring s 1)))
8264 (remove-text-properties
8265 0 (length s)
8266 '(face nil mouse-face nil keymap nil fontified nil) s)
8267 ;; Make a series of regular expressions to find a match
8268 (setq words (org-split-string s "[ \n\r\t]+")
8270 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8271 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8272 "\\)" markers)
8273 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8274 re2a (concat "[ \t\r\n]" re2a_)
8275 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8276 re4 (concat "[^a-zA-Z_]" re4_)
8278 re1 (concat pre re2 post)
8279 re3 (concat pre (if pre re4_ re4) post)
8280 re5 (concat pre ".*" re4)
8281 re2 (concat pre re2)
8282 re2a (concat pre (if pre re2a_ re2a))
8283 re4 (concat pre (if pre re4_ re4))
8284 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8285 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8286 re5 "\\)"
8288 (cond
8289 ((eq type 'org-occur) (org-occur reall))
8290 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8291 (t (goto-char (point-min))
8292 (setq type 'fuzzy)
8293 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8294 (org-search-not-self 1 re1 nil t)
8295 (org-search-not-self 1 re2 nil t)
8296 (org-search-not-self 1 re2a nil t)
8297 (org-search-not-self 1 re3 nil t)
8298 (org-search-not-self 1 re4 nil t)
8299 (org-search-not-self 1 re5 nil t)
8301 (goto-char (match-beginning 1))
8302 (goto-char pos)
8303 (error "No match")))))
8305 ;; Normal string-search
8306 (goto-char (point-min))
8307 (if (search-forward s nil t)
8308 (goto-char (match-beginning 0))
8309 (error "No match"))))
8310 (and (org-mode-p) (org-show-context 'link-search))
8311 type))
8313 (defun org-search-not-self (group &rest args)
8314 "Execute `re-search-forward', but only accept matches that do not
8315 enclose the position of `org-open-link-marker'."
8316 (let ((m org-open-link-marker))
8317 (catch 'exit
8318 (while (apply 're-search-forward args)
8319 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8320 (goto-char (match-end group))
8321 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8322 (> (match-beginning 0) (marker-position m))
8323 (< (match-end 0) (marker-position m)))
8324 (save-match-data
8325 (or (not (org-in-regexp
8326 org-bracket-link-analytic-regexp 1))
8327 (not (match-end 4)) ; no description
8328 (and (<= (match-beginning 4) (point))
8329 (>= (match-end 4) (point))))))
8330 (throw 'exit (point))))))))
8332 (defun org-get-buffer-for-internal-link (buffer)
8333 "Return a buffer to be used for displaying the link target of internal links."
8334 (cond
8335 ((not org-display-internal-link-with-indirect-buffer)
8336 buffer)
8337 ((string-match "(Clone)$" (buffer-name buffer))
8338 (message "Buffer is already a clone, not making another one")
8339 ;; we also do not modify visibility in this case
8340 buffer)
8341 (t ; make a new indirect buffer for displaying the link
8342 (let* ((bn (buffer-name buffer))
8343 (ibn (concat bn "(Clone)"))
8344 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8345 (with-current-buffer ib (org-overview))
8346 ib))))
8348 (defun org-do-occur (regexp &optional cleanup)
8349 "Call the Emacs command `occur'.
8350 If CLEANUP is non-nil, remove the printout of the regular expression
8351 in the *Occur* buffer. This is useful if the regex is long and not useful
8352 to read."
8353 (occur regexp)
8354 (when cleanup
8355 (let ((cwin (selected-window)) win beg end)
8356 (when (setq win (get-buffer-window "*Occur*"))
8357 (select-window win))
8358 (goto-char (point-min))
8359 (when (re-search-forward "match[a-z]+" nil t)
8360 (setq beg (match-end 0))
8361 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8362 (setq end (1- (match-beginning 0)))))
8363 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8364 (goto-char (point-min))
8365 (select-window cwin))))
8367 ;;; The mark ring for links jumps
8369 (defvar org-mark-ring nil
8370 "Mark ring for positions before jumps in Org-mode.")
8371 (defvar org-mark-ring-last-goto nil
8372 "Last position in the mark ring used to go back.")
8373 ;; Fill and close the ring
8374 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8375 (loop for i from 1 to org-mark-ring-length do
8376 (push (make-marker) org-mark-ring))
8377 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8378 org-mark-ring)
8380 (defun org-mark-ring-push (&optional pos buffer)
8381 "Put the current position or POS into the mark ring and rotate it."
8382 (interactive)
8383 (setq pos (or pos (point)))
8384 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8385 (move-marker (car org-mark-ring)
8386 (or pos (point))
8387 (or buffer (current-buffer)))
8388 (message "%s"
8389 (substitute-command-keys
8390 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8392 (defun org-mark-ring-goto (&optional n)
8393 "Jump to the previous position in the mark ring.
8394 With prefix arg N, jump back that many stored positions. When
8395 called several times in succession, walk through the entire ring.
8396 Org-mode commands jumping to a different position in the current file,
8397 or to another Org-mode file, automatically push the old position
8398 onto the ring."
8399 (interactive "p")
8400 (let (p m)
8401 (if (eq last-command this-command)
8402 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8403 (setq p org-mark-ring))
8404 (setq org-mark-ring-last-goto p)
8405 (setq m (car p))
8406 (switch-to-buffer (marker-buffer m))
8407 (goto-char m)
8408 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8410 (defun org-remove-angle-brackets (s)
8411 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8412 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8414 (defun org-add-angle-brackets (s)
8415 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8416 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8418 (defun org-remove-double-quotes (s)
8419 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8420 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8423 ;;; Following specific links
8425 (defun org-follow-timestamp-link ()
8426 (cond
8427 ((org-at-date-range-p t)
8428 (let ((org-agenda-start-on-weekday)
8429 (t1 (match-string 1))
8430 (t2 (match-string 2)))
8431 (setq t1 (time-to-days (org-time-string-to-time t1))
8432 t2 (time-to-days (org-time-string-to-time t2)))
8433 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8434 ((org-at-timestamp-p t)
8435 (org-agenda-list nil (time-to-days (org-time-string-to-time
8436 (substring (match-string 1) 0 10)))
8438 (t (error "This should not happen"))))
8441 ;;; Following file links
8442 (defvar org-wait nil)
8443 (defun org-open-file (path &optional in-emacs line search)
8444 "Open the file at PATH.
8445 First, this expands any special file name abbreviations. Then the
8446 configuration variable `org-file-apps' is checked if it contains an
8447 entry for this file type, and if yes, the corresponding command is launched.
8449 If no application is found, Emacs simply visits the file.
8451 With optional prefix argument IN-EMACS, Emacs will visit the file.
8452 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8453 and o use an external application to visit the file.
8455 Optional LINE specifies a line to go to, optional SEARCH a string to
8456 search for. If LINE or SEARCH is given, the file will always be
8457 opened in Emacs.
8458 If the file does not exist, an error is thrown."
8459 (setq in-emacs (or in-emacs line search))
8460 (let* ((file (if (equal path "")
8461 buffer-file-name
8462 (substitute-in-file-name (expand-file-name path))))
8463 (apps (append org-file-apps (org-default-apps)))
8464 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8465 (dirp (if remp nil (file-directory-p file)))
8466 (file (if (and dirp org-open-directory-means-index-dot-org)
8467 (concat (file-name-as-directory file) "index.org")
8468 file))
8469 (a-m-a-p (assq 'auto-mode apps))
8470 (dfile (downcase file))
8471 (old-buffer (current-buffer))
8472 (old-pos (point))
8473 (old-mode major-mode)
8474 ext cmd)
8475 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8476 (setq ext (match-string 1 dfile))
8477 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8478 (setq ext (match-string 1 dfile))))
8479 (cond
8480 ((equal in-emacs '(16))
8481 (setq cmd (cdr (assoc 'system apps))))
8482 (in-emacs (setq cmd 'emacs))
8484 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8485 (and dirp (cdr (assoc 'directory apps)))
8486 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8487 'string-match)
8488 (cdr (assoc ext apps))
8489 (cdr (assoc t apps))))))
8490 (when (eq cmd 'system)
8491 (setq cmd (cdr (assoc 'system apps))))
8492 (when (eq cmd 'default)
8493 (setq cmd (cdr (assoc t apps))))
8494 (when (eq cmd 'mailcap)
8495 (require 'mailcap)
8496 (mailcap-parse-mailcaps)
8497 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8498 (command (mailcap-mime-info mime-type)))
8499 (if (stringp command)
8500 (setq cmd command)
8501 (setq cmd 'emacs))))
8502 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8503 (not (file-exists-p file))
8504 (not org-open-non-existing-files))
8505 (error "No such file: %s" file))
8506 (cond
8507 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8508 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8509 (while (string-match "['\"]%s['\"]" cmd)
8510 (setq cmd (replace-match "%s" t t cmd)))
8511 (while (string-match "%s" cmd)
8512 (setq cmd (replace-match
8513 (save-match-data
8514 (shell-quote-argument
8515 (convert-standard-filename file)))
8516 t t cmd)))
8517 (save-window-excursion
8518 (start-process-shell-command cmd nil cmd)
8519 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8521 ((or (stringp cmd)
8522 (eq cmd 'emacs))
8523 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8524 (widen)
8525 (if line (org-goto-line line)
8526 (if search (org-link-search search))))
8527 ((consp cmd)
8528 (let ((file (convert-standard-filename file)))
8529 (eval cmd)))
8530 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8531 (and (org-mode-p) (eq old-mode 'org-mode)
8532 (or (not (equal old-buffer (current-buffer)))
8533 (not (equal old-pos (point))))
8534 (org-mark-ring-push old-pos old-buffer))))
8536 (defun org-default-apps ()
8537 "Return the default applications for this operating system."
8538 (cond
8539 ((eq system-type 'darwin)
8540 org-file-apps-defaults-macosx)
8541 ((eq system-type 'windows-nt)
8542 org-file-apps-defaults-windowsnt)
8543 (t org-file-apps-defaults-gnu)))
8545 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8546 "Convert extensions to regular expressions in the cars of LIST.
8547 Also, weed out any non-string entries, because the return value is used
8548 only for regexp matching.
8549 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8550 point to the symbol `emacs', indicating that the file should
8551 be opened in Emacs."
8552 (append
8553 (delq nil
8554 (mapcar (lambda (x)
8555 (if (not (stringp (car x)))
8557 (if (string-match "\\W" (car x))
8559 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8560 list))
8561 (if add-auto-mode
8562 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8564 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8565 (defun org-file-remote-p (file)
8566 "Test whether FILE specifies a location on a remote system.
8567 Return non-nil if the location is indeed remote.
8569 For example, the filename \"/user@host:/foo\" specifies a location
8570 on the system \"/user@host:\"."
8571 (cond ((fboundp 'file-remote-p)
8572 (file-remote-p file))
8573 ((fboundp 'tramp-handle-file-remote-p)
8574 (tramp-handle-file-remote-p file))
8575 ((and (boundp 'ange-ftp-name-format)
8576 (string-match (car ange-ftp-name-format) file))
8578 (t nil)))
8581 ;;;; Refiling
8583 (defun org-get-org-file ()
8584 "Read a filename, with default directory `org-directory'."
8585 (let ((default (or org-default-notes-file remember-data-file)))
8586 (read-file-name (format "File name [%s]: " default)
8587 (file-name-as-directory org-directory)
8588 default)))
8590 (defun org-notes-order-reversed-p ()
8591 "Check if the current file should receive notes in reversed order."
8592 (cond
8593 ((not org-reverse-note-order) nil)
8594 ((eq t org-reverse-note-order) t)
8595 ((not (listp org-reverse-note-order)) nil)
8596 (t (catch 'exit
8597 (let ((all org-reverse-note-order)
8598 entry)
8599 (while (setq entry (pop all))
8600 (if (string-match (car entry) buffer-file-name)
8601 (throw 'exit (cdr entry))))
8602 nil)))))
8604 (defvar org-refile-target-table nil
8605 "The list of refile targets, created by `org-refile'.")
8607 (defvar org-agenda-new-buffers nil
8608 "Buffers created to visit agenda files.")
8610 (defun org-get-refile-targets (&optional default-buffer)
8611 "Produce a table with refile targets."
8612 (let ((case-fold-search nil)
8613 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8614 (entries (or org-refile-targets '((nil . (:level . 1)))))
8615 targets txt re files f desc descre fast-path-p level pos0)
8616 (message "Getting targets...")
8617 (with-current-buffer (or default-buffer (current-buffer))
8618 (while (setq entry (pop entries))
8619 (setq files (car entry) desc (cdr entry))
8620 (setq fast-path-p nil)
8621 (cond
8622 ((null files) (setq files (list (current-buffer))))
8623 ((eq files 'org-agenda-files)
8624 (setq files (org-agenda-files 'unrestricted)))
8625 ((and (symbolp files) (fboundp files))
8626 (setq files (funcall files)))
8627 ((and (symbolp files) (boundp files))
8628 (setq files (symbol-value files))))
8629 (if (stringp files) (setq files (list files)))
8630 (cond
8631 ((eq (car desc) :tag)
8632 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8633 ((eq (car desc) :todo)
8634 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8635 ((eq (car desc) :regexp)
8636 (setq descre (cdr desc)))
8637 ((eq (car desc) :level)
8638 (setq descre (concat "^\\*\\{" (number-to-string
8639 (if org-odd-levels-only
8640 (1- (* 2 (cdr desc)))
8641 (cdr desc)))
8642 "\\}[ \t]")))
8643 ((eq (car desc) :maxlevel)
8644 (setq fast-path-p t)
8645 (setq descre (concat "^\\*\\{1," (number-to-string
8646 (if org-odd-levels-only
8647 (1- (* 2 (cdr desc)))
8648 (cdr desc)))
8649 "\\}[ \t]")))
8650 (t (error "Bad refiling target description %s" desc)))
8651 (while (setq f (pop files))
8652 (save-excursion
8653 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8654 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8655 (setq f (expand-file-name f))
8656 (if (eq org-refile-use-outline-path 'file)
8657 (push (list (file-name-nondirectory f) f nil nil) targets))
8658 (save-excursion
8659 (save-restriction
8660 (widen)
8661 (goto-char (point-min))
8662 (while (re-search-forward descre nil t)
8663 (goto-char (setq pos0 (point-at-bol)))
8664 (catch 'next
8665 (when org-refile-target-verify-function
8666 (save-match-data
8667 (or (funcall org-refile-target-verify-function)
8668 (throw 'next t))))
8669 (when (looking-at org-complex-heading-regexp)
8670 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8671 txt (org-link-display-format (match-string 4))
8672 re (concat "^" (regexp-quote
8673 (buffer-substring (match-beginning 1)
8674 (match-end 4)))))
8675 (if (match-end 5) (setq re (concat re "[ \t]+"
8676 (regexp-quote
8677 (match-string 5)))))
8678 (setq re (concat re "[ \t]*$"))
8679 (when org-refile-use-outline-path
8680 (setq txt (mapconcat 'org-protect-slash
8681 (append
8682 (if (eq org-refile-use-outline-path 'file)
8683 (list (file-name-nondirectory
8684 (buffer-file-name (buffer-base-buffer))))
8685 (if (eq org-refile-use-outline-path 'full-file-path)
8686 (list (buffer-file-name (buffer-base-buffer)))))
8687 (org-get-outline-path fast-path-p level txt)
8688 (list txt))
8689 "/")))
8690 (push (list txt f re (point)) targets)))
8691 (when (= (point) pos0)
8692 ;; verification function has not moved point
8693 (goto-char (point-at-eol))))))))))
8694 (message "Getting targets...done")
8695 (nreverse targets)))
8697 (defun org-protect-slash (s)
8698 (while (string-match "/" s)
8699 (setq s (replace-match "\\" t t s)))
8702 (defvar org-olpa (make-vector 20 nil))
8704 (defun org-get-outline-path (&optional fastp level heading)
8705 "Return the outline path to the current entry, as a list."
8706 (if fastp
8707 (progn
8708 (if (> level 19)
8709 (error "Outline path failure, more than 19 levels."))
8710 (loop for i from level upto 19 do
8711 (aset org-olpa i nil))
8712 (prog1
8713 (delq nil (append org-olpa nil))
8714 (aset org-olpa level heading)))
8715 (let (rtn)
8716 (save-excursion
8717 (while (org-up-heading-safe)
8718 (when (looking-at org-complex-heading-regexp)
8719 (push (org-match-string-no-properties 4) rtn)))
8720 rtn))))
8722 (defvar org-refile-history nil
8723 "History for refiling operations.")
8725 (defvar org-after-refile-insert-hook nil
8726 "Hook run after `org-refile' has inserted its stuff at the new location.
8727 Note that this is still *before* the stuff will be removed from
8728 the *old* location.")
8730 (defun org-refile (&optional goto default-buffer rfloc)
8731 "Move the entry at point to another heading.
8732 The list of target headings is compiled using the information in
8733 `org-refile-targets', which see. This list is created before each use
8734 and will therefore always be up-to-date.
8736 At the target location, the entry is filed as a subitem of the target heading.
8737 Depending on `org-reverse-note-order', the new subitem will either be the
8738 first or the last subitem.
8740 If there is an active region, all entries in that region will be moved.
8741 However, the region must fulfil the requirement that the first heading
8742 is the first one sets the top-level of the moved text - at most siblings
8743 below it are allowed.
8745 With prefix arg GOTO, the command will only visit the target location,
8746 not actually move anything.
8747 With a double prefix `C-u C-u', go to the location where the last refiling
8748 operation has put the subtree.
8750 RFLOC can be a refile location obtained in a different way.
8752 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8753 (interactive "P")
8754 (let* ((cbuf (current-buffer))
8755 (regionp (org-region-active-p))
8756 (region-start (and regionp (region-beginning)))
8757 (region-end (and regionp (region-end)))
8758 (region-length (and regionp (- region-end region-start)))
8759 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8760 pos it nbuf file re level reversed)
8761 (when regionp
8762 (goto-char region-start)
8763 (or (bolp) (goto-char (point-at-bol)))
8764 (setq region-start (point))
8765 (unless (org-kill-is-subtree-p
8766 (buffer-substring region-start region-end))
8767 (error "The region is not a (sequence of) subtree(s)")))
8768 (if (equal goto '(16))
8769 (org-refile-goto-last-stored)
8770 (when (setq it (or rfloc
8771 (save-excursion
8772 (org-refile-get-location
8773 (if goto "Goto: " "Refile to: ") default-buffer
8774 org-refile-allow-creating-parent-nodes))))
8775 (setq file (nth 1 it)
8776 re (nth 2 it)
8777 pos (nth 3 it))
8778 (if (and (not goto)
8780 (equal (buffer-file-name) file)
8781 (if regionp
8782 (and (>= pos region-start)
8783 (<= pos region-end))
8784 (and (>= pos (point))
8785 (< pos (save-excursion
8786 (org-end-of-subtree t t))))))
8787 (error "Cannot refile to position inside the tree or region"))
8789 (setq nbuf (or (find-buffer-visiting file)
8790 (find-file-noselect file)))
8791 (if goto
8792 (progn
8793 (switch-to-buffer nbuf)
8794 (goto-char pos)
8795 (org-show-context 'org-goto))
8796 (if regionp
8797 (progn
8798 (org-kill-new (buffer-substring region-start region-end))
8799 (org-save-markers-in-region region-start region-end))
8800 (org-copy-subtree 1 nil t))
8801 (save-excursion
8802 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8803 (find-file-noselect file))))
8804 (setq reversed (org-notes-order-reversed-p))
8805 (save-excursion
8806 (save-restriction
8807 (widen)
8808 (if pos
8809 (progn
8810 (goto-char pos)
8811 (looking-at outline-regexp)
8812 (setq level (org-get-valid-level (funcall outline-level) 1))
8813 (goto-char
8814 (if reversed
8815 (or (outline-next-heading) (point-max))
8816 (or (save-excursion (org-get-next-sibling))
8817 (org-end-of-subtree t t)
8818 (point-max)))))
8819 (setq level 1)
8820 (if (not reversed)
8821 (goto-char (point-max))
8822 (goto-char (point-min))
8823 (or (outline-next-heading) (goto-char (point-max)))))
8824 (if (not (bolp)) (newline))
8825 (bookmark-set "org-refile-last-stored")
8826 (org-paste-subtree level)
8827 (if (fboundp 'deactivate-mark) (deactivate-mark))
8828 (run-hooks 'org-after-refile-insert-hook))))
8829 (if regionp
8830 (delete-region (point) (+ (point) region-length))
8831 (org-cut-subtree))
8832 (when (featurep 'org-inlinetask)
8833 (org-inlinetask-remove-END-maybe))
8834 (setq org-markers-to-move nil)
8835 (message "Refiled to \"%s\"" (car it))))))
8836 (org-reveal))
8838 (defun org-refile-goto-last-stored ()
8839 "Go to the location where the last refile was stored."
8840 (interactive)
8841 (bookmark-jump "org-refile-last-stored")
8842 (message "This is the location of the last refile"))
8844 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8845 "Prompt the user for a refile location, using PROMPT."
8846 (let ((org-refile-targets org-refile-targets)
8847 (org-refile-use-outline-path org-refile-use-outline-path))
8848 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8849 (unless org-refile-target-table
8850 (error "No refile targets"))
8851 (let* ((cbuf (current-buffer))
8852 (partial-completion-mode nil)
8853 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8854 (cfunc (if (and org-refile-use-outline-path
8855 org-outline-path-complete-in-steps)
8856 'org-olpath-completing-read
8857 'org-icompleting-read))
8858 (extra (if org-refile-use-outline-path "/" ""))
8859 (filename (and cfn (expand-file-name cfn)))
8860 (tbl (mapcar
8861 (lambda (x)
8862 (if (and (not (member org-refile-use-outline-path
8863 '(file full-file-path)))
8864 (not (equal filename (nth 1 x))))
8865 (cons (concat (car x) extra " ("
8866 (file-name-nondirectory (nth 1 x)) ")")
8867 (cdr x))
8868 (cons (concat (car x) extra) (cdr x))))
8869 org-refile-target-table))
8870 (completion-ignore-case t)
8871 pa answ parent-target child parent old-hist)
8872 (setq old-hist org-refile-history)
8873 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8874 nil 'org-refile-history))
8875 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8876 (if pa
8877 (progn
8878 (when (or (not org-refile-history)
8879 (not (eq old-hist org-refile-history))
8880 (not (equal (car pa) (car org-refile-history))))
8881 (setq org-refile-history
8882 (cons (car pa) (if (assoc (car org-refile-history) tbl)
8883 org-refile-history
8884 (cdr org-refile-history))))
8885 (if (equal (car org-refile-history) (nth 1 org-refile-history))
8886 (pop org-refile-history)))
8888 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8889 (setq parent (match-string 1 answ)
8890 child (match-string 2 answ))
8891 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8892 (when (and parent-target
8893 (or (eq new-nodes t)
8894 (and (eq new-nodes 'confirm)
8895 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8896 (org-refile-new-child parent-target child))))))
8898 (defun org-refile-new-child (parent-target child)
8899 "Use refile target PARENT-TARGET to add new CHILD below it."
8900 (unless parent-target
8901 (error "Cannot find parent for new node"))
8902 (let ((file (nth 1 parent-target))
8903 (pos (nth 3 parent-target))
8904 level)
8905 (with-current-buffer (or (find-buffer-visiting file)
8906 (find-file-noselect file))
8907 (save-excursion
8908 (save-restriction
8909 (widen)
8910 (if pos
8911 (goto-char pos)
8912 (goto-char (point-max))
8913 (if (not (bolp)) (newline)))
8914 (when (looking-at outline-regexp)
8915 (setq level (funcall outline-level))
8916 (org-end-of-subtree t t))
8917 (org-back-over-empty-lines)
8918 (insert "\n" (make-string
8919 (if pos (org-get-valid-level level 1) 1) ?*)
8920 " " child "\n")
8921 (beginning-of-line 0)
8922 (list (concat (car parent-target) "/" child) file "" (point)))))))
8924 (defun org-olpath-completing-read (prompt collection &rest args)
8925 "Read an outline path like a file name."
8926 (let ((thetable collection)
8927 (org-completion-use-ido nil) ; does not work with ido.
8928 (org-completion-use-iswitchb nil)) ; or iswitchb
8929 (apply
8930 'org-icompleting-read prompt
8931 (lambda (string predicate &optional flag)
8932 (let (rtn r f (l (length string)))
8933 (cond
8934 ((eq flag nil)
8935 ;; try completion
8936 (try-completion string thetable))
8937 ((eq flag t)
8938 ;; all-completions
8939 (setq rtn (all-completions string thetable predicate))
8940 (mapcar
8941 (lambda (x)
8942 (setq r (substring x l))
8943 (if (string-match " ([^)]*)$" x)
8944 (setq f (match-string 0 x))
8945 (setq f ""))
8946 (if (string-match "/" r)
8947 (concat string (substring r 0 (match-end 0)) f)
8949 rtn))
8950 ((eq flag 'lambda)
8951 ;; exact match?
8952 (assoc string thetable)))
8954 args)))
8956 ;;;; Dynamic blocks
8958 (defun org-find-dblock (name)
8959 "Find the first dynamic block with name NAME in the buffer.
8960 If not found, stay at current position and return nil."
8961 (let (pos)
8962 (save-excursion
8963 (goto-char (point-min))
8964 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8965 nil t)
8966 (match-beginning 0))))
8967 (if pos (goto-char pos))
8968 pos))
8970 (defconst org-dblock-start-re
8971 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8972 "Matches the startline of a dynamic block, with parameters.")
8974 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8975 "Matches the end of a dynamic block.")
8977 (defun org-create-dblock (plist)
8978 "Create a dynamic block section, with parameters taken from PLIST.
8979 PLIST must contain a :name entry which is used as name of the block."
8980 (unless (bolp) (newline))
8981 (let ((name (plist-get plist :name)))
8982 (insert "#+BEGIN: " name)
8983 (while plist
8984 (if (eq (car plist) :name)
8985 (setq plist (cddr plist))
8986 (insert " " (prin1-to-string (pop plist)))))
8987 (insert "\n\n#+END:\n")
8988 (beginning-of-line -2)))
8990 (defun org-prepare-dblock ()
8991 "Prepare dynamic block for refresh.
8992 This empties the block, puts the cursor at the insert position and returns
8993 the property list including an extra property :name with the block name."
8994 (unless (looking-at org-dblock-start-re)
8995 (error "Not at a dynamic block"))
8996 (let* ((begdel (1+ (match-end 0)))
8997 (name (org-no-properties (match-string 1)))
8998 (params (append (list :name name)
8999 (read (concat "(" (match-string 3) ")")))))
9000 (unless (re-search-forward org-dblock-end-re nil t)
9001 (error "Dynamic block not terminated"))
9002 (setq params
9003 (append params
9004 (list :content (buffer-substring
9005 begdel (match-beginning 0)))))
9006 (delete-region begdel (match-beginning 0))
9007 (goto-char begdel)
9008 (open-line 1)
9009 params))
9011 (defun org-map-dblocks (&optional command)
9012 "Apply COMMAND to all dynamic blocks in the current buffer.
9013 If COMMAND is not given, use `org-update-dblock'."
9014 (let ((cmd (or command 'org-update-dblock))
9015 pos)
9016 (save-excursion
9017 (goto-char (point-min))
9018 (while (re-search-forward org-dblock-start-re nil t)
9019 (goto-char (setq pos (match-beginning 0)))
9020 (condition-case nil
9021 (funcall cmd)
9022 (error (message "Error during update of dynamic block")))
9023 (goto-char pos)
9024 (unless (re-search-forward org-dblock-end-re nil t)
9025 (error "Dynamic block not terminated"))))))
9027 (defun org-dblock-update (&optional arg)
9028 "User command for updating dynamic blocks.
9029 Update the dynamic block at point. With prefix ARG, update all dynamic
9030 blocks in the buffer."
9031 (interactive "P")
9032 (if arg
9033 (org-update-all-dblocks)
9034 (or (looking-at org-dblock-start-re)
9035 (org-beginning-of-dblock))
9036 (org-update-dblock)))
9038 (defun org-update-dblock ()
9039 "Update the dynamic block at point
9040 This means to empty the block, parse for parameters and then call
9041 the correct writing function."
9042 (save-window-excursion
9043 (let* ((pos (point))
9044 (line (org-current-line))
9045 (params (org-prepare-dblock))
9046 (name (plist-get params :name))
9047 (cmd (intern (concat "org-dblock-write:" name))))
9048 (message "Updating dynamic block `%s' at line %d..." name line)
9049 (funcall cmd params)
9050 (message "Updating dynamic block `%s' at line %d...done" name line)
9051 (goto-char pos))))
9053 (defun org-beginning-of-dblock ()
9054 "Find the beginning of the dynamic block at point.
9055 Error if there is no such block at point."
9056 (let ((pos (point))
9057 beg)
9058 (end-of-line 1)
9059 (if (and (re-search-backward org-dblock-start-re nil t)
9060 (setq beg (match-beginning 0))
9061 (re-search-forward org-dblock-end-re nil t)
9062 (> (match-end 0) pos))
9063 (goto-char beg)
9064 (goto-char pos)
9065 (error "Not in a dynamic block"))))
9067 (defun org-update-all-dblocks ()
9068 "Update all dynamic blocks in the buffer.
9069 This function can be used in a hook."
9070 (when (org-mode-p)
9071 (org-map-dblocks 'org-update-dblock)))
9074 ;;;; Completion
9076 (defconst org-additional-option-like-keywords
9077 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9078 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9079 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
9080 "BEGIN:" "END:"
9081 "ORGTBL" "TBLFM:" "TBLNAME:"
9082 "BEGIN_EXAMPLE" "END_EXAMPLE"
9083 "BEGIN_QUOTE" "END_QUOTE"
9084 "BEGIN_VERSE" "END_VERSE"
9085 "BEGIN_CENTER" "END_CENTER"
9086 "BEGIN_SRC" "END_SRC"
9087 "CATEGORY" "COLUMNS"
9088 "CAPTION" "LABEL"
9089 "BIND"
9090 "MACRO"))
9092 (defcustom org-structure-template-alist
9094 ("s" "#+begin_src ?\n\n#+end_src"
9095 "<src lang=\"?\">\n\n</src>")
9096 ("e" "#+begin_example\n?\n#+end_example"
9097 "<example>\n?\n</example>")
9098 ("q" "#+begin_quote\n?\n#+end_quote"
9099 "<quote>\n?\n</quote>")
9100 ("v" "#+begin_verse\n?\n#+end_verse"
9101 "<verse>\n?\n/verse>")
9102 ("c" "#+begin_center\n?\n#+end_center"
9103 "<center>\n?\n/center>")
9104 ("l" "#+begin_latex\n?\n#+end_latex"
9105 "<literal style=\"latex\">\n?\n</literal>")
9106 ("L" "#+latex: "
9107 "<literal style=\"latex\">?</literal>")
9108 ("h" "#+begin_html\n?\n#+end_html"
9109 "<literal style=\"html\">\n?\n</literal>")
9110 ("H" "#+html: "
9111 "<literal style=\"html\">?</literal>")
9112 ("a" "#+begin_ascii\n?\n#+end_ascii")
9113 ("A" "#+ascii: ")
9114 ("i" "#+include %file ?"
9115 "<include file=%file markup=\"?\">")
9117 "Structure completion elements.
9118 This is a list of abbreviation keys and values. The value gets inserted
9119 it you type @samp{.} followed by the key and then the completion key,
9120 usually `M-TAB'. %file will be replaced by a file name after prompting
9121 for the file using completion.
9122 There are two templates for each key, the first uses the original Org syntax,
9123 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9124 the default when the /org-mtags.el/ module has been loaded. See also the
9125 variable `org-mtags-prefer-muse-templates'.
9126 This is an experimental feature, it is undecided if it is going to stay in."
9127 :group 'org-completion
9128 :type '(repeat
9129 (string :tag "Key")
9130 (string :tag "Template")
9131 (string :tag "Muse Template")))
9133 (defun org-try-structure-completion ()
9134 "Try to complete a structure template before point.
9135 This looks for strings like \"<e\" on an otherwise empty line and
9136 expands them."
9137 (let ((l (buffer-substring (point-at-bol) (point)))
9139 (when (and (looking-at "[ \t]*$")
9140 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9141 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9142 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9143 (match-beginning 1)) a)
9144 t)))
9146 (defun org-complete-expand-structure-template (start cell)
9147 "Expand a structure template."
9148 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9149 (rpl (nth (if musep 2 1) cell))
9150 (ind ""))
9151 (delete-region start (point))
9152 (when (string-match "\\`#\\+" rpl)
9153 (cond
9154 ((bolp))
9155 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9156 (setq ind (buffer-substring (point-at-bol) (point))))
9157 (t (newline))))
9158 (setq start (point))
9159 (if (string-match "%file" rpl)
9160 (setq rpl (replace-match
9161 (concat
9162 "\""
9163 (save-match-data
9164 (abbreviate-file-name (read-file-name "Include file: ")))
9165 "\"")
9166 t t rpl)))
9167 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9168 (concat "\n" ind)))
9169 (insert rpl)
9170 (if (re-search-backward "\\?" start t) (delete-char 1))))
9173 (defun org-complete (&optional arg)
9174 "Perform completion on word at point.
9175 At the beginning of a headline, this completes TODO keywords as given in
9176 `org-todo-keywords'.
9177 If the current word is preceded by a backslash, completes the TeX symbols
9178 that are supported for HTML support.
9179 If the current word is preceded by \"#+\", completes special words for
9180 setting file options.
9181 In the line after \"#+STARTUP:, complete valid keywords.\"
9182 At all other locations, this simply calls the value of
9183 `org-completion-fallback-command'."
9184 (interactive "P")
9185 (org-without-partial-completion
9186 (catch 'exit
9187 (let* ((a nil)
9188 (end (point))
9189 (beg1 (save-excursion
9190 (skip-chars-backward (org-re "[:alnum:]_@"))
9191 (point)))
9192 (beg (save-excursion
9193 (skip-chars-backward "a-zA-Z0-9_:$")
9194 (point)))
9195 (confirm (lambda (x) (stringp (car x))))
9196 (searchhead (equal (char-before beg) ?*))
9197 (struct
9198 (when (and (member (char-before beg1) '(?. ?<))
9199 (setq a (assoc (buffer-substring beg1 (point))
9200 org-structure-template-alist)))
9201 (org-complete-expand-structure-template (1- beg1) a)
9202 (throw 'exit t)))
9203 (tag (and (equal (char-before beg1) ?:)
9204 (equal (char-after (point-at-bol)) ?*)))
9205 (prop (and (equal (char-before beg1) ?:)
9206 (not (equal (char-after (point-at-bol)) ?*))))
9207 (texp (equal (char-before beg) ?\\))
9208 (link (equal (char-before beg) ?\[))
9209 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9210 beg)
9211 "#+"))
9212 (startup (string-match "^#\\+STARTUP:.*"
9213 (buffer-substring (point-at-bol) (point))))
9214 (completion-ignore-case opt)
9215 (type nil)
9216 (tbl nil)
9217 (table (cond
9218 (opt
9219 (setq type :opt)
9220 (require 'org-exp)
9221 (append
9222 (delq nil
9223 (mapcar
9224 (lambda (x)
9225 (if (string-match
9226 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9227 (cons (match-string 2 x)
9228 (match-string 1 x))))
9229 (org-split-string (org-get-current-options) "\n")))
9230 (mapcar 'list org-additional-option-like-keywords)))
9231 (startup
9232 (setq type :startup)
9233 org-startup-options)
9234 (link (append org-link-abbrev-alist-local
9235 org-link-abbrev-alist))
9236 (texp
9237 (setq type :tex)
9238 org-html-entities)
9239 ((string-match "\\`\\*+[ \t]+\\'"
9240 (buffer-substring (point-at-bol) beg))
9241 (setq type :todo)
9242 (mapcar 'list org-todo-keywords-1))
9243 (searchhead
9244 (setq type :searchhead)
9245 (save-excursion
9246 (goto-char (point-min))
9247 (while (re-search-forward org-todo-line-regexp nil t)
9248 (push (list
9249 (org-make-org-heading-search-string
9250 (match-string 3) t))
9251 tbl)))
9252 tbl)
9253 (tag (setq type :tag beg beg1)
9254 (or org-tag-alist (org-get-buffer-tags)))
9255 (prop (setq type :prop beg beg1)
9256 (mapcar 'list (org-buffer-property-keys nil t t)))
9257 (t (progn
9258 (call-interactively org-completion-fallback-command)
9259 (throw 'exit nil)))))
9260 (pattern (buffer-substring-no-properties beg end))
9261 (completion (try-completion pattern table confirm)))
9262 (cond ((eq completion t)
9263 (if (not (assoc (upcase pattern) table))
9264 (message "Already complete")
9265 (if (and (equal type :opt)
9266 (not (member (car (assoc (upcase pattern) table))
9267 org-additional-option-like-keywords)))
9268 (insert (substring (cdr (assoc (upcase pattern) table))
9269 (length pattern)))
9270 (if (memq type '(:tag :prop)) (insert ":")))))
9271 ((null completion)
9272 (message "Can't find completion for \"%s\"" pattern)
9273 (ding))
9274 ((not (string= pattern completion))
9275 (delete-region beg end)
9276 (if (string-match " +$" completion)
9277 (setq completion (replace-match "" t t completion)))
9278 (insert completion)
9279 (if (get-buffer-window "*Completions*")
9280 (delete-window (get-buffer-window "*Completions*")))
9281 (if (assoc completion table)
9282 (if (eq type :todo) (insert " ")
9283 (if (memq type '(:tag :prop)) (insert ":"))))
9284 (if (and (equal type :opt) (assoc completion table))
9285 (message "%s" (substitute-command-keys
9286 "Press \\[org-complete] again to insert example settings"))))
9288 (message "Making completion list...")
9289 (let ((list (sort (all-completions pattern table confirm)
9290 'string<)))
9291 (with-output-to-temp-buffer "*Completions*"
9292 (condition-case nil
9293 ;; Protection needed for XEmacs and emacs 21
9294 (display-completion-list list pattern)
9295 (error (display-completion-list list)))))
9296 (message "Making completion list...%s" "done")))))))
9298 ;;;; TODO, DEADLINE, Comments
9300 (defun org-toggle-comment ()
9301 "Change the COMMENT state of an entry."
9302 (interactive)
9303 (save-excursion
9304 (org-back-to-heading)
9305 (let (case-fold-search)
9306 (if (looking-at (concat outline-regexp
9307 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9308 (replace-match "" t t nil 1)
9309 (if (looking-at outline-regexp)
9310 (progn
9311 (goto-char (match-end 0))
9312 (insert org-comment-string " ")))))))
9314 (defvar org-last-todo-state-is-todo nil
9315 "This is non-nil when the last TODO state change led to a TODO state.
9316 If the last change removed the TODO tag or switched to DONE, then
9317 this is nil.")
9319 (defvar org-setting-tags nil) ; dynamically skipped
9321 (defun org-parse-local-options (string var)
9322 "Parse STRING for startup setting relevant for variable VAR."
9323 (let ((rtn (symbol-value var))
9324 e opts)
9325 (save-match-data
9326 (if (or (not string) (not (string-match "\\S-" string)))
9328 (setq opts (delq nil (mapcar (lambda (x)
9329 (setq e (assoc x org-startup-options))
9330 (if (eq (nth 1 e) var) e nil))
9331 (org-split-string string "[ \t]+"))))
9332 (if (not opts)
9334 (setq rtn nil)
9335 (while (setq e (pop opts))
9336 (if (not (nth 3 e))
9337 (setq rtn (nth 2 e))
9338 (if (not (listp rtn)) (setq rtn nil))
9339 (push (nth 2 e) rtn)))
9340 rtn)))))
9342 (defvar org-todo-setup-filter-hook nil
9343 "Hook for functions that pre-filter todo specs.
9345 Each function takes a todo spec and returns either `nil' or the spec
9346 transformed into canonical form." )
9348 (defvar org-todo-get-default-hook nil
9349 "Hook for functions that get a default item for todo.
9351 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9352 `nil' or a string to be used for the todo mark." )
9354 (defvar org-agenda-headline-snapshot-before-repeat)
9356 (defun org-todo (&optional arg)
9357 "Change the TODO state of an item.
9358 The state of an item is given by a keyword at the start of the heading,
9359 like
9360 *** TODO Write paper
9361 *** DONE Call mom
9363 The different keywords are specified in the variable `org-todo-keywords'.
9364 By default the available states are \"TODO\" and \"DONE\".
9365 So for this example: when the item starts with TODO, it is changed to DONE.
9366 When it starts with DONE, the DONE is removed. And when neither TODO nor
9367 DONE are present, add TODO at the beginning of the heading.
9369 With C-u prefix arg, use completion to determine the new state.
9370 With numeric prefix arg, switch to that state.
9371 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9372 With a tripple C-u prefix, circumvent any state blocking.
9374 For calling through lisp, arg is also interpreted in the following way:
9375 'none -> empty state
9376 \"\"(empty string) -> switch to empty state
9377 'done -> switch to DONE
9378 'nextset -> switch to the next set of keywords
9379 'previousset -> switch to the previous set of keywords
9380 \"WAITING\" -> switch to the specified keyword, but only if it
9381 really is a member of `org-todo-keywords'."
9382 (interactive "P")
9383 (if (equal arg '(16)) (setq arg 'nextset))
9384 (let ((org-blocker-hook org-blocker-hook)
9385 (case-fold-search nil))
9386 (when (equal arg '(64))
9387 (setq arg nil org-blocker-hook nil))
9388 (when (and org-blocker-hook
9389 (or org-inhibit-blocking
9390 (org-entry-get nil "NOBLOCKING")))
9391 (setq org-blocker-hook nil))
9392 (save-excursion
9393 (catch 'exit
9394 (org-back-to-heading)
9395 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9396 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9397 (looking-at " *"))
9398 (let* ((match-data (match-data))
9399 (startpos (point-at-bol))
9400 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9401 (org-log-done org-log-done)
9402 (org-log-repeat org-log-repeat)
9403 (org-todo-log-states org-todo-log-states)
9404 (this (match-string 1))
9405 (hl-pos (match-beginning 0))
9406 (head (org-get-todo-sequence-head this))
9407 (ass (assoc head org-todo-kwd-alist))
9408 (interpret (nth 1 ass))
9409 (done-word (nth 3 ass))
9410 (final-done-word (nth 4 ass))
9411 (last-state (or this ""))
9412 (completion-ignore-case t)
9413 (member (member this org-todo-keywords-1))
9414 (tail (cdr member))
9415 (state (cond
9416 ((and org-todo-key-trigger
9417 (or (and (equal arg '(4))
9418 (eq org-use-fast-todo-selection 'prefix))
9419 (and (not arg) org-use-fast-todo-selection
9420 (not (eq org-use-fast-todo-selection
9421 'prefix)))))
9422 ;; Use fast selection
9423 (org-fast-todo-selection))
9424 ((and (equal arg '(4))
9425 (or (not org-use-fast-todo-selection)
9426 (not org-todo-key-trigger)))
9427 ;; Read a state with completion
9428 (org-icompleting-read
9429 "State: " (mapcar (lambda(x) (list x))
9430 org-todo-keywords-1)
9431 nil t))
9432 ((eq arg 'right)
9433 (if this
9434 (if tail (car tail) nil)
9435 (car org-todo-keywords-1)))
9436 ((eq arg 'left)
9437 (if (equal member org-todo-keywords-1)
9439 (if this
9440 (nth (- (length org-todo-keywords-1)
9441 (length tail) 2)
9442 org-todo-keywords-1)
9443 (org-last org-todo-keywords-1))))
9444 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9445 (setq arg nil))) ; hack to fall back to cycling
9446 (arg
9447 ;; user or caller requests a specific state
9448 (cond
9449 ((equal arg "") nil)
9450 ((eq arg 'none) nil)
9451 ((eq arg 'done) (or done-word (car org-done-keywords)))
9452 ((eq arg 'nextset)
9453 (or (car (cdr (member head org-todo-heads)))
9454 (car org-todo-heads)))
9455 ((eq arg 'previousset)
9456 (let ((org-todo-heads (reverse org-todo-heads)))
9457 (or (car (cdr (member head org-todo-heads)))
9458 (car org-todo-heads))))
9459 ((car (member arg org-todo-keywords-1)))
9460 ((nth (1- (prefix-numeric-value arg))
9461 org-todo-keywords-1))))
9462 ((null member) (or head (car org-todo-keywords-1)))
9463 ((equal this final-done-word) nil) ;; -> make empty
9464 ((null tail) nil) ;; -> first entry
9465 ((memq interpret '(type priority))
9466 (if (eq this-command last-command)
9467 (car tail)
9468 (if (> (length tail) 0)
9469 (or done-word (car org-done-keywords))
9470 nil)))
9472 (car tail))))
9473 (state (or
9474 (run-hook-with-args-until-success
9475 'org-todo-get-default-hook state last-state)
9476 state))
9477 (next (if state (concat " " state " ") " "))
9478 (change-plist (list :type 'todo-state-change :from this :to state
9479 :position startpos))
9480 dolog now-done-p)
9481 (when org-blocker-hook
9482 (setq org-last-todo-state-is-todo
9483 (not (member this org-done-keywords)))
9484 (unless (save-excursion
9485 (save-match-data
9486 (run-hook-with-args-until-failure
9487 'org-blocker-hook change-plist)))
9488 (if (interactive-p)
9489 (error "TODO state change from %s to %s blocked" this state)
9490 ;; fail silently
9491 (message "TODO state change from %s to %s blocked" this state)
9492 (throw 'exit nil))))
9493 (store-match-data match-data)
9494 (replace-match next t t)
9495 (unless (pos-visible-in-window-p hl-pos)
9496 (message "TODO state changed to %s" (org-trim next)))
9497 (unless head
9498 (setq head (org-get-todo-sequence-head state)
9499 ass (assoc head org-todo-kwd-alist)
9500 interpret (nth 1 ass)
9501 done-word (nth 3 ass)
9502 final-done-word (nth 4 ass)))
9503 (when (memq arg '(nextset previousset))
9504 (message "Keyword-Set %d/%d: %s"
9505 (- (length org-todo-sets) -1
9506 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9507 (length org-todo-sets)
9508 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9509 (setq org-last-todo-state-is-todo
9510 (not (member state org-done-keywords)))
9511 (setq now-done-p (and (member state org-done-keywords)
9512 (not (member this org-done-keywords))))
9513 (and logging (org-local-logging logging))
9514 (when (and (or org-todo-log-states org-log-done)
9515 (not (eq org-inhibit-logging t))
9516 (not (memq arg '(nextset previousset))))
9517 ;; we need to look at recording a time and note
9518 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9519 (nth 2 (assoc this org-todo-log-states))))
9520 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9521 (setq dolog 'time))
9522 (when (and state
9523 (member state org-not-done-keywords)
9524 (not (member this org-not-done-keywords)))
9525 ;; This is now a todo state and was not one before
9526 ;; If there was a CLOSED time stamp, get rid of it.
9527 (org-add-planning-info nil nil 'closed))
9528 (when (and now-done-p org-log-done)
9529 ;; It is now done, and it was not done before
9530 (org-add-planning-info 'closed (org-current-time))
9531 (if (and (not dolog) (eq 'note org-log-done))
9532 (org-add-log-setup 'done state this 'findpos 'note)))
9533 (when (and state dolog)
9534 ;; This is a non-nil state, and we need to log it
9535 (org-add-log-setup 'state state this 'findpos dolog)))
9536 ;; Fixup tag positioning
9537 (org-todo-trigger-tag-changes state)
9538 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9539 (when org-provide-todo-statistics
9540 (org-update-parent-todo-statistics))
9541 (run-hooks 'org-after-todo-state-change-hook)
9542 (if (and arg (not (member state org-done-keywords)))
9543 (setq head (org-get-todo-sequence-head state)))
9544 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9545 ;; Do we need to trigger a repeat?
9546 (when now-done-p
9547 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9548 ;; This is for the agenda, take a snapshot of the headline.
9549 (save-match-data
9550 (setq org-agenda-headline-snapshot-before-repeat
9551 (org-get-heading))))
9552 (org-auto-repeat-maybe state))
9553 ;; Fixup cursor location if close to the keyword
9554 (if (and (outline-on-heading-p)
9555 (not (bolp))
9556 (save-excursion (beginning-of-line 1)
9557 (looking-at org-todo-line-regexp))
9558 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9559 (progn
9560 (goto-char (or (match-end 2) (match-end 1)))
9561 (and (looking-at " ") (just-one-space))))
9562 (when org-trigger-hook
9563 (save-excursion
9564 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9566 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9567 "Block turning an entry into a TODO, using the hierarchy.
9568 This checks whether the current task should be blocked from state
9569 changes. Such blocking occurs when:
9571 1. The task has children which are not all in a completed state.
9573 2. A task has a parent with the property :ORDERED:, and there
9574 are siblings prior to the current task with incomplete
9575 status.
9577 3. The parent of the task is blocked because it has siblings that should
9578 be done first, or is child of a block grandparent TODO entry."
9580 (catch 'dont-block
9581 ;; If this is not a todo state change, or if this entry is already DONE,
9582 ;; do not block
9583 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9584 (member (plist-get change-plist :from)
9585 (cons 'done org-done-keywords))
9586 (member (plist-get change-plist :to)
9587 (cons 'todo org-not-done-keywords)))
9588 (throw 'dont-block t))
9589 ;; If this task has children, and any are undone, it's blocked
9590 (save-excursion
9591 (org-back-to-heading t)
9592 (let ((this-level (funcall outline-level)))
9593 (outline-next-heading)
9594 (let ((child-level (funcall outline-level)))
9595 (while (and (not (eobp))
9596 (> child-level this-level))
9597 ;; this todo has children, check whether they are all
9598 ;; completed
9599 (if (and (not (org-entry-is-done-p))
9600 (org-entry-is-todo-p))
9601 (throw 'dont-block nil))
9602 (outline-next-heading)
9603 (setq child-level (funcall outline-level))))))
9604 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9605 ;; any previous siblings are undone, it's blocked
9606 (save-excursion
9607 (org-back-to-heading t)
9608 (let* ((pos (point))
9609 (parent-pos (and (org-up-heading-safe) (point))))
9610 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9611 (when (and (org-entry-get (point) "ORDERED")
9612 (forward-line 1)
9613 (re-search-forward org-not-done-heading-regexp pos t))
9614 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9615 ;; Search further up the hierarchy, to see if an anchestor is blocked
9616 (while t
9617 (goto-char parent-pos)
9618 (if (not (looking-at org-not-done-heading-regexp))
9619 (throw 'dont-block t)) ; do not block, parent is not a TODO
9620 (setq pos (point))
9621 (setq parent-pos (and (org-up-heading-safe) (point)))
9622 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9623 (when (and (org-entry-get (point) "ORDERED")
9624 (forward-line 1)
9625 (re-search-forward org-not-done-heading-regexp pos t))
9626 (throw 'dont-block nil))))))) ; block, older sibling not done.
9628 (defcustom org-track-ordered-property-with-tag nil
9629 "Should the ORDERED property also be shown as a tag?
9630 The ORDERED property decides if an entry should require subtasks to be
9631 completed in sequence. Since a property is not very visible, setting
9632 this option means that toggling the ORDERED property with the command
9633 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9634 not relevant for the behavior, but it makes things more visible.
9636 Note that toggling the tag with tags commands will not change the property
9637 and therefore not influence behavior!
9639 This can be t, meaning the tag ORDERED should be used, It can also be a
9640 string to select a different tag for this task."
9641 :group 'org-todo
9642 :type '(choice
9643 (const :tag "No tracking" nil)
9644 (const :tag "Track with ORDERED tag" t)
9645 (string :tag "Use other tag")))
9647 (defun org-toggle-ordered-property ()
9648 "Toggle the ORDERED property of the current entry.
9649 For better visibility, you can track the value of this property with a tag.
9650 See variable `org-track-ordered-property-with-tag'."
9651 (interactive)
9652 (let* ((t1 org-track-ordered-property-with-tag)
9653 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9654 (save-excursion
9655 (org-back-to-heading)
9656 (if (org-entry-get nil "ORDERED")
9657 (progn
9658 (org-delete-property "ORDERED")
9659 (and tag (org-toggle-tag tag 'off))
9660 (message "Subtasks can be completed in arbitrary order"))
9661 (org-entry-put nil "ORDERED" "t")
9662 (and tag (org-toggle-tag tag 'on))
9663 (message "Subtasks must be completed in sequence")))))
9665 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9666 (defun org-block-todo-from-checkboxes (change-plist)
9667 "Block turning an entry into a TODO, using checkboxes.
9668 This checks whether the current task should be blocked from state
9669 changes because there are uncheckd boxes in this entry."
9670 (catch 'dont-block
9671 ;; If this is not a todo state change, or if this entry is already DONE,
9672 ;; do not block
9673 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9674 (member (plist-get change-plist :from)
9675 (cons 'done org-done-keywords))
9676 (member (plist-get change-plist :to)
9677 (cons 'todo org-not-done-keywords)))
9678 (throw 'dont-block t))
9679 ;; If this task has checkboxes that are not checked, it's blocked
9680 (save-excursion
9681 (org-back-to-heading t)
9682 (let ((beg (point)) end)
9683 (outline-next-heading)
9684 (setq end (point))
9685 (goto-char beg)
9686 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9687 end t)
9688 (progn
9689 (if (boundp 'org-blocked-by-checkboxes)
9690 (setq org-blocked-by-checkboxes t))
9691 (throw 'dont-block nil)))))
9692 t)) ; do not block
9694 (defun org-update-statistics-cookies (all)
9695 "Update the statistics cookie, either from TODO or from checkboxes.
9696 This should be called with the cursor in a line with a statistics cookie."
9697 (interactive "P")
9698 (if all
9699 (progn
9700 (org-update-checkbox-count 'all)
9701 (org-map-entries 'org-update-parent-todo-statistics))
9702 (if (not (org-on-heading-p))
9703 (org-update-checkbox-count)
9704 (let ((pos (move-marker (make-marker) (point)))
9705 end l1 l2)
9706 (ignore-errors (org-back-to-heading t))
9707 (if (not (org-on-heading-p))
9708 (org-update-checkbox-count)
9709 (setq l1 (org-outline-level))
9710 (setq end (save-excursion
9711 (outline-next-heading)
9712 (if (org-on-heading-p) (setq l2 (org-outline-level)))
9713 (point)))
9714 (if (and (save-excursion (re-search-forward
9715 "^[ \t]*[-+*] \\[[- X]\\]" end t))
9716 (not (save-excursion (re-search-forward
9717 ":COOKIE_DATA:.*\\<todo\\>" end t))))
9718 (org-update-checkbox-count)
9719 (if (and l2 (> l2 l1))
9720 (progn
9721 (goto-char end)
9722 (org-update-parent-todo-statistics))
9723 (error "No data for statistics cookie"))))
9724 (goto-char pos)
9725 (move-marker pos nil)))))
9727 (defvar org-entry-property-inherited-from) ;; defined below
9728 (defun org-update-parent-todo-statistics ()
9729 "Update any statistics cookie in the parent of the current headline.
9730 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9731 the entire subtree and this will travel up the hierarchy and update
9732 statistics everywhere."
9733 (interactive)
9734 (let* ((lim 0) prop
9735 (recursive (or (not org-hierarchical-todo-statistics)
9736 (string-match
9737 "\\<recursive\\>"
9738 (or (setq prop (org-entry-get
9739 nil "COOKIE_DATA" 'inherit)) ""))))
9740 (lim (or (and prop (marker-position
9741 org-entry-property-inherited-from))
9742 lim))
9743 (first t)
9744 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9745 level ltoggle l1
9746 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9747 (catch 'exit
9748 (save-excursion
9749 (beginning-of-line 1)
9750 (if (org-at-heading-p)
9751 (setq ltoggle (funcall outline-level))
9752 (error "This should not happen"))
9753 (while (and (setq level (org-up-heading-safe))
9754 (or recursive first)
9755 (>= (point) lim))
9756 (setq first nil)
9757 (unless (and level
9758 (not (string-match
9759 "\\<checkbox\\>"
9760 (downcase
9761 (or (org-entry-get
9762 nil "COOKIE_DATA")
9763 "")))))
9764 (throw 'exit nil))
9765 (while (re-search-forward box-re (point-at-eol) t)
9766 (setq cnt-all 0 cnt-done 0 cookie-present t)
9767 (setq is-percent (match-end 2))
9768 (save-match-data
9769 (unless (outline-next-heading) (throw 'exit nil))
9770 (while (and (looking-at org-complex-heading-regexp)
9771 (> (setq l1 (length (match-string 1))) level))
9772 (setq kwd (and (or recursive (= l1 ltoggle))
9773 (match-string 2)))
9774 (if (or (eq org-provide-todo-statistics 'all-headlines)
9775 (and (listp org-provide-todo-statistics)
9776 (or (member kwd org-provide-todo-statistics)
9777 (member kwd org-done-keywords))))
9778 (setq cnt-all (1+ cnt-all))
9779 (if (eq org-provide-todo-statistics t)
9780 (and kwd (setq cnt-all (1+ cnt-all)))))
9781 (and (member kwd org-done-keywords)
9782 (setq cnt-done (1+ cnt-done)))
9783 (outline-next-heading)))
9784 (replace-match
9785 (if is-percent
9786 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9787 (format "[%d/%d]" cnt-done cnt-all)))))
9788 (when cookie-present
9789 (run-hook-with-args 'org-after-todo-statistics-hook
9790 cnt-done (- cnt-all cnt-done)))))
9791 (run-hooks 'org-todo-statistics-hook)))
9793 (defvar org-after-todo-statistics-hook nil
9794 "Hook that is called after a TODO statistics cookie has been updated.
9795 Each function is called with two arguments: the number of not-done entries
9796 and the number of done entries.
9798 For example, the following function, when added to this hook, will switch
9799 an entry to DONE when all children are done, and back to TODO when new
9800 entries are set to a TODO status. Note that this hook is only called
9801 when there is a statistics cookie in the headline!
9803 (defun org-summary-todo (n-done n-not-done)
9804 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9805 (let (org-log-done org-log-states) ; turn off logging
9806 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9809 (defvar org-todo-statistics-hook nil
9810 "Hook that is run whenever Org thinks TODO statistics should be updated.
9811 This hook runs even if there is no statisics cookie present, in which case
9812 `org-after-todo-statistics-hook' would not run.")
9814 (defun org-todo-trigger-tag-changes (state)
9815 "Apply the changes defined in `org-todo-state-tags-triggers'."
9816 (let ((l org-todo-state-tags-triggers)
9817 changes)
9818 (when (or (not state) (equal state ""))
9819 (setq changes (append changes (cdr (assoc "" l)))))
9820 (when (and (stringp state) (> (length state) 0))
9821 (setq changes (append changes (cdr (assoc state l)))))
9822 (when (member state org-not-done-keywords)
9823 (setq changes (append changes (cdr (assoc 'todo l)))))
9824 (when (member state org-done-keywords)
9825 (setq changes (append changes (cdr (assoc 'done l)))))
9826 (dolist (c changes)
9827 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9829 (defun org-local-logging (value)
9830 "Get logging settings from a property VALUE."
9831 (let* (words w a)
9832 ;; directly set the variables, they are already local.
9833 (setq org-log-done nil
9834 org-log-repeat nil
9835 org-todo-log-states nil)
9836 (setq words (org-split-string value))
9837 (while (setq w (pop words))
9838 (cond
9839 ((setq a (assoc w org-startup-options))
9840 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9841 (set (nth 1 a) (nth 2 a))))
9842 ((setq a (org-extract-log-state-settings w))
9843 (and (member (car a) org-todo-keywords-1)
9844 (push a org-todo-log-states)))))))
9846 (defun org-get-todo-sequence-head (kwd)
9847 "Return the head of the TODO sequence to which KWD belongs.
9848 If KWD is not set, check if there is a text property remembering the
9849 right sequence."
9850 (let (p)
9851 (cond
9852 ((not kwd)
9853 (or (get-text-property (point-at-bol) 'org-todo-head)
9854 (progn
9855 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9856 nil (point-at-eol)))
9857 (get-text-property p 'org-todo-head))))
9858 ((not (member kwd org-todo-keywords-1))
9859 (car org-todo-keywords-1))
9860 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9862 (defun org-fast-todo-selection ()
9863 "Fast TODO keyword selection with single keys.
9864 Returns the new TODO keyword, or nil if no state change should occur."
9865 (let* ((fulltable org-todo-key-alist)
9866 (done-keywords org-done-keywords) ;; needed for the faces.
9867 (maxlen (apply 'max (mapcar
9868 (lambda (x)
9869 (if (stringp (car x)) (string-width (car x)) 0))
9870 fulltable)))
9871 (expert nil)
9872 (fwidth (+ maxlen 3 1 3))
9873 (ncol (/ (- (window-width) 4) fwidth))
9874 tg cnt e c tbl
9875 groups ingroup)
9876 (save-excursion
9877 (save-window-excursion
9878 (if expert
9879 (set-buffer (get-buffer-create " *Org todo*"))
9880 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9881 (erase-buffer)
9882 (org-set-local 'org-done-keywords done-keywords)
9883 (setq tbl fulltable cnt 0)
9884 (while (setq e (pop tbl))
9885 (cond
9886 ((equal e '(:startgroup))
9887 (push '() groups) (setq ingroup t)
9888 (when (not (= cnt 0))
9889 (setq cnt 0)
9890 (insert "\n"))
9891 (insert "{ "))
9892 ((equal e '(:endgroup))
9893 (setq ingroup nil cnt 0)
9894 (insert "}\n"))
9895 ((equal e '(:newline))
9896 (when (not (= cnt 0))
9897 (setq cnt 0)
9898 (insert "\n")
9899 (setq e (car tbl))
9900 (while (equal (car tbl) '(:newline))
9901 (insert "\n")
9902 (setq tbl (cdr tbl)))))
9904 (setq tg (car e) c (cdr e))
9905 (if ingroup (push tg (car groups)))
9906 (setq tg (org-add-props tg nil 'face
9907 (org-get-todo-face tg)))
9908 (if (and (= cnt 0) (not ingroup)) (insert " "))
9909 (insert "[" c "] " tg (make-string
9910 (- fwidth 4 (length tg)) ?\ ))
9911 (when (= (setq cnt (1+ cnt)) ncol)
9912 (insert "\n")
9913 (if ingroup (insert " "))
9914 (setq cnt 0)))))
9915 (insert "\n")
9916 (goto-char (point-min))
9917 (if (not expert) (org-fit-window-to-buffer))
9918 (message "[a-z..]:Set [SPC]:clear")
9919 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9920 (cond
9921 ((or (= c ?\C-g)
9922 (and (= c ?q) (not (rassoc c fulltable))))
9923 (setq quit-flag t))
9924 ((= c ?\ ) nil)
9925 ((setq e (rassoc c fulltable) tg (car e))
9927 (t (setq quit-flag t)))))))
9929 (defun org-entry-is-todo-p ()
9930 (member (org-get-todo-state) org-not-done-keywords))
9932 (defun org-entry-is-done-p ()
9933 (member (org-get-todo-state) org-done-keywords))
9935 (defun org-get-todo-state ()
9936 (save-excursion
9937 (org-back-to-heading t)
9938 (and (looking-at org-todo-line-regexp)
9939 (match-end 2)
9940 (match-string 2))))
9942 (defun org-at-date-range-p (&optional inactive-ok)
9943 "Is the cursor inside a date range?"
9944 (interactive)
9945 (save-excursion
9946 (catch 'exit
9947 (let ((pos (point)))
9948 (skip-chars-backward "^[<\r\n")
9949 (skip-chars-backward "<[")
9950 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9951 (>= (match-end 0) pos)
9952 (throw 'exit t))
9953 (skip-chars-backward "^<[\r\n")
9954 (skip-chars-backward "<[")
9955 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9956 (>= (match-end 0) pos)
9957 (throw 'exit t)))
9958 nil)))
9960 (defun org-get-repeat ()
9961 "Check if there is a deadline/schedule with repeater in this entry."
9962 (save-match-data
9963 (save-excursion
9964 (org-back-to-heading t)
9965 (if (re-search-forward
9966 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9967 (match-string 1)))))
9969 (defvar org-last-changed-timestamp)
9970 (defvar org-last-inserted-timestamp)
9971 (defvar org-log-post-message)
9972 (defvar org-log-note-purpose)
9973 (defvar org-log-note-how)
9974 (defvar org-log-note-extra)
9975 (defun org-auto-repeat-maybe (done-word)
9976 "Check if the current headline contains a repeated deadline/schedule.
9977 If yes, set TODO state back to what it was and change the base date
9978 of repeating deadline/scheduled time stamps to new date.
9979 This function is run automatically after each state change to a DONE state."
9980 ;; last-state is dynamically scoped into this function
9981 (let* ((repeat (org-get-repeat))
9982 (aa (assoc last-state org-todo-kwd-alist))
9983 (interpret (nth 1 aa))
9984 (head (nth 2 aa))
9985 (whata '(("d" . day) ("m" . month) ("y" . year)))
9986 (msg "Entry repeats: ")
9987 (org-log-done nil)
9988 (org-todo-log-states nil)
9989 (nshiftmax 10) (nshift 0)
9990 re type n what ts time)
9991 (when repeat
9992 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9993 (org-todo (if (eq interpret 'type) last-state head))
9994 (org-entry-put nil "LAST_REPEAT" (format-time-string
9995 (org-time-stamp-format t t)))
9996 (when org-log-repeat
9997 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9998 (memq 'org-add-log-note post-command-hook))
9999 ;; OK, we are already setup for some record
10000 (if (eq org-log-repeat 'note)
10001 ;; make sure we take a note, not only a time stamp
10002 (setq org-log-note-how 'note))
10003 ;; Set up for taking a record
10004 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10005 last-state
10006 'findpos org-log-repeat)))
10007 (org-back-to-heading t)
10008 (org-add-planning-info nil nil 'closed)
10009 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10010 org-deadline-time-regexp "\\)\\|\\("
10011 org-ts-regexp "\\)"))
10012 (while (re-search-forward
10013 re (save-excursion (outline-next-heading) (point)) t)
10014 (setq type (if (match-end 1) org-scheduled-string
10015 (if (match-end 3) org-deadline-string "Plain:"))
10016 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10017 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10018 (setq n (string-to-number (match-string 2 ts))
10019 what (match-string 3 ts))
10020 (if (equal what "w") (setq n (* n 7) what "d"))
10021 ;; Preparation, see if we need to modify the start date for the change
10022 (when (match-end 1)
10023 (setq time (save-match-data (org-time-string-to-time ts)))
10024 (cond
10025 ((equal (match-string 1 ts) ".")
10026 ;; Shift starting date to today
10027 (org-timestamp-change
10028 (- (time-to-days (current-time)) (time-to-days time))
10029 'day))
10030 ((equal (match-string 1 ts) "+")
10031 (while (or (= nshift 0)
10032 (<= (time-to-days time) (time-to-days (current-time))))
10033 (when (= (incf nshift) nshiftmax)
10034 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10035 (error "Abort")))
10036 (org-timestamp-change n (cdr (assoc what whata)))
10037 (org-at-timestamp-p t)
10038 (setq ts (match-string 1))
10039 (setq time (save-match-data (org-time-string-to-time ts))))
10040 (org-timestamp-change (- n) (cdr (assoc what whata)))
10041 ;; rematch, so that we have everything in place for the real shift
10042 (org-at-timestamp-p t)
10043 (setq ts (match-string 1))
10044 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10045 (org-timestamp-change n (cdr (assoc what whata)))
10046 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10047 (setq org-log-post-message msg)
10048 (message "%s" msg))))
10050 (defun org-show-todo-tree (arg)
10051 "Make a compact tree which shows all headlines marked with TODO.
10052 The tree will show the lines where the regexp matches, and all higher
10053 headlines above the match.
10054 With a \\[universal-argument] prefix, prompt for a regexp to match.
10055 With a numeric prefix N, construct a sparse tree for the Nth element
10056 of `org-todo-keywords-1'."
10057 (interactive "P")
10058 (let ((case-fold-search nil)
10059 (kwd-re
10060 (cond ((null arg) org-not-done-regexp)
10061 ((equal arg '(4))
10062 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10063 (mapcar 'list org-todo-keywords-1))))
10064 (concat "\\("
10065 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10066 "\\)\\>")))
10067 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10068 (regexp-quote (nth (1- (prefix-numeric-value arg))
10069 org-todo-keywords-1)))
10070 (t (error "Invalid prefix argument: %s" arg)))))
10071 (message "%d TODO entries found"
10072 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10074 (defun org-deadline (&optional remove time)
10075 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10076 With argument REMOVE, remove any deadline from the item.
10077 When TIME is set, it should be an internal time specification, and the
10078 scheduling will use the corresponding date."
10079 (interactive "P")
10080 (if remove
10081 (progn
10082 (org-remove-timestamp-with-keyword org-deadline-string)
10083 (message "Item no longer has a deadline."))
10084 (if (org-get-repeat)
10085 (error "Cannot change deadline on task with repeater, please do that by hand")
10086 (org-add-planning-info 'deadline time 'closed)
10087 (message "Deadline on %s" org-last-inserted-timestamp))))
10089 (defun org-schedule (&optional remove time)
10090 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10091 With argument REMOVE, remove any scheduling date from the item.
10092 When TIME is set, it should be an internal time specification, and the
10093 scheduling will use the corresponding date."
10094 (interactive "P")
10095 (if remove
10096 (progn
10097 (org-remove-timestamp-with-keyword org-scheduled-string)
10098 (message "Item is no longer scheduled."))
10099 (if (org-get-repeat)
10100 (error "Cannot reschedule task with repeater, please do that by hand")
10101 (org-add-planning-info 'scheduled time 'closed)
10102 (message "Scheduled to %s" org-last-inserted-timestamp))))
10104 (defun org-get-scheduled-time (pom &optional inherit)
10105 "Get the scheduled time as a time tuple, of a format suitable
10106 for calling org-schedule with, or if there is no scheduling,
10107 returns nil."
10108 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10109 (when time
10110 (apply 'encode-time (org-parse-time-string time)))))
10112 (defun org-get-deadline-time (pom &optional inherit)
10113 "Get the deadine as a time tuple, of a format suitable for
10114 calling org-deadlin with, or if there is no scheduling, returns
10115 nil."
10116 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10117 (when time
10118 (apply 'encode-time (org-parse-time-string time)))))
10120 (defun org-remove-timestamp-with-keyword (keyword)
10121 "Remove all time stamps with KEYWORD in the current entry."
10122 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10123 beg)
10124 (save-excursion
10125 (org-back-to-heading t)
10126 (setq beg (point))
10127 (outline-next-heading)
10128 (while (re-search-backward re beg t)
10129 (replace-match "")
10130 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10131 (equal (char-before) ?\ ))
10132 (backward-delete-char 1)
10133 (if (string-match "^[ \t]*$" (buffer-substring
10134 (point-at-bol) (point-at-eol)))
10135 (delete-region (point-at-bol)
10136 (min (point-max) (1+ (point-at-eol))))))))))
10138 (defun org-add-planning-info (what &optional time &rest remove)
10139 "Insert new timestamp with keyword in the line directly after the headline.
10140 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10141 If non is given, the user is prompted for a date.
10142 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10143 be removed."
10144 (interactive)
10145 (let (org-time-was-given org-end-time-was-given ts
10146 end default-time default-input)
10148 (catch 'exit
10149 (when (and (not time) (memq what '(scheduled deadline)))
10150 ;; Try to get a default date/time from existing timestamp
10151 (save-excursion
10152 (org-back-to-heading t)
10153 (setq end (save-excursion (outline-next-heading) (point)))
10154 (when (re-search-forward (if (eq what 'scheduled)
10155 org-scheduled-time-regexp
10156 org-deadline-time-regexp)
10157 end t)
10158 (setq ts (match-string 1)
10159 default-time
10160 (apply 'encode-time (org-parse-time-string ts))
10161 default-input (and ts (org-get-compact-tod ts))))))
10162 (when what
10163 ;; If necessary, get the time from the user
10164 (setq time (or time (org-read-date nil 'to-time nil nil
10165 default-time default-input))))
10167 (when (and org-insert-labeled-timestamps-at-point
10168 (member what '(scheduled deadline)))
10169 (insert
10170 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10171 (org-insert-time-stamp time org-time-was-given
10172 nil nil nil (list org-end-time-was-given))
10173 (setq what nil))
10174 (save-excursion
10175 (save-restriction
10176 (let (col list elt ts buffer-invisibility-spec)
10177 (org-back-to-heading t)
10178 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10179 (goto-char (match-end 1))
10180 (setq col (current-column))
10181 (goto-char (match-end 0))
10182 (if (eobp) (insert "\n") (forward-char 1))
10183 (when (and (not what)
10184 (not (looking-at
10185 (concat "[ \t]*"
10186 org-keyword-time-not-clock-regexp))))
10187 ;; Nothing to add, nothing to remove...... :-)
10188 (throw 'exit nil))
10189 (if (and (not (looking-at outline-regexp))
10190 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10191 "[^\r\n]*"))
10192 (not (equal (match-string 1) org-clock-string)))
10193 (narrow-to-region (match-beginning 0) (match-end 0))
10194 (insert-before-markers "\n")
10195 (backward-char 1)
10196 (narrow-to-region (point) (point))
10197 (and org-adapt-indentation (org-indent-to-column col)))
10198 ;; Check if we have to remove something.
10199 (setq list (cons what remove))
10200 (while list
10201 (setq elt (pop list))
10202 (goto-char (point-min))
10203 (when (or (and (eq elt 'scheduled)
10204 (re-search-forward org-scheduled-time-regexp nil t))
10205 (and (eq elt 'deadline)
10206 (re-search-forward org-deadline-time-regexp nil t))
10207 (and (eq elt 'closed)
10208 (re-search-forward org-closed-time-regexp nil t)))
10209 (replace-match "")
10210 (if (looking-at "--+<[^>]+>") (replace-match ""))
10211 (skip-chars-backward " ")
10212 (if (looking-at " +") (replace-match ""))))
10213 (goto-char (point-max))
10214 (when what
10215 (insert
10216 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10217 (cond ((eq what 'scheduled) org-scheduled-string)
10218 ((eq what 'deadline) org-deadline-string)
10219 ((eq what 'closed) org-closed-string))
10220 " ")
10221 (setq ts (org-insert-time-stamp
10222 time
10223 (or org-time-was-given
10224 (and (eq what 'closed) org-log-done-with-time))
10225 (eq what 'closed)
10226 nil nil (list org-end-time-was-given)))
10227 (end-of-line 1))
10228 (goto-char (point-min))
10229 (widen)
10230 (if (and (looking-at "[ \t]+\n")
10231 (equal (char-before) ?\n))
10232 (delete-region (1- (point)) (point-at-eol)))
10233 ts))))))
10235 (defvar org-log-note-marker (make-marker))
10236 (defvar org-log-note-purpose nil)
10237 (defvar org-log-note-state nil)
10238 (defvar org-log-note-previous-state nil)
10239 (defvar org-log-note-how nil)
10240 (defvar org-log-note-extra nil)
10241 (defvar org-log-note-window-configuration nil)
10242 (defvar org-log-note-return-to (make-marker))
10243 (defvar org-log-post-message nil
10244 "Message to be displayed after a log note has been stored.
10245 The auto-repeater uses this.")
10247 (defun org-add-note ()
10248 "Add a note to the current entry.
10249 This is done in the same way as adding a state change note."
10250 (interactive)
10251 (org-add-log-setup 'note nil nil 'findpos nil))
10253 (defvar org-property-end-re)
10254 (defun org-add-log-setup (&optional purpose state prev-state
10255 findpos how &optional extra)
10256 "Set up the post command hook to take a note.
10257 If this is about to TODO state change, the new state is expected in STATE.
10258 When FINDPOS is non-nil, find the correct position for the note in
10259 the current entry. If not, assume that it can be inserted at point.
10260 HOW is an indicator what kind of note should be created.
10261 EXTRA is additional text that will be inserted into the notes buffer."
10262 (let* ((org-log-into-drawer (org-log-into-drawer))
10263 (drawer (cond ((stringp org-log-into-drawer)
10264 org-log-into-drawer)
10265 (org-log-into-drawer "LOGBOOK")
10266 (t nil))))
10267 (save-restriction
10268 (save-excursion
10269 (when findpos
10270 (org-back-to-heading t)
10271 (narrow-to-region (point) (save-excursion
10272 (outline-next-heading) (point)))
10273 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10274 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10275 "[^\r\n]*\\)?"))
10276 (goto-char (match-end 0))
10277 (cond
10278 (drawer
10279 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10280 nil t)
10281 (progn
10282 (goto-char (match-end 0))
10283 (or org-log-states-order-reversed
10284 (and (re-search-forward org-property-end-re nil t)
10285 (goto-char (1- (match-beginning 0))))))
10286 (insert "\n:" drawer ":\n:END:")
10287 (beginning-of-line 0)
10288 (org-indent-line-function)
10289 (beginning-of-line 2)
10290 (org-indent-line-function)
10291 (end-of-line 0)))
10292 ((and org-log-state-notes-insert-after-drawers
10293 (save-excursion
10294 (forward-line) (looking-at org-drawer-regexp)))
10295 (forward-line)
10296 (while (looking-at org-drawer-regexp)
10297 (goto-char (match-end 0))
10298 (re-search-forward org-property-end-re (point-max) t)
10299 (forward-line))
10300 (forward-line -1)))
10301 (unless org-log-states-order-reversed
10302 (and (= (char-after) ?\n) (forward-char 1))
10303 (org-skip-over-state-notes)
10304 (skip-chars-backward " \t\n\r")))
10305 (move-marker org-log-note-marker (point))
10306 (setq org-log-note-purpose purpose
10307 org-log-note-state state
10308 org-log-note-previous-state prev-state
10309 org-log-note-how how
10310 org-log-note-extra extra)
10311 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10313 (defun org-skip-over-state-notes ()
10314 "Skip past the list of State notes in an entry."
10315 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10316 (while (looking-at "[ \t]*- State")
10317 (condition-case nil
10318 (org-next-item)
10319 (error (org-end-of-item)))))
10321 (defun org-add-log-note (&optional purpose)
10322 "Pop up a window for taking a note, and add this note later at point."
10323 (remove-hook 'post-command-hook 'org-add-log-note)
10324 (setq org-log-note-window-configuration (current-window-configuration))
10325 (delete-other-windows)
10326 (move-marker org-log-note-return-to (point))
10327 (switch-to-buffer (marker-buffer org-log-note-marker))
10328 (goto-char org-log-note-marker)
10329 (org-switch-to-buffer-other-window "*Org Note*")
10330 (erase-buffer)
10331 (if (memq org-log-note-how '(time state))
10332 (let (current-prefix-arg) (org-store-log-note))
10333 (let ((org-inhibit-startup t)) (org-mode))
10334 (insert (format "# Insert note for %s.
10335 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10336 (cond
10337 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10338 ((eq org-log-note-purpose 'done) "closed todo item")
10339 ((eq org-log-note-purpose 'state)
10340 (format "state change from \"%s\" to \"%s\""
10341 (or org-log-note-previous-state "")
10342 (or org-log-note-state "")))
10343 ((eq org-log-note-purpose 'note)
10344 "this entry")
10345 (t (error "This should not happen")))))
10346 (if org-log-note-extra (insert org-log-note-extra))
10347 (org-set-local 'org-finish-function 'org-store-log-note)))
10349 (defvar org-note-abort nil) ; dynamically scoped
10350 (defun org-store-log-note ()
10351 "Finish taking a log note, and insert it to where it belongs."
10352 (let ((txt (buffer-string))
10353 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10354 lines ind)
10355 (kill-buffer (current-buffer))
10356 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10357 (setq txt (replace-match "" t t txt)))
10358 (if (string-match "\\s-+\\'" txt)
10359 (setq txt (replace-match "" t t txt)))
10360 (setq lines (org-split-string txt "\n"))
10361 (when (and note (string-match "\\S-" note))
10362 (setq note
10363 (org-replace-escapes
10364 note
10365 (list (cons "%u" (user-login-name))
10366 (cons "%U" user-full-name)
10367 (cons "%t" (format-time-string
10368 (org-time-stamp-format 'long 'inactive)
10369 (current-time)))
10370 (cons "%s" (if org-log-note-state
10371 (concat "\"" org-log-note-state "\"")
10372 ""))
10373 (cons "%S" (if org-log-note-previous-state
10374 (concat "\"" org-log-note-previous-state "\"")
10375 "\"\"")))))
10376 (if lines (setq note (concat note " \\\\")))
10377 (push note lines))
10378 (when (or current-prefix-arg org-note-abort)
10379 (when org-log-into-drawer
10380 (org-remove-empty-drawer-at
10381 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10382 org-log-note-marker))
10383 (setq lines nil))
10384 (when lines
10385 (save-excursion
10386 (set-buffer (marker-buffer org-log-note-marker))
10387 (save-excursion
10388 (goto-char org-log-note-marker)
10389 (move-marker org-log-note-marker nil)
10390 (end-of-line 1)
10391 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10392 (insert "- " (pop lines))
10393 (org-indent-line-function)
10394 (beginning-of-line 1)
10395 (looking-at "[ \t]*")
10396 (setq ind (concat (match-string 0) " "))
10397 (end-of-line 1)
10398 (while lines (insert "\n" ind (pop lines)))
10399 (message "Note stored")
10400 (org-back-to-heading t)
10401 (org-cycle-hide-drawers 'children)))))
10402 (set-window-configuration org-log-note-window-configuration)
10403 (with-current-buffer (marker-buffer org-log-note-return-to)
10404 (goto-char org-log-note-return-to))
10405 (move-marker org-log-note-return-to nil)
10406 (and org-log-post-message (message "%s" org-log-post-message)))
10408 (defun org-remove-empty-drawer-at (drawer pos)
10409 "Remove an emptyr DARWER drawer at position POS.
10410 POS may also be a marker."
10411 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10412 (save-excursion
10413 (save-restriction
10414 (widen)
10415 (goto-char pos)
10416 (if (org-in-regexp
10417 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10418 (replace-match ""))))))
10420 (defun org-sparse-tree (&optional arg)
10421 "Create a sparse tree, prompt for the details.
10422 This command can create sparse trees. You first need to select the type
10423 of match used to create the tree:
10425 t Show entries with a specific TODO keyword.
10426 m Show entries selected by a tags/property match.
10427 p Enter a property name and its value (both with completion on existing
10428 names/values) and show entries with that property.
10429 r Show entries matching a regular expression.
10430 d Show deadlines due within `org-deadline-warning-days'.
10431 b Show deadlines and scheduled items before a date.
10432 a Show deadlines and scheduled items after a date."
10433 (interactive "P")
10434 (let (ans kwd value)
10435 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10436 (setq ans (read-char-exclusive))
10437 (cond
10438 ((equal ans ?d)
10439 (call-interactively 'org-check-deadlines))
10440 ((equal ans ?b)
10441 (call-interactively 'org-check-before-date))
10442 ((equal ans ?a)
10443 (call-interactively 'org-check-after-date))
10444 ((equal ans ?t)
10445 (org-show-todo-tree '(4)))
10446 ((member ans '(?T ?m))
10447 (call-interactively 'org-match-sparse-tree))
10448 ((member ans '(?p ?P))
10449 (setq kwd (org-icompleting-read "Property: "
10450 (mapcar 'list (org-buffer-property-keys))))
10451 (setq value (org-icompleting-read "Value: "
10452 (mapcar 'list (org-property-values kwd))))
10453 (unless (string-match "\\`{.*}\\'" value)
10454 (setq value (concat "\"" value "\"")))
10455 (org-match-sparse-tree arg (concat kwd "=" value)))
10456 ((member ans '(?r ?R ?/))
10457 (call-interactively 'org-occur))
10458 (t (error "No such sparse tree command \"%c\"" ans)))))
10460 (defvar org-occur-highlights nil
10461 "List of overlays used for occur matches.")
10462 (make-variable-buffer-local 'org-occur-highlights)
10463 (defvar org-occur-parameters nil
10464 "Parameters of the active org-occur calls.
10465 This is a list, each call to org-occur pushes as cons cell,
10466 containing the regular expression and the callback, onto the list.
10467 The list can contain several entries if `org-occur' has been called
10468 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10469 will only contain one set of parameters. When the highlights are
10470 removed (for example with `C-c C-c', or with the next edit (depending
10471 on `org-remove-highlights-with-change'), this variable is emptied
10472 as well.")
10473 (make-variable-buffer-local 'org-occur-parameters)
10475 (defun org-occur (regexp &optional keep-previous callback)
10476 "Make a compact tree which shows all matches of REGEXP.
10477 The tree will show the lines where the regexp matches, and all higher
10478 headlines above the match. It will also show the heading after the match,
10479 to make sure editing the matching entry is easy.
10480 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10481 call to `org-occur' will be kept, to allow stacking of calls to this
10482 command.
10483 If CALLBACK is non-nil, it is a function which is called to confirm
10484 that the match should indeed be shown."
10485 (interactive "sRegexp: \nP")
10486 (when (equal regexp "")
10487 (error "Regexp cannot be empty"))
10488 (unless keep-previous
10489 (org-remove-occur-highlights nil nil t))
10490 (push (cons regexp callback) org-occur-parameters)
10491 (let ((cnt 0))
10492 (save-excursion
10493 (goto-char (point-min))
10494 (if (or (not keep-previous) ; do not want to keep
10495 (not org-occur-highlights)) ; no previous matches
10496 ;; hide everything
10497 (org-overview))
10498 (while (re-search-forward regexp nil t)
10499 (when (or (not callback)
10500 (save-match-data (funcall callback)))
10501 (setq cnt (1+ cnt))
10502 (when org-highlight-sparse-tree-matches
10503 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10504 (org-show-context 'occur-tree))))
10505 (when org-remove-highlights-with-change
10506 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10507 nil 'local))
10508 (unless org-sparse-tree-open-archived-trees
10509 (org-hide-archived-subtrees (point-min) (point-max)))
10510 (run-hooks 'org-occur-hook)
10511 (if (interactive-p)
10512 (message "%d match(es) for regexp %s" cnt regexp))
10513 cnt))
10515 (defun org-show-context (&optional key)
10516 "Make sure point and context and visible.
10517 How much context is shown depends upon the variables
10518 `org-show-hierarchy-above', `org-show-following-heading'. and
10519 `org-show-siblings'."
10520 (let ((heading-p (org-on-heading-p t))
10521 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10522 (following-p (org-get-alist-option org-show-following-heading key))
10523 (entry-p (org-get-alist-option org-show-entry-below key))
10524 (siblings-p (org-get-alist-option org-show-siblings key)))
10525 (catch 'exit
10526 ;; Show heading or entry text
10527 (if (and heading-p (not entry-p))
10528 (org-flag-heading nil) ; only show the heading
10529 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10530 (org-show-hidden-entry))) ; show entire entry
10531 (when following-p
10532 ;; Show next sibling, or heading below text
10533 (save-excursion
10534 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10535 (org-flag-heading nil))))
10536 (when siblings-p (org-show-siblings))
10537 (when hierarchy-p
10538 ;; show all higher headings, possibly with siblings
10539 (save-excursion
10540 (while (and (condition-case nil
10541 (progn (org-up-heading-all 1) t)
10542 (error nil))
10543 (not (bobp)))
10544 (org-flag-heading nil)
10545 (when siblings-p (org-show-siblings))))))))
10547 (defun org-reveal (&optional siblings)
10548 "Show current entry, hierarchy above it, and the following headline.
10549 This can be used to show a consistent set of context around locations
10550 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10551 not t for the search context.
10553 With optional argument SIBLINGS, on each level of the hierarchy all
10554 siblings are shown. This repairs the tree structure to what it would
10555 look like when opened with hierarchical calls to `org-cycle'."
10556 (interactive "P")
10557 (let ((org-show-hierarchy-above t)
10558 (org-show-following-heading t)
10559 (org-show-siblings (if siblings t org-show-siblings)))
10560 (org-show-context nil)))
10562 (defun org-highlight-new-match (beg end)
10563 "Highlight from BEG to END and mark the highlight is an occur headline."
10564 (let ((ov (org-make-overlay beg end)))
10565 (org-overlay-put ov 'face 'secondary-selection)
10566 (push ov org-occur-highlights)))
10568 (defun org-remove-occur-highlights (&optional beg end noremove)
10569 "Remove the occur highlights from the buffer.
10570 BEG and END are ignored. If NOREMOVE is nil, remove this function
10571 from the `before-change-functions' in the current buffer."
10572 (interactive)
10573 (unless org-inhibit-highlight-removal
10574 (mapc 'org-delete-overlay org-occur-highlights)
10575 (setq org-occur-highlights nil)
10576 (setq org-occur-parameters nil)
10577 (unless noremove
10578 (remove-hook 'before-change-functions
10579 'org-remove-occur-highlights 'local))))
10581 ;;;; Priorities
10583 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10584 "Regular expression matching the priority indicator.")
10586 (defvar org-remove-priority-next-time nil)
10588 (defun org-priority-up ()
10589 "Increase the priority of the current item."
10590 (interactive)
10591 (org-priority 'up))
10593 (defun org-priority-down ()
10594 "Decrease the priority of the current item."
10595 (interactive)
10596 (org-priority 'down))
10598 (defun org-priority (&optional action)
10599 "Change the priority of an item by ARG.
10600 ACTION can be `set', `up', `down', or a character."
10601 (interactive)
10602 (unless org-enable-priority-commands
10603 (error "Priority commands are disabled"))
10604 (setq action (or action 'set))
10605 (let (current new news have remove)
10606 (save-excursion
10607 (org-back-to-heading t)
10608 (if (looking-at org-priority-regexp)
10609 (setq current (string-to-char (match-string 2))
10610 have t)
10611 (setq current org-default-priority))
10612 (cond
10613 ((or (eq action 'set)
10614 (if (featurep 'xemacs) (characterp action) (integerp action)))
10615 (if (not (eq action 'set))
10616 (setq new action)
10617 (message "Priority %c-%c, SPC to remove: "
10618 org-highest-priority org-lowest-priority)
10619 (setq new (read-char-exclusive)))
10620 (if (and (= (upcase org-highest-priority) org-highest-priority)
10621 (= (upcase org-lowest-priority) org-lowest-priority))
10622 (setq new (upcase new)))
10623 (cond ((equal new ?\ ) (setq remove t))
10624 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10625 (error "Priority must be between `%c' and `%c'"
10626 org-highest-priority org-lowest-priority))))
10627 ((eq action 'up)
10628 (if (and (not have) (eq last-command this-command))
10629 (setq new org-lowest-priority)
10630 (setq new (if (and org-priority-start-cycle-with-default (not have))
10631 org-default-priority (1- current)))))
10632 ((eq action 'down)
10633 (if (and (not have) (eq last-command this-command))
10634 (setq new org-highest-priority)
10635 (setq new (if (and org-priority-start-cycle-with-default (not have))
10636 org-default-priority (1+ current)))))
10637 (t (error "Invalid action")))
10638 (if (or (< (upcase new) org-highest-priority)
10639 (> (upcase new) org-lowest-priority))
10640 (setq remove t))
10641 (setq news (format "%c" new))
10642 (if have
10643 (if remove
10644 (replace-match "" t t nil 1)
10645 (replace-match news t t nil 2))
10646 (if remove
10647 (error "No priority cookie found in line")
10648 (let ((case-fold-search nil))
10649 (looking-at org-todo-line-regexp))
10650 (if (match-end 2)
10651 (progn
10652 (goto-char (match-end 2))
10653 (insert " [#" news "]"))
10654 (goto-char (match-beginning 3))
10655 (insert "[#" news "] "))))
10656 (org-preserve-lc (org-set-tags nil 'align)))
10657 (if remove
10658 (message "Priority removed")
10659 (message "Priority of current item set to %s" news))))
10661 (defun org-get-priority (s)
10662 "Find priority cookie and return priority."
10663 (save-match-data
10664 (if (not (string-match org-priority-regexp s))
10665 (* 1000 (- org-lowest-priority org-default-priority))
10666 (* 1000 (- org-lowest-priority
10667 (string-to-char (match-string 2 s)))))))
10669 ;;;; Tags
10671 (defvar org-agenda-archives-mode)
10672 (defvar org-map-continue-from nil
10673 "Position from where mapping should continue.
10674 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10676 (defvar org-scanner-tags nil
10677 "The current tag list while the tags scanner is running.")
10678 (defvar org-trust-scanner-tags nil
10679 "Should `org-get-tags-at' use the tags fro the scanner.
10680 This is for internal dynamical scoping only.
10681 When this is non-nil, the function `org-get-tags-at' will return the value
10682 of `org-scanner-tags' instead of building the list by itself. This
10683 can lead to large speed-ups when the tags scanner is used in a file with
10684 many entries, and when the list of tags is retrieved, for example to
10685 obtain a list of properties. Building the tags list for each entry in such
10686 a file becomes an N^2 operation - but with this variable set, it scales
10687 as N.")
10689 (defun org-scan-tags (action matcher &optional todo-only)
10690 "Scan headline tags with inheritance and produce output ACTION.
10692 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10693 or `agenda' to produce an entry list for an agenda view. It can also be
10694 a Lisp form or a function that should be called at each matched headline, in
10695 this case the return value is a list of all return values from these calls.
10697 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10698 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10699 only lines with a TODO keyword are included in the output."
10700 (require 'org-agenda)
10701 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10702 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10703 (org-re
10704 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10705 (props (list 'face 'default
10706 'done-face 'org-agenda-done
10707 'undone-face 'default
10708 'mouse-face 'highlight
10709 'org-not-done-regexp org-not-done-regexp
10710 'org-todo-regexp org-todo-regexp
10711 'keymap org-agenda-keymap
10712 'help-echo
10713 (format "mouse-2 or RET jump to org file %s"
10714 (abbreviate-file-name
10715 (or (buffer-file-name (buffer-base-buffer))
10716 (buffer-name (buffer-base-buffer)))))))
10717 (case-fold-search nil)
10718 (org-map-continue-from nil)
10719 lspos tags tags-list
10720 (tags-alist (list (cons 0 org-file-tags)))
10721 (llast 0) rtn rtn1 level category i txt
10722 todo marker entry priority)
10723 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10724 (setq action (list 'lambda nil action)))
10725 (save-excursion
10726 (goto-char (point-min))
10727 (when (eq action 'sparse-tree)
10728 (org-overview)
10729 (org-remove-occur-highlights))
10730 (while (re-search-forward re nil t)
10731 (catch :skip
10732 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10733 tags (if (match-end 4) (org-match-string-no-properties 4)))
10734 (goto-char (setq lspos (match-beginning 0)))
10735 (setq level (org-reduced-level (funcall outline-level))
10736 category (org-get-category))
10737 (setq i llast llast level)
10738 ;; remove tag lists from same and sublevels
10739 (while (>= i level)
10740 (when (setq entry (assoc i tags-alist))
10741 (setq tags-alist (delete entry tags-alist)))
10742 (setq i (1- i)))
10743 ;; add the next tags
10744 (when tags
10745 (setq tags (org-split-string tags ":")
10746 tags-alist
10747 (cons (cons level tags) tags-alist)))
10748 ;; compile tags for current headline
10749 (setq tags-list
10750 (if org-use-tag-inheritance
10751 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10752 tags)
10753 org-scanner-tags tags-list)
10754 (when org-use-tag-inheritance
10755 (setcdr (car tags-alist)
10756 (mapcar (lambda (x)
10757 (setq x (copy-sequence x))
10758 (org-add-prop-inherited x))
10759 (cdar tags-alist))))
10760 (when (and tags org-use-tag-inheritance
10761 (or (not (eq t org-use-tag-inheritance))
10762 org-tags-exclude-from-inheritance))
10763 ;; selective inheritance, remove uninherited ones
10764 (setcdr (car tags-alist)
10765 (org-remove-uniherited-tags (cdar tags-alist))))
10766 (when (and (or (not todo-only)
10767 (and (member todo org-not-done-keywords)
10768 (or (not org-agenda-tags-todo-honor-ignore-options)
10769 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10770 (let ((case-fold-search t)) (eval matcher))
10772 (not (member org-archive-tag tags-list))
10773 ;; we have an archive tag, should we use this anyway?
10774 (or (not org-agenda-skip-archived-trees)
10775 (and (eq action 'agenda) org-agenda-archives-mode))))
10776 (unless (eq action 'sparse-tree) (org-agenda-skip))
10778 ;; select this headline
10780 (cond
10781 ((eq action 'sparse-tree)
10782 (and org-highlight-sparse-tree-matches
10783 (org-get-heading) (match-end 0)
10784 (org-highlight-new-match
10785 (match-beginning 0) (match-beginning 1)))
10786 (org-show-context 'tags-tree))
10787 ((eq action 'agenda)
10788 (setq txt (org-format-agenda-item
10790 (concat
10791 (if (eq org-tags-match-list-sublevels 'indented)
10792 (make-string (1- level) ?.) "")
10793 (org-get-heading))
10794 category
10795 tags-list
10797 priority (org-get-priority txt))
10798 (goto-char lspos)
10799 (setq marker (org-agenda-new-marker))
10800 (org-add-props txt props
10801 'org-marker marker 'org-hd-marker marker 'org-category category
10802 'todo-state todo
10803 'priority priority 'type "tagsmatch")
10804 (push txt rtn))
10805 ((functionp action)
10806 (setq org-map-continue-from nil)
10807 (save-excursion
10808 (setq rtn1 (funcall action))
10809 (push rtn1 rtn)))
10810 (t (error "Invalid action")))
10812 ;; if we are to skip sublevels, jump to end of subtree
10813 (unless org-tags-match-list-sublevels
10814 (org-end-of-subtree t)
10815 (backward-char 1))))
10816 ;; Get the correct position from where to continue
10817 (if org-map-continue-from
10818 (goto-char org-map-continue-from)
10819 (and (= (point) lspos) (end-of-line 1)))))
10820 (when (and (eq action 'sparse-tree)
10821 (not org-sparse-tree-open-archived-trees))
10822 (org-hide-archived-subtrees (point-min) (point-max)))
10823 (nreverse rtn)))
10825 (defun org-remove-uniherited-tags (tags)
10826 "Remove all tags that are not inherited from the list TAGS."
10827 (cond
10828 ((eq org-use-tag-inheritance t)
10829 (if org-tags-exclude-from-inheritance
10830 (org-delete-all org-tags-exclude-from-inheritance tags)
10831 tags))
10832 ((not org-use-tag-inheritance) nil)
10833 ((stringp org-use-tag-inheritance)
10834 (delq nil (mapcar
10835 (lambda (x)
10836 (if (and (string-match org-use-tag-inheritance x)
10837 (not (member x org-tags-exclude-from-inheritance)))
10838 x nil))
10839 tags)))
10840 ((listp org-use-tag-inheritance)
10841 (delq nil (mapcar
10842 (lambda (x)
10843 (if (member x org-use-tag-inheritance) x nil))
10844 tags)))))
10846 (defvar todo-only) ;; dynamically scoped
10848 (defun org-match-sparse-tree (&optional todo-only match)
10849 "Create a sparse tree according to tags string MATCH.
10850 MATCH can contain positive and negative selection of tags, like
10851 \"+WORK+URGENT-WITHBOSS\".
10852 If optional argument TODO-ONLY is non-nil, only select lines that are
10853 also TODO lines."
10854 (interactive "P")
10855 (org-prepare-agenda-buffers (list (current-buffer)))
10856 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10858 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10860 (defvar org-cached-props nil)
10861 (defun org-cached-entry-get (pom property)
10862 (if (or (eq t org-use-property-inheritance)
10863 (and (stringp org-use-property-inheritance)
10864 (string-match org-use-property-inheritance property))
10865 (and (listp org-use-property-inheritance)
10866 (member property org-use-property-inheritance)))
10867 ;; Caching is not possible, check it directly
10868 (org-entry-get pom property 'inherit)
10869 ;; Get all properties, so that we can do complicated checks easily
10870 (cdr (assoc property (or org-cached-props
10871 (setq org-cached-props
10872 (org-entry-properties pom)))))))
10874 (defun org-global-tags-completion-table (&optional files)
10875 "Return the list of all tags in all agenda buffer/files."
10876 (save-excursion
10877 (org-uniquify
10878 (delq nil
10879 (apply 'append
10880 (mapcar
10881 (lambda (file)
10882 (set-buffer (find-file-noselect file))
10883 (append (org-get-buffer-tags)
10884 (mapcar (lambda (x) (if (stringp (car-safe x))
10885 (list (car-safe x)) nil))
10886 org-tag-alist)))
10887 (if (and files (car files))
10888 files
10889 (org-agenda-files))))))))
10891 (defun org-make-tags-matcher (match)
10892 "Create the TAGS//TODO matcher form for the selection string MATCH."
10893 ;; todo-only is scoped dynamically into this function, and the function
10894 ;; may change it if the matcher asks for it.
10895 (unless match
10896 ;; Get a new match request, with completion
10897 (let ((org-last-tags-completion-table
10898 (org-global-tags-completion-table)))
10899 (setq match (org-completing-read-no-i
10900 "Match: " 'org-tags-completion-function nil nil nil
10901 'org-tags-history))))
10903 ;; Parse the string and create a lisp form
10904 (let ((match0 match)
10905 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10906 minus tag mm
10907 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10908 orterms term orlist re-p str-p level-p level-op time-p
10909 prop-p pn pv po cat-p gv rest)
10910 (if (string-match "/+" match)
10911 ;; match contains also a todo-matching request
10912 (progn
10913 (setq tagsmatch (substring match 0 (match-beginning 0))
10914 todomatch (substring match (match-end 0)))
10915 (if (string-match "^!" todomatch)
10916 (setq todo-only t todomatch (substring todomatch 1)))
10917 (if (string-match "^\\s-*$" todomatch)
10918 (setq todomatch nil)))
10919 ;; only matching tags
10920 (setq tagsmatch match todomatch nil))
10922 ;; Make the tags matcher
10923 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10924 (setq tagsmatcher t)
10925 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10926 (while (setq term (pop orterms))
10927 (while (and (equal (substring term -1) "\\") orterms)
10928 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10929 (while (string-match re term)
10930 (setq rest (substring term (match-end 0))
10931 minus (and (match-end 1)
10932 (equal (match-string 1 term) "-"))
10933 tag (match-string 2 term)
10934 re-p (equal (string-to-char tag) ?{)
10935 level-p (match-end 4)
10936 prop-p (match-end 5)
10937 mm (cond
10938 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10939 (level-p
10940 (setq level-op (org-op-to-function (match-string 3 term)))
10941 `(,level-op level ,(string-to-number
10942 (match-string 4 term))))
10943 (prop-p
10944 (setq pn (match-string 5 term)
10945 po (match-string 6 term)
10946 pv (match-string 7 term)
10947 cat-p (equal pn "CATEGORY")
10948 re-p (equal (string-to-char pv) ?{)
10949 str-p (equal (string-to-char pv) ?\")
10950 time-p (save-match-data
10951 (string-match "^\"[[<].*[]>]\"$" pv))
10952 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10953 (if time-p (setq pv (org-matcher-time pv)))
10954 (setq po (org-op-to-function po (if time-p 'time str-p)))
10955 (cond
10956 ((equal pn "CATEGORY")
10957 (setq gv '(get-text-property (point) 'org-category)))
10958 ((equal pn "TODO")
10959 (setq gv 'todo))
10961 (setq gv `(org-cached-entry-get nil ,pn))))
10962 (if re-p
10963 (if (eq po 'org<>)
10964 `(not (string-match ,pv (or ,gv "")))
10965 `(string-match ,pv (or ,gv "")))
10966 (if str-p
10967 `(,po (or ,gv "") ,pv)
10968 `(,po (string-to-number (or ,gv ""))
10969 ,(string-to-number pv) ))))
10970 (t `(member ,tag tags-list)))
10971 mm (if minus (list 'not mm) mm)
10972 term rest)
10973 (push mm tagsmatcher))
10974 (push (if (> (length tagsmatcher) 1)
10975 (cons 'and tagsmatcher)
10976 (car tagsmatcher))
10977 orlist)
10978 (setq tagsmatcher nil))
10979 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10980 (setq tagsmatcher
10981 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10982 ;; Make the todo matcher
10983 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10984 (setq todomatcher t)
10985 (setq orterms (org-split-string todomatch "|") orlist nil)
10986 (while (setq term (pop orterms))
10987 (while (string-match re term)
10988 (setq minus (and (match-end 1)
10989 (equal (match-string 1 term) "-"))
10990 kwd (match-string 2 term)
10991 re-p (equal (string-to-char kwd) ?{)
10992 term (substring term (match-end 0))
10993 mm (if re-p
10994 `(string-match ,(substring kwd 1 -1) todo)
10995 (list 'equal 'todo kwd))
10996 mm (if minus (list 'not mm) mm))
10997 (push mm todomatcher))
10998 (push (if (> (length todomatcher) 1)
10999 (cons 'and todomatcher)
11000 (car todomatcher))
11001 orlist)
11002 (setq todomatcher nil))
11003 (setq todomatcher (if (> (length orlist) 1)
11004 (cons 'or orlist) (car orlist))))
11006 ;; Return the string and lisp forms of the matcher
11007 (setq matcher (if todomatcher
11008 (list 'and tagsmatcher todomatcher)
11009 tagsmatcher))
11010 (cons match0 matcher)))
11012 (defun org-op-to-function (op &optional stringp)
11013 "Turn an operator into the appropriate function."
11014 (setq op
11015 (cond
11016 ((equal op "<" ) '(< string< org-time<))
11017 ((equal op ">" ) '(> org-string> org-time>))
11018 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11019 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11020 ((member op '("=" "==")) '(= string= org-time=))
11021 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11022 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11024 (defun org<> (a b) (not (= a b)))
11025 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11026 (defun org-string>= (a b) (not (string< a b)))
11027 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11028 (defun org-string<> (a b) (not (string= a b)))
11029 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11030 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11031 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11032 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11033 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11034 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11035 (defun org-2ft (s)
11036 "Convert S to a floating point time.
11037 If S is already a number, just return it. If it is a string, parse
11038 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11039 (cond
11040 ((numberp s) s)
11041 ((stringp s)
11042 (condition-case nil
11043 (float-time (apply 'encode-time (org-parse-time-string s)))
11044 (error 0.)))
11045 (t 0.)))
11047 (defun org-time-today ()
11048 "Time in seconds today at 0:00.
11049 Returns the float number of seconds since the beginning of the
11050 epoch to the beginning of today (00:00)."
11051 (float-time (apply 'encode-time
11052 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11054 (defun org-matcher-time (s)
11055 "Interpret a time comparison value."
11056 (save-match-data
11057 (cond
11058 ((string= s "<now>") (float-time))
11059 ((string= s "<today>") (org-time-today))
11060 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11061 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11062 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11063 (+ (org-time-today)
11064 (* (string-to-number (match-string 1 s))
11065 (cdr (assoc (match-string 2 s)
11066 '(("d" . 86400.0) ("w" . 604800.0)
11067 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11068 (t (org-2ft s)))))
11070 (defun org-match-any-p (re list)
11071 "Does re match any element of list?"
11072 (setq list (mapcar (lambda (x) (string-match re x)) list))
11073 (delq nil list))
11075 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11076 (defvar org-tags-overlay (org-make-overlay 1 1))
11077 (org-detach-overlay org-tags-overlay)
11079 (defun org-get-local-tags-at (&optional pos)
11080 "Get a list of tags defined in the current headline."
11081 (org-get-tags-at pos 'local))
11083 (defun org-get-local-tags ()
11084 "Get a list of tags defined in the current headline."
11085 (org-get-tags-at nil 'local))
11087 (defun org-get-tags-at (&optional pos local)
11088 "Get a list of all headline tags applicable at POS.
11089 POS defaults to point. If tags are inherited, the list contains
11090 the targets in the same sequence as the headlines appear, i.e.
11091 the tags of the current headline come last.
11092 When LOCAL is non-nil, only return tags from the current headline,
11093 ignore inherited ones."
11094 (interactive)
11095 (if (and org-trust-scanner-tags
11096 (or (not pos) (equal pos (point)))
11097 (not local))
11098 org-scanner-tags
11099 (let (tags ltags lastpos parent)
11100 (save-excursion
11101 (save-restriction
11102 (widen)
11103 (goto-char (or pos (point)))
11104 (save-match-data
11105 (catch 'done
11106 (condition-case nil
11107 (progn
11108 (org-back-to-heading t)
11109 (while (not (equal lastpos (point)))
11110 (setq lastpos (point))
11111 (when (looking-at
11112 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11113 (setq ltags (org-split-string
11114 (org-match-string-no-properties 1) ":"))
11115 (when parent
11116 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11117 (setq tags (append
11118 (if parent
11119 (org-remove-uniherited-tags ltags)
11120 ltags)
11121 tags)))
11122 (or org-use-tag-inheritance (throw 'done t))
11123 (if local (throw 'done t))
11124 (or (org-up-heading-safe) (error nil))
11125 (setq parent t)))
11126 (error nil)))))
11127 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11129 (defun org-add-prop-inherited (s)
11130 (add-text-properties 0 (length s) '(inherited t) s)
11133 (defun org-toggle-tag (tag &optional onoff)
11134 "Toggle the tag TAG for the current line.
11135 If ONOFF is `on' or `off', don't toggle but set to this state."
11136 (let (res current)
11137 (save-excursion
11138 (org-back-to-heading t)
11139 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11140 (point-at-eol) t)
11141 (progn
11142 (setq current (match-string 1))
11143 (replace-match ""))
11144 (setq current ""))
11145 (setq current (nreverse (org-split-string current ":")))
11146 (cond
11147 ((eq onoff 'on)
11148 (setq res t)
11149 (or (member tag current) (push tag current)))
11150 ((eq onoff 'off)
11151 (or (not (member tag current)) (setq current (delete tag current))))
11152 (t (if (member tag current)
11153 (setq current (delete tag current))
11154 (setq res t)
11155 (push tag current))))
11156 (end-of-line 1)
11157 (if current
11158 (progn
11159 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11160 (org-set-tags nil t))
11161 (delete-horizontal-space))
11162 (run-hooks 'org-after-tags-change-hook))
11163 res))
11165 (defun org-align-tags-here (to-col)
11166 ;; Assumes that this is a headline
11167 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11168 (beginning-of-line 1)
11169 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11170 (< pos (match-beginning 2)))
11171 (progn
11172 (setq tags-l (- (match-end 2) (match-beginning 2)))
11173 (goto-char (match-beginning 1))
11174 (insert " ")
11175 (delete-region (point) (1+ (match-beginning 2)))
11176 (setq ncol (max (1+ (current-column))
11177 (1+ col)
11178 (if (> to-col 0)
11179 to-col
11180 (- (abs to-col) tags-l))))
11181 (setq p (point))
11182 (insert (make-string (- ncol (current-column)) ?\ ))
11183 (setq ncol (current-column))
11184 (when indent-tabs-mode (tabify p (point-at-eol)))
11185 (org-move-to-column (min ncol col) t))
11186 (goto-char pos))))
11188 (defun org-set-tags-command (&optional arg just-align)
11189 "Call the set-tags command for the current entry."
11190 (interactive "P")
11191 (if (org-on-heading-p)
11192 (org-set-tags arg just-align)
11193 (save-excursion
11194 (org-back-to-heading t)
11195 (org-set-tags arg just-align))))
11197 (defun org-set-tags (&optional arg just-align)
11198 "Set the tags for the current headline.
11199 With prefix ARG, realign all tags in headings in the current buffer."
11200 (interactive "P")
11201 (let* ((re (concat "^" outline-regexp))
11202 (current (org-get-tags-string))
11203 (col (current-column))
11204 (org-setting-tags t)
11205 table current-tags inherited-tags ; computed below when needed
11206 tags p0 c0 c1 rpl)
11207 (if arg
11208 (save-excursion
11209 (goto-char (point-min))
11210 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11211 (while (re-search-forward re nil t)
11212 (org-set-tags nil t)
11213 (end-of-line 1)))
11214 (message "All tags realigned to column %d" org-tags-column))
11215 (if just-align
11216 (setq tags current)
11217 ;; Get a new set of tags from the user
11218 (save-excursion
11219 (setq table (append org-tag-persistent-alist
11220 (or org-tag-alist (org-get-buffer-tags)))
11221 org-last-tags-completion-table table
11222 current-tags (org-split-string current ":")
11223 inherited-tags (nreverse
11224 (nthcdr (length current-tags)
11225 (nreverse (org-get-tags-at))))
11226 tags
11227 (if (or (eq t org-use-fast-tag-selection)
11228 (and org-use-fast-tag-selection
11229 (delq nil (mapcar 'cdr table))))
11230 (org-fast-tag-selection
11231 current-tags inherited-tags table
11232 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11233 (let ((org-add-colon-after-tag-completion t))
11234 (org-trim
11235 (org-without-partial-completion
11236 (org-icompleting-read "Tags: " 'org-tags-completion-function
11237 nil nil current 'org-tags-history)))))))
11238 (while (string-match "[-+&]+" tags)
11239 ;; No boolean logic, just a list
11240 (setq tags (replace-match ":" t t tags))))
11242 (if org-tags-sort-function
11243 (setq tags (mapconcat 'identity
11244 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11245 org-tags-sort-function) ":")))
11247 (if (string-match "\\`[\t ]*\\'" tags)
11248 (setq tags "")
11249 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11250 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11252 ;; Insert new tags at the correct column
11253 (beginning-of-line 1)
11254 (cond
11255 ((and (equal current "") (equal tags "")))
11256 ((re-search-forward
11257 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11258 (point-at-eol) t)
11259 (if (equal tags "")
11260 (setq rpl "")
11261 (goto-char (match-beginning 0))
11262 (setq c0 (current-column) p0 (point)
11263 c1 (max (1+ c0) (if (> org-tags-column 0)
11264 org-tags-column
11265 (- (- org-tags-column) (length tags))))
11266 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11267 (replace-match rpl t t)
11268 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11269 tags)
11270 (t (error "Tags alignment failed")))
11271 (org-move-to-column col)
11272 (unless just-align
11273 (run-hooks 'org-after-tags-change-hook)))))
11275 (defun org-change-tag-in-region (beg end tag off)
11276 "Add or remove TAG for each entry in the region.
11277 This works in the agenda, and also in an org-mode buffer."
11278 (interactive
11279 (list (region-beginning) (region-end)
11280 (let ((org-last-tags-completion-table
11281 (if (org-mode-p)
11282 (org-get-buffer-tags)
11283 (org-global-tags-completion-table))))
11284 (org-icompleting-read
11285 "Tag: " 'org-tags-completion-function nil nil nil
11286 'org-tags-history))
11287 (progn
11288 (message "[s]et or [r]emove? ")
11289 (equal (read-char-exclusive) ?r))))
11290 (if (fboundp 'deactivate-mark) (deactivate-mark))
11291 (let ((agendap (equal major-mode 'org-agenda-mode))
11292 l1 l2 m buf pos newhead (cnt 0))
11293 (goto-char end)
11294 (setq l2 (1- (org-current-line)))
11295 (goto-char beg)
11296 (setq l1 (org-current-line))
11297 (loop for l from l1 to l2 do
11298 (org-goto-line l)
11299 (setq m (get-text-property (point) 'org-hd-marker))
11300 (when (or (and (org-mode-p) (org-on-heading-p))
11301 (and agendap m))
11302 (setq buf (if agendap (marker-buffer m) (current-buffer))
11303 pos (if agendap m (point)))
11304 (with-current-buffer buf
11305 (save-excursion
11306 (save-restriction
11307 (goto-char pos)
11308 (setq cnt (1+ cnt))
11309 (org-toggle-tag tag (if off 'off 'on))
11310 (setq newhead (org-get-heading)))))
11311 (and agendap (org-agenda-change-all-lines newhead m))))
11312 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11314 (defun org-tags-completion-function (string predicate &optional flag)
11315 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11316 (confirm (lambda (x) (stringp (car x)))))
11317 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11318 (setq s1 (match-string 1 string)
11319 s2 (match-string 2 string))
11320 (setq s1 "" s2 string))
11321 (cond
11322 ((eq flag nil)
11323 ;; try completion
11324 (setq rtn (try-completion s2 ctable confirm))
11325 (if (stringp rtn)
11326 (setq rtn
11327 (concat s1 s2 (substring rtn (length s2))
11328 (if (and org-add-colon-after-tag-completion
11329 (assoc rtn ctable))
11330 ":" ""))))
11331 rtn)
11332 ((eq flag t)
11333 ;; all-completions
11334 (all-completions s2 ctable confirm)
11336 ((eq flag 'lambda)
11337 ;; exact match?
11338 (assoc s2 ctable)))
11341 (defun org-fast-tag-insert (kwd tags face &optional end)
11342 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11343 (insert (format "%-12s" (concat kwd ":"))
11344 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11345 (or end "")))
11347 (defun org-fast-tag-show-exit (flag)
11348 (save-excursion
11349 (org-goto-line 3)
11350 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11351 (replace-match ""))
11352 (when flag
11353 (end-of-line 1)
11354 (org-move-to-column (- (window-width) 19) t)
11355 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11357 (defun org-set-current-tags-overlay (current prefix)
11358 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11359 (if (featurep 'xemacs)
11360 (org-overlay-display org-tags-overlay (concat prefix s)
11361 'secondary-selection)
11362 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11363 (org-overlay-display org-tags-overlay (concat prefix s)))))
11365 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11366 "Fast tag selection with single keys.
11367 CURRENT is the current list of tags in the headline, INHERITED is the
11368 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11369 possibly with grouping information. TODO-TABLE is a similar table with
11370 TODO keywords, should these have keys assigned to them.
11371 If the keys are nil, a-z are automatically assigned.
11372 Returns the new tags string, or nil to not change the current settings."
11373 (let* ((fulltable (append table todo-table))
11374 (maxlen (apply 'max (mapcar
11375 (lambda (x)
11376 (if (stringp (car x)) (string-width (car x)) 0))
11377 fulltable)))
11378 (buf (current-buffer))
11379 (expert (eq org-fast-tag-selection-single-key 'expert))
11380 (buffer-tags nil)
11381 (fwidth (+ maxlen 3 1 3))
11382 (ncol (/ (- (window-width) 4) fwidth))
11383 (i-face 'org-done)
11384 (c-face 'org-todo)
11385 tg cnt e c char c1 c2 ntable tbl rtn
11386 ov-start ov-end ov-prefix
11387 (exit-after-next org-fast-tag-selection-single-key)
11388 (done-keywords org-done-keywords)
11389 groups ingroup)
11390 (save-excursion
11391 (beginning-of-line 1)
11392 (if (looking-at
11393 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11394 (setq ov-start (match-beginning 1)
11395 ov-end (match-end 1)
11396 ov-prefix "")
11397 (setq ov-start (1- (point-at-eol))
11398 ov-end (1+ ov-start))
11399 (skip-chars-forward "^\n\r")
11400 (setq ov-prefix
11401 (concat
11402 (buffer-substring (1- (point)) (point))
11403 (if (> (current-column) org-tags-column)
11405 (make-string (- org-tags-column (current-column)) ?\ ))))))
11406 (org-move-overlay org-tags-overlay ov-start ov-end)
11407 (save-window-excursion
11408 (if expert
11409 (set-buffer (get-buffer-create " *Org tags*"))
11410 (delete-other-windows)
11411 (split-window-vertically)
11412 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11413 (erase-buffer)
11414 (org-set-local 'org-done-keywords done-keywords)
11415 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11416 (org-fast-tag-insert "Current" current c-face "\n\n")
11417 (org-fast-tag-show-exit exit-after-next)
11418 (org-set-current-tags-overlay current ov-prefix)
11419 (setq tbl fulltable char ?a cnt 0)
11420 (while (setq e (pop tbl))
11421 (cond
11422 ((equal e '(:startgroup))
11423 (push '() groups) (setq ingroup t)
11424 (when (not (= cnt 0))
11425 (setq cnt 0)
11426 (insert "\n"))
11427 (insert "{ "))
11428 ((equal e '(:endgroup))
11429 (setq ingroup nil cnt 0)
11430 (insert "}\n"))
11431 ((equal e '(:newline))
11432 (when (not (= cnt 0))
11433 (setq cnt 0)
11434 (insert "\n")
11435 (setq e (car tbl))
11436 (while (equal (car tbl) '(:newline))
11437 (insert "\n")
11438 (setq tbl (cdr tbl)))))
11440 (setq tg (copy-sequence (car e)) c2 nil)
11441 (if (cdr e)
11442 (setq c (cdr e))
11443 ;; automatically assign a character.
11444 (setq c1 (string-to-char
11445 (downcase (substring
11446 tg (if (= (string-to-char tg) ?@) 1 0)))))
11447 (if (or (rassoc c1 ntable) (rassoc c1 table))
11448 (while (or (rassoc char ntable) (rassoc char table))
11449 (setq char (1+ char)))
11450 (setq c2 c1))
11451 (setq c (or c2 char)))
11452 (if ingroup (push tg (car groups)))
11453 (setq tg (org-add-props tg nil 'face
11454 (cond
11455 ((not (assoc tg table))
11456 (org-get-todo-face tg))
11457 ((member tg current) c-face)
11458 ((member tg inherited) i-face)
11459 (t nil))))
11460 (if (and (= cnt 0) (not ingroup)) (insert " "))
11461 (insert "[" c "] " tg (make-string
11462 (- fwidth 4 (length tg)) ?\ ))
11463 (push (cons tg c) ntable)
11464 (when (= (setq cnt (1+ cnt)) ncol)
11465 (insert "\n")
11466 (if ingroup (insert " "))
11467 (setq cnt 0)))))
11468 (setq ntable (nreverse ntable))
11469 (insert "\n")
11470 (goto-char (point-min))
11471 (if (not expert) (org-fit-window-to-buffer))
11472 (setq rtn
11473 (catch 'exit
11474 (while t
11475 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11476 (if groups " [!] no groups" " [!]groups")
11477 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11478 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11479 (cond
11480 ((= c ?\r) (throw 'exit t))
11481 ((= c ?!)
11482 (setq groups (not groups))
11483 (goto-char (point-min))
11484 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11485 ((= c ?\C-c)
11486 (if (not expert)
11487 (org-fast-tag-show-exit
11488 (setq exit-after-next (not exit-after-next)))
11489 (setq expert nil)
11490 (delete-other-windows)
11491 (split-window-vertically)
11492 (org-switch-to-buffer-other-window " *Org tags*")
11493 (org-fit-window-to-buffer)))
11494 ((or (= c ?\C-g)
11495 (and (= c ?q) (not (rassoc c ntable))))
11496 (org-detach-overlay org-tags-overlay)
11497 (setq quit-flag t))
11498 ((= c ?\ )
11499 (setq current nil)
11500 (if exit-after-next (setq exit-after-next 'now)))
11501 ((= c ?\t)
11502 (condition-case nil
11503 (setq tg (org-icompleting-read
11504 "Tag: "
11505 (or buffer-tags
11506 (with-current-buffer buf
11507 (org-get-buffer-tags)))))
11508 (quit (setq tg "")))
11509 (when (string-match "\\S-" tg)
11510 (add-to-list 'buffer-tags (list tg))
11511 (if (member tg current)
11512 (setq current (delete tg current))
11513 (push tg current)))
11514 (if exit-after-next (setq exit-after-next 'now)))
11515 ((setq e (rassoc c todo-table) tg (car e))
11516 (with-current-buffer buf
11517 (save-excursion (org-todo tg)))
11518 (if exit-after-next (setq exit-after-next 'now)))
11519 ((setq e (rassoc c ntable) tg (car e))
11520 (if (member tg current)
11521 (setq current (delete tg current))
11522 (loop for g in groups do
11523 (if (member tg g)
11524 (mapc (lambda (x)
11525 (setq current (delete x current)))
11526 g)))
11527 (push tg current))
11528 (if exit-after-next (setq exit-after-next 'now))))
11530 ;; Create a sorted list
11531 (setq current
11532 (sort current
11533 (lambda (a b)
11534 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11535 (if (eq exit-after-next 'now) (throw 'exit t))
11536 (goto-char (point-min))
11537 (beginning-of-line 2)
11538 (delete-region (point) (point-at-eol))
11539 (org-fast-tag-insert "Current" current c-face)
11540 (org-set-current-tags-overlay current ov-prefix)
11541 (while (re-search-forward
11542 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11543 (setq tg (match-string 1))
11544 (add-text-properties
11545 (match-beginning 1) (match-end 1)
11546 (list 'face
11547 (cond
11548 ((member tg current) c-face)
11549 ((member tg inherited) i-face)
11550 (t (get-text-property (match-beginning 1) 'face))))))
11551 (goto-char (point-min)))))
11552 (org-detach-overlay org-tags-overlay)
11553 (if rtn
11554 (mapconcat 'identity current ":")
11555 nil))))
11557 (defun org-get-tags-string ()
11558 "Get the TAGS string in the current headline."
11559 (unless (org-on-heading-p t)
11560 (error "Not on a heading"))
11561 (save-excursion
11562 (beginning-of-line 1)
11563 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11564 (org-match-string-no-properties 1)
11565 "")))
11567 (defun org-get-tags ()
11568 "Get the list of tags specified in the current headline."
11569 (org-split-string (org-get-tags-string) ":"))
11571 (defun org-get-buffer-tags ()
11572 "Get a table of all tags used in the buffer, for completion."
11573 (let (tags)
11574 (save-excursion
11575 (goto-char (point-min))
11576 (while (re-search-forward
11577 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11578 (when (equal (char-after (point-at-bol 0)) ?*)
11579 (mapc (lambda (x) (add-to-list 'tags x))
11580 (org-split-string (org-match-string-no-properties 1) ":")))))
11581 (mapcar 'list tags)))
11583 ;;;; The mapping API
11585 ;;;###autoload
11586 (defun org-map-entries (func &optional match scope &rest skip)
11587 "Call FUNC at each headline selected by MATCH in SCOPE.
11589 FUNC is a function or a lisp form. The function will be called without
11590 arguments, with the cursor positioned at the beginning of the headline.
11591 The return values of all calls to the function will be collected and
11592 returned as a list.
11594 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11595 does not need to preserve point. After evaluation, the cursor will be
11596 moved to the end of the line (presumably of the headline of the
11597 processed entry) and search continues from there. Under some
11598 circumstances, this may not produce the wanted results. For example,
11599 if you have removed (e.g. archived) the current (sub)tree it could
11600 mean that the next entry will be skipped entirely. In such cases, you
11601 can specify the position from where search should continue by making
11602 FUNC set the variable `org-map-continue-from' to the desired buffer
11603 position.
11605 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11606 Only headlines that are matched by this query will be considered during
11607 the iteration. When MATCH is nil or t, all headlines will be
11608 visited by the iteration.
11610 SCOPE determines the scope of this command. It can be any of:
11612 nil The current buffer, respecting the restriction if any
11613 tree The subtree started with the entry at point
11614 file The current buffer, without restriction
11615 file-with-archives
11616 The current buffer, and any archives associated with it
11617 agenda All agenda files
11618 agenda-with-archives
11619 All agenda files with any archive files associated with them
11620 \(file1 file2 ...)
11621 If this is a list, all files in the list will be scanned
11623 The remaining args are treated as settings for the skipping facilities of
11624 the scanner. The following items can be given here:
11626 archive skip trees with the archive tag.
11627 comment skip trees with the COMMENT keyword
11628 function or Emacs Lisp form:
11629 will be used as value for `org-agenda-skip-function', so whenever
11630 the the function returns t, FUNC will not be called for that
11631 entry and search will continue from the point where the
11632 function leaves it.
11634 If your function needs to retrieve the tags including inherited tags
11635 at the *current* entry, you can use the value of the variable
11636 `org-scanner-tags' which will be much faster than getting the value
11637 with `org-get-tags-at'. If your function gets properties with
11638 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11639 to t around the call to `org-entry-properties' to get the same speedup.
11640 Note that if your function moves around to retrieve tags and properties at
11641 a *different* entry, you cannot use these techniques."
11642 (let* ((org-agenda-archives-mode nil) ; just to make sure
11643 (org-agenda-skip-archived-trees (memq 'archive skip))
11644 (org-agenda-skip-comment-trees (memq 'comment skip))
11645 (org-agenda-skip-function
11646 (car (org-delete-all '(comment archive) skip)))
11647 (org-tags-match-list-sublevels t)
11648 matcher file res
11649 org-todo-keywords-for-agenda
11650 org-done-keywords-for-agenda
11651 org-todo-keyword-alist-for-agenda
11652 org-tag-alist-for-agenda)
11654 (cond
11655 ((eq match t) (setq matcher t))
11656 ((eq match nil) (setq matcher t))
11657 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11659 (save-excursion
11660 (save-restriction
11661 (when (eq scope 'tree)
11662 (org-back-to-heading t)
11663 (org-narrow-to-subtree)
11664 (setq scope nil))
11666 (if (not scope)
11667 (progn
11668 (org-prepare-agenda-buffers
11669 (list (buffer-file-name (current-buffer))))
11670 (setq res (org-scan-tags func matcher)))
11671 ;; Get the right scope
11672 (cond
11673 ((and scope (listp scope) (symbolp (car scope)))
11674 (setq scope (eval scope)))
11675 ((eq scope 'agenda)
11676 (setq scope (org-agenda-files t)))
11677 ((eq scope 'agenda-with-archives)
11678 (setq scope (org-agenda-files t))
11679 (setq scope (org-add-archive-files scope)))
11680 ((eq scope 'file)
11681 (setq scope (list (buffer-file-name))))
11682 ((eq scope 'file-with-archives)
11683 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11684 (org-prepare-agenda-buffers scope)
11685 (while (setq file (pop scope))
11686 (with-current-buffer (org-find-base-buffer-visiting file)
11687 (save-excursion
11688 (save-restriction
11689 (widen)
11690 (goto-char (point-min))
11691 (setq res (append res (org-scan-tags func matcher))))))))))
11692 res))
11694 ;;;; Properties
11696 ;;; Setting and retrieving properties
11698 (defconst org-special-properties
11699 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11700 "TIMESTAMP" "TIMESTAMP_IA")
11701 "The special properties valid in Org-mode.
11703 These are properties that are not defined in the property drawer,
11704 but in some other way.")
11706 (defconst org-default-properties
11707 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11708 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11709 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11710 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11711 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11712 "CLOCK_MODELINE_TOTAL")
11713 "Some properties that are used by Org-mode for various purposes.
11714 Being in this list makes sure that they are offered for completion.")
11716 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11717 "Regular expression matching the first line of a property drawer.")
11719 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11720 "Regular expression matching the first line of a property drawer.")
11722 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11723 "Regular expression matching the first line of a property drawer.")
11725 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11726 "Regular expression matching the first line of a property drawer.")
11728 (defconst org-property-drawer-re
11729 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11730 org-property-end-re "\\)\n?")
11731 "Matches an entire property drawer.")
11733 (defconst org-clock-drawer-re
11734 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11735 org-property-end-re "\\)\n?")
11736 "Matches an entire clock drawer.")
11738 (defun org-property-action ()
11739 "Do an action on properties."
11740 (interactive)
11741 (let (c)
11742 (org-at-property-p)
11743 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11744 (setq c (read-char-exclusive))
11745 (cond
11746 ((equal c ?s)
11747 (call-interactively 'org-set-property))
11748 ((equal c ?d)
11749 (call-interactively 'org-delete-property))
11750 ((equal c ?D)
11751 (call-interactively 'org-delete-property-globally))
11752 ((equal c ?c)
11753 (call-interactively 'org-compute-property-at-point))
11754 (t (error "No such property action %c" c)))))
11756 (defun org-set-effort (&optional value)
11757 "Set the effort property of the current entry.
11758 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
11759 allowed value."
11760 (interactive "P")
11761 (if (equal value 0) (setq value 10))
11762 (let* ((completion-ignore-case t)
11763 (prop org-effort-property)
11764 (cur (org-entry-get nil prop))
11765 (allowed (org-property-get-allowed-values nil prop 'table))
11766 (existing (mapcar 'list (org-property-values prop)))
11767 (val (cond
11768 ((stringp value) value)
11769 ((and allowed (integerp value))
11770 (or (car (nth (1- value) allowed))
11771 (car (org-last allowed))))
11772 (allowed
11773 (org-completing-read "Value: " allowed nil 'req-match))
11775 (let (org-completion-use-ido org-completion-use-iswitchb)
11776 (org-completing-read
11777 (concat "Value " (if (and cur (string-match "\\S-" cur))
11778 (concat "[" cur "]") "")
11779 ": ")
11780 existing nil nil "" nil cur))))))
11781 (unless (equal (org-entry-get nil prop) val)
11782 (org-entry-put nil prop val))
11783 (message "%s is now %s" prop val)))
11785 (defun org-at-property-p ()
11786 "Is the cursor in a property line?"
11787 ;; FIXME: Does not check if we are actually in the drawer.
11788 ;; FIXME: also returns true on any drawers.....
11789 ;; This is used by C-c C-c for property action.
11790 (save-excursion
11791 (beginning-of-line 1)
11792 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11794 (defun org-get-property-block (&optional beg end force)
11795 "Return the (beg . end) range of the body of the property drawer.
11796 BEG and END can be beginning and end of subtree, if not given
11797 they will be found.
11798 If the drawer does not exist and FORCE is non-nil, create the drawer."
11799 (catch 'exit
11800 (save-excursion
11801 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11802 (end (or end (progn (outline-next-heading) (point)))))
11803 (goto-char beg)
11804 (if (re-search-forward org-property-start-re end t)
11805 (setq beg (1+ (match-end 0)))
11806 (if force
11807 (save-excursion
11808 (org-insert-property-drawer)
11809 (setq end (progn (outline-next-heading) (point))))
11810 (throw 'exit nil))
11811 (goto-char beg)
11812 (if (re-search-forward org-property-start-re end t)
11813 (setq beg (1+ (match-end 0)))))
11814 (if (re-search-forward org-property-end-re end t)
11815 (setq end (match-beginning 0))
11816 (or force (throw 'exit nil))
11817 (goto-char beg)
11818 (setq end beg)
11819 (org-indent-line-function)
11820 (insert ":END:\n"))
11821 (cons beg end)))))
11823 (defun org-entry-properties (&optional pom which)
11824 "Get all properties of the entry at point-or-marker POM.
11825 This includes the TODO keyword, the tags, time strings for deadline,
11826 scheduled, and clocking, and any additional properties defined in the
11827 entry. The return value is an alist, keys may occur multiple times
11828 if the property key was used several times.
11829 POM may also be nil, in which case the current entry is used.
11830 If WHICH is nil or `all', get all properties. If WHICH is
11831 `special' or `standard', only get that subclass."
11832 (setq which (or which 'all))
11833 (org-with-point-at pom
11834 (let ((clockstr (substring org-clock-string 0 -1))
11835 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11836 beg end range props sum-props key value string clocksum)
11837 (save-excursion
11838 (when (condition-case nil
11839 (and (org-mode-p) (org-back-to-heading t))
11840 (error nil))
11841 (setq beg (point))
11842 (setq sum-props (get-text-property (point) 'org-summaries))
11843 (setq clocksum (get-text-property (point) :org-clock-minutes))
11844 (outline-next-heading)
11845 (setq end (point))
11846 (when (memq which '(all special))
11847 ;; Get the special properties, like TODO and tags
11848 (goto-char beg)
11849 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11850 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11851 (when (looking-at org-priority-regexp)
11852 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11853 (when (and (setq value (org-get-tags-string))
11854 (string-match "\\S-" value))
11855 (push (cons "TAGS" value) props))
11856 (when (setq value (org-get-tags-at))
11857 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11858 props))
11859 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11860 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11861 string (if (equal key clockstr)
11862 (org-no-properties
11863 (org-trim
11864 (buffer-substring
11865 (match-beginning 3) (goto-char (point-at-eol)))))
11866 (substring (org-match-string-no-properties 3) 1 -1)))
11867 (unless key
11868 (if (= (char-after (match-beginning 3)) ?\[)
11869 (setq key "TIMESTAMP_IA")
11870 (setq key "TIMESTAMP")))
11871 (when (or (equal key clockstr) (not (assoc key props)))
11872 (push (cons key string) props)))
11876 (when (memq which '(all standard))
11877 ;; Get the standard properties, like :PROP: ...
11878 (setq range (org-get-property-block beg end))
11879 (when range
11880 (goto-char (car range))
11881 (while (re-search-forward
11882 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11883 (cdr range) t)
11884 (setq key (org-match-string-no-properties 1)
11885 value (org-trim (or (org-match-string-no-properties 2) "")))
11886 (unless (member key excluded)
11887 (push (cons key (or value "")) props)))))
11888 (if clocksum
11889 (push (cons "CLOCKSUM"
11890 (org-columns-number-to-string (/ (float clocksum) 60.)
11891 'add_times))
11892 props))
11893 (unless (assoc "CATEGORY" props)
11894 (setq value (or (org-get-category)
11895 (progn (org-refresh-category-properties)
11896 (org-get-category))))
11897 (push (cons "CATEGORY" value) props))
11898 (append sum-props (nreverse props)))))))
11900 (defun org-entry-get (pom property &optional inherit)
11901 "Get value of PROPERTY for entry at point-or-marker POM.
11902 If INHERIT is non-nil and the entry does not have the property,
11903 then also check higher levels of the hierarchy.
11904 If INHERIT is the symbol `selective', use inheritance only if the setting
11905 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11906 If the property is present but empty, the return value is the empty string.
11907 If the property is not present at all, nil is returned."
11908 (org-with-point-at pom
11909 (if (and inherit (if (eq inherit 'selective)
11910 (org-property-inherit-p property)
11912 (org-entry-get-with-inheritance property)
11913 (if (member property org-special-properties)
11914 ;; We need a special property. Use brute force, get all properties.
11915 (cdr (assoc property (org-entry-properties nil 'special)))
11916 (let ((range (org-get-property-block)))
11917 (if (and range
11918 (goto-char (car range))
11919 (re-search-forward
11920 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11921 (cdr range) t))
11922 ;; Found the property, return it.
11923 (if (match-end 1)
11924 (org-match-string-no-properties 1)
11925 "")))))))
11927 (defun org-property-or-variable-value (var &optional inherit)
11928 "Check if there is a property fixing the value of VAR.
11929 If yes, return this value. If not, return the current value of the variable."
11930 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11931 (if (and prop (stringp prop) (string-match "\\S-" prop))
11932 (read prop)
11933 (symbol-value var))))
11935 (defun org-entry-delete (pom property)
11936 "Delete the property PROPERTY from entry at point-or-marker POM."
11937 (org-with-point-at pom
11938 (if (member property org-special-properties)
11939 nil ; cannot delete these properties.
11940 (let ((range (org-get-property-block)))
11941 (if (and range
11942 (goto-char (car range))
11943 (re-search-forward
11944 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11945 (cdr range) t))
11946 (progn
11947 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11949 nil)))))
11951 ;; Multi-values properties are properties that contain multiple values
11952 ;; These values are assumed to be single words, separated by whitespace.
11953 (defun org-entry-add-to-multivalued-property (pom property value)
11954 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11955 (let* ((old (org-entry-get pom property))
11956 (values (and old (org-split-string old "[ \t]"))))
11957 (setq value (org-entry-protect-space value))
11958 (unless (member value values)
11959 (setq values (cons value values))
11960 (org-entry-put pom property
11961 (mapconcat 'identity values " ")))))
11963 (defun org-entry-remove-from-multivalued-property (pom property value)
11964 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11965 (let* ((old (org-entry-get pom property))
11966 (values (and old (org-split-string old "[ \t]"))))
11967 (setq value (org-entry-protect-space value))
11968 (when (member value values)
11969 (setq values (delete value values))
11970 (org-entry-put pom property
11971 (mapconcat 'identity values " ")))))
11973 (defun org-entry-member-in-multivalued-property (pom property value)
11974 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11975 (let* ((old (org-entry-get pom property))
11976 (values (and old (org-split-string old "[ \t]"))))
11977 (setq value (org-entry-protect-space value))
11978 (member value values)))
11980 (defun org-entry-get-multivalued-property (pom property)
11981 "Return a list of values in a multivalued property."
11982 (let* ((value (org-entry-get pom property))
11983 (values (and value (org-split-string value "[ \t]"))))
11984 (mapcar 'org-entry-restore-space values)))
11986 (defun org-entry-put-multivalued-property (pom property &rest values)
11987 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11988 VALUES should be a list of strings. Spaces will be protected."
11989 (org-entry-put pom property
11990 (mapconcat 'org-entry-protect-space values " "))
11991 (let* ((value (org-entry-get pom property))
11992 (values (and value (org-split-string value "[ \t]"))))
11993 (mapcar 'org-entry-restore-space values)))
11995 (defun org-entry-protect-space (s)
11996 "Protect spaces and newline in string S."
11997 (while (string-match " " s)
11998 (setq s (replace-match "%20" t t s)))
11999 (while (string-match "\n" s)
12000 (setq s (replace-match "%0A" t t s)))
12003 (defun org-entry-restore-space (s)
12004 "Restore spaces and newline in string S."
12005 (while (string-match "%20" s)
12006 (setq s (replace-match " " t t s)))
12007 (while (string-match "%0A" s)
12008 (setq s (replace-match "\n" t t s)))
12011 (defvar org-entry-property-inherited-from (make-marker)
12012 "Marker pointing to the entry from where a property was inherited.
12013 Each call to `org-entry-get-with-inheritance' will set this marker to the
12014 location of the entry where the inheritance search matched. If there was
12015 no match, the marker will point nowhere.
12016 Note that also `org-entry-get' calls this function, if the INHERIT flag
12017 is set.")
12019 (defun org-entry-get-with-inheritance (property)
12020 "Get entry property, and search higher levels if not present."
12021 (move-marker org-entry-property-inherited-from nil)
12022 (let (tmp)
12023 (save-excursion
12024 (save-restriction
12025 (widen)
12026 (catch 'ex
12027 (while t
12028 (when (setq tmp (org-entry-get nil property))
12029 (org-back-to-heading t)
12030 (move-marker org-entry-property-inherited-from (point))
12031 (throw 'ex tmp))
12032 (or (org-up-heading-safe) (throw 'ex nil)))))
12033 (or tmp
12034 (cdr (assoc property org-file-properties))
12035 (cdr (assoc property org-global-properties))
12036 (cdr (assoc property org-global-properties-fixed))))))
12038 (defun org-entry-put (pom property value)
12039 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12040 (org-with-point-at pom
12041 (org-back-to-heading t)
12042 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12043 range)
12044 (cond
12045 ((equal property "TODO")
12046 (when (and (stringp value) (string-match "\\S-" value)
12047 (not (member value org-todo-keywords-1)))
12048 (error "\"%s\" is not a valid TODO state" value))
12049 (if (or (not value)
12050 (not (string-match "\\S-" value)))
12051 (setq value 'none))
12052 (org-todo value)
12053 (org-set-tags nil 'align))
12054 ((equal property "PRIORITY")
12055 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12056 (string-to-char value) ?\ ))
12057 (org-set-tags nil 'align))
12058 ((equal property "SCHEDULED")
12059 (if (re-search-forward org-scheduled-time-regexp end t)
12060 (cond
12061 ((eq value 'earlier) (org-timestamp-change -1 'day))
12062 ((eq value 'later) (org-timestamp-change 1 'day))
12063 (t (call-interactively 'org-schedule)))
12064 (call-interactively 'org-schedule)))
12065 ((equal property "DEADLINE")
12066 (if (re-search-forward org-deadline-time-regexp end t)
12067 (cond
12068 ((eq value 'earlier) (org-timestamp-change -1 'day))
12069 ((eq value 'later) (org-timestamp-change 1 'day))
12070 (t (call-interactively 'org-deadline)))
12071 (call-interactively 'org-deadline)))
12072 ((member property org-special-properties)
12073 (error "The %s property can not yet be set with `org-entry-put'"
12074 property))
12075 (t ; a non-special property
12076 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12077 (setq range (org-get-property-block beg end 'force))
12078 (goto-char (car range))
12079 (if (re-search-forward
12080 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12081 (progn
12082 (delete-region (match-beginning 1) (match-end 1))
12083 (goto-char (match-beginning 1)))
12084 (goto-char (cdr range))
12085 (insert "\n")
12086 (backward-char 1)
12087 (org-indent-line-function)
12088 (insert ":" property ":"))
12089 (and value (insert " " value))
12090 (org-indent-line-function)))))))
12092 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12093 "Get all property keys in the current buffer.
12094 With INCLUDE-SPECIALS, also list the special properties that reflect things
12095 like tags and TODO state.
12096 With INCLUDE-DEFAULTS, also include properties that has special meaning
12097 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12098 With INCLUDE-COLUMNS, also include property names given in COLUMN
12099 formats in the current buffer."
12100 (let (rtn range cfmt s p)
12101 (save-excursion
12102 (save-restriction
12103 (widen)
12104 (goto-char (point-min))
12105 (while (re-search-forward org-property-start-re nil t)
12106 (setq range (org-get-property-block))
12107 (goto-char (car range))
12108 (while (re-search-forward
12109 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12110 (cdr range) t)
12111 (add-to-list 'rtn (org-match-string-no-properties 1)))
12112 (outline-next-heading))))
12114 (when include-specials
12115 (setq rtn (append org-special-properties rtn)))
12117 (when include-defaults
12118 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12119 (add-to-list 'rtn org-effort-property))
12121 (when include-columns
12122 (save-excursion
12123 (save-restriction
12124 (widen)
12125 (goto-char (point-min))
12126 (while (re-search-forward
12127 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12128 nil t)
12129 (setq cfmt (match-string 2) s 0)
12130 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12131 cfmt s)
12132 (setq s (match-end 0)
12133 p (match-string 1 cfmt))
12134 (unless (or (equal p "ITEM")
12135 (member p org-special-properties))
12136 (add-to-list 'rtn (match-string 1 cfmt))))))))
12138 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12140 (defun org-property-values (key)
12141 "Return a list of all values of property KEY."
12142 (save-excursion
12143 (save-restriction
12144 (widen)
12145 (goto-char (point-min))
12146 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12147 values)
12148 (while (re-search-forward re nil t)
12149 (add-to-list 'values (org-trim (match-string 1))))
12150 (delete "" values)))))
12152 (defun org-insert-property-drawer ()
12153 "Insert a property drawer into the current entry."
12154 (interactive)
12155 (org-back-to-heading t)
12156 (looking-at outline-regexp)
12157 (let ((indent (if org-adapt-indentation
12158 (- (match-end 0)(match-beginning 0))
12160 (beg (point))
12161 (re (concat "^[ \t]*" org-keyword-time-regexp))
12162 end hiddenp)
12163 (outline-next-heading)
12164 (setq end (point))
12165 (goto-char beg)
12166 (while (re-search-forward re end t))
12167 (setq hiddenp (org-invisible-p))
12168 (end-of-line 1)
12169 (and (equal (char-after) ?\n) (forward-char 1))
12170 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12171 (if (member (match-string 1) '("CLOCK:" ":END:"))
12172 ;; just skip this line
12173 (beginning-of-line 2)
12174 ;; Drawer start, find the end
12175 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12176 (beginning-of-line 1)))
12177 (org-skip-over-state-notes)
12178 (skip-chars-backward " \t\n\r")
12179 (if (eq (char-before) ?*) (forward-char 1))
12180 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12181 (beginning-of-line 0)
12182 (org-indent-to-column indent)
12183 (beginning-of-line 2)
12184 (org-indent-to-column indent)
12185 (beginning-of-line 0)
12186 (if hiddenp
12187 (save-excursion
12188 (org-back-to-heading t)
12189 (hide-entry))
12190 (org-flag-drawer t))))
12192 (defun org-set-property (property value)
12193 "In the current entry, set PROPERTY to VALUE.
12194 When called interactively, this will prompt for a property name, offering
12195 completion on existing and default properties. And then it will prompt
12196 for a value, offering completion either on allowed values (via an inherited
12197 xxx_ALL property) or on existing values in other instances of this property
12198 in the current file."
12199 (interactive
12200 (let* ((completion-ignore-case t)
12201 (keys (org-buffer-property-keys nil t t))
12202 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12203 (prop (if (member prop0 keys)
12204 prop0
12205 (or (cdr (assoc (downcase prop0)
12206 (mapcar (lambda (x) (cons (downcase x) x))
12207 keys)))
12208 prop0)))
12209 (cur (org-entry-get nil prop))
12210 (allowed (org-property-get-allowed-values nil prop 'table))
12211 (existing (mapcar 'list (org-property-values prop)))
12212 (val (if allowed
12213 (org-completing-read "Value: " allowed nil 'req-match)
12214 (let (org-completion-use-ido org-completion-use-iswitchb)
12215 (org-completing-read
12216 (concat "Value " (if (and cur (string-match "\\S-" cur))
12217 (concat "[" cur "]") "")
12218 ": ")
12219 existing nil nil "" nil cur)))))
12220 (list prop (if (equal val "") cur val))))
12221 (unless (equal (org-entry-get nil property) value)
12222 (org-entry-put nil property value)))
12224 (defun org-delete-property (property)
12225 "In the current entry, delete PROPERTY."
12226 (interactive
12227 (let* ((completion-ignore-case t)
12228 (prop (org-icompleting-read
12229 "Property: " (org-entry-properties nil 'standard))))
12230 (list prop)))
12231 (message "Property %s %s" property
12232 (if (org-entry-delete nil property)
12233 "deleted"
12234 "was not present in the entry")))
12236 (defun org-delete-property-globally (property)
12237 "Remove PROPERTY globally, from all entries."
12238 (interactive
12239 (let* ((completion-ignore-case t)
12240 (prop (org-icompleting-read
12241 "Globally remove property: "
12242 (mapcar 'list (org-buffer-property-keys)))))
12243 (list prop)))
12244 (save-excursion
12245 (save-restriction
12246 (widen)
12247 (goto-char (point-min))
12248 (let ((cnt 0))
12249 (while (re-search-forward
12250 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12251 nil t)
12252 (setq cnt (1+ cnt))
12253 (replace-match ""))
12254 (message "Property \"%s\" removed from %d entries" property cnt)))))
12256 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12258 (defun org-compute-property-at-point ()
12259 "Compute the property at point.
12260 This looks for an enclosing column format, extracts the operator and
12261 then applies it to the property in the column format's scope."
12262 (interactive)
12263 (unless (org-at-property-p)
12264 (error "Not at a property"))
12265 (let ((prop (org-match-string-no-properties 2)))
12266 (org-columns-get-format-and-top-level)
12267 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12268 (error "No operator defined for property %s" prop))
12269 (org-columns-compute prop)))
12271 (defun org-property-get-allowed-values (pom property &optional table)
12272 "Get allowed values for the property PROPERTY.
12273 When TABLE is non-nil, return an alist that can directly be used for
12274 completion."
12275 (let (vals)
12276 (cond
12277 ((equal property "TODO")
12278 (setq vals (org-with-point-at pom
12279 (append org-todo-keywords-1 '("")))))
12280 ((equal property "PRIORITY")
12281 (let ((n org-lowest-priority))
12282 (while (>= n org-highest-priority)
12283 (push (char-to-string n) vals)
12284 (setq n (1- n)))))
12285 ((member property org-special-properties))
12287 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12289 (when (and vals (string-match "\\S-" vals))
12290 (setq vals (car (read-from-string (concat "(" vals ")"))))
12291 (setq vals (mapcar (lambda (x)
12292 (cond ((stringp x) x)
12293 ((numberp x) (number-to-string x))
12294 ((symbolp x) (symbol-name x))
12295 (t "???")))
12296 vals)))))
12297 (if table (mapcar 'list vals) vals)))
12299 (defun org-property-previous-allowed-value (&optional previous)
12300 "Switch to the next allowed value for this property."
12301 (interactive)
12302 (org-property-next-allowed-value t))
12304 (defun org-property-next-allowed-value (&optional previous)
12305 "Switch to the next allowed value for this property."
12306 (interactive)
12307 (unless (org-at-property-p)
12308 (error "Not at a property"))
12309 (let* ((key (match-string 2))
12310 (value (match-string 3))
12311 (allowed (or (org-property-get-allowed-values (point) key)
12312 (and (member value '("[ ]" "[-]" "[X]"))
12313 '("[ ]" "[X]"))))
12314 nval)
12315 (unless allowed
12316 (error "Allowed values for this property have not been defined"))
12317 (if previous (setq allowed (reverse allowed)))
12318 (if (member value allowed)
12319 (setq nval (car (cdr (member value allowed)))))
12320 (setq nval (or nval (car allowed)))
12321 (if (equal nval value)
12322 (error "Only one allowed value for this property"))
12323 (org-at-property-p)
12324 (replace-match (concat " :" key ": " nval) t t)
12325 (org-indent-line-function)
12326 (beginning-of-line 1)
12327 (skip-chars-forward " \t")))
12329 (defun org-find-entry-with-id (ident)
12330 "Locate the entry that contains the ID property with exact value IDENT.
12331 IDENT can be a string, a symbol or a number, this function will search for
12332 the string representation of it.
12333 Return the position where this entry starts, or nil if there is no such entry."
12334 (interactive "sID: ")
12335 (let ((id (cond
12336 ((stringp ident) ident)
12337 ((symbol-name ident) (symbol-name ident))
12338 ((numberp ident) (number-to-string ident))
12339 (t (error "IDENT %s must be a string, symbol or number" ident))))
12340 (case-fold-search nil))
12341 (save-excursion
12342 (save-restriction
12343 (widen)
12344 (goto-char (point-min))
12345 (when (re-search-forward
12346 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12347 nil t)
12348 (org-back-to-heading t)
12349 (point))))))
12351 ;;;; Timestamps
12353 (defvar org-last-changed-timestamp nil)
12354 (defvar org-last-inserted-timestamp nil
12355 "The last time stamp inserted with `org-insert-time-stamp'.")
12356 (defvar org-time-was-given) ; dynamically scoped parameter
12357 (defvar org-end-time-was-given) ; dynamically scoped parameter
12358 (defvar org-ts-what) ; dynamically scoped parameter
12360 (defun org-time-stamp (arg &optional inactive)
12361 "Prompt for a date/time and insert a time stamp.
12362 If the user specifies a time like HH:MM, or if this command is called
12363 with a prefix argument, the time stamp will contain date and time.
12364 Otherwise, only the date will be included. All parts of a date not
12365 specified by the user will be filled in from the current date/time.
12366 So if you press just return without typing anything, the time stamp
12367 will represent the current date/time. If there is already a timestamp
12368 at the cursor, it will be modified."
12369 (interactive "P")
12370 (let* ((ts nil)
12371 (default-time
12372 ;; Default time is either today, or, when entering a range,
12373 ;; the range start.
12374 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12375 (save-excursion
12376 (re-search-backward
12377 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12378 (- (point) 20) t)))
12379 (apply 'encode-time (org-parse-time-string (match-string 1)))
12380 (current-time)))
12381 (default-input (and ts (org-get-compact-tod ts)))
12382 org-time-was-given org-end-time-was-given time)
12383 (cond
12384 ((and (org-at-timestamp-p t)
12385 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12386 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12387 (insert "--")
12388 (setq time (let ((this-command this-command))
12389 (org-read-date arg 'totime nil nil
12390 default-time default-input)))
12391 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12392 ((org-at-timestamp-p t)
12393 (setq time (let ((this-command this-command))
12394 (org-read-date arg 'totime nil nil default-time default-input)))
12395 (when (org-at-timestamp-p t) ; just to get the match data
12396 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12397 (replace-match "")
12398 (setq org-last-changed-timestamp
12399 (org-insert-time-stamp
12400 time (or org-time-was-given arg)
12401 inactive nil nil (list org-end-time-was-given))))
12402 (message "Timestamp updated"))
12404 (setq time (let ((this-command this-command))
12405 (org-read-date arg 'totime nil nil default-time default-input)))
12406 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12407 nil nil (list org-end-time-was-given))))))
12409 ;; FIXME: can we use this for something else, like computing time differences?
12410 (defun org-get-compact-tod (s)
12411 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12412 (let* ((t1 (match-string 1 s))
12413 (h1 (string-to-number (match-string 2 s)))
12414 (m1 (string-to-number (match-string 3 s)))
12415 (t2 (and (match-end 4) (match-string 5 s)))
12416 (h2 (and t2 (string-to-number (match-string 6 s))))
12417 (m2 (and t2 (string-to-number (match-string 7 s))))
12418 dh dm)
12419 (if (not t2)
12421 (setq dh (- h2 h1) dm (- m2 m1))
12422 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12423 (concat t1 "+" (number-to-string dh)
12424 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12426 (defun org-time-stamp-inactive (&optional arg)
12427 "Insert an inactive time stamp.
12428 An inactive time stamp is enclosed in square brackets instead of angle
12429 brackets. It is inactive in the sense that it does not trigger agenda entries,
12430 does not link to the calendar and cannot be changed with the S-cursor keys.
12431 So these are more for recording a certain time/date."
12432 (interactive "P")
12433 (org-time-stamp arg 'inactive))
12435 (defvar org-date-ovl (org-make-overlay 1 1))
12436 (org-overlay-put org-date-ovl 'face 'org-warning)
12437 (org-detach-overlay org-date-ovl)
12439 (defvar org-ans1) ; dynamically scoped parameter
12440 (defvar org-ans2) ; dynamically scoped parameter
12442 (defvar org-plain-time-of-day-regexp) ; defined below
12444 (defvar org-overriding-default-time nil) ; dynamically scoped
12445 (defvar org-read-date-overlay nil)
12446 (defvar org-dcst nil) ; dynamically scoped
12447 (defvar org-read-date-history nil)
12448 (defvar org-read-date-final-answer nil)
12450 (defun org-read-date (&optional with-time to-time from-string prompt
12451 default-time default-input)
12452 "Read a date, possibly a time, and make things smooth for the user.
12453 The prompt will suggest to enter an ISO date, but you can also enter anything
12454 which will at least partially be understood by `parse-time-string'.
12455 Unrecognized parts of the date will default to the current day, month, year,
12456 hour and minute. If this command is called to replace a timestamp at point,
12457 of to enter the second timestamp of a range, the default time is taken from the
12458 existing stamp. For example,
12459 3-2-5 --> 2003-02-05
12460 feb 15 --> currentyear-02-15
12461 sep 12 9 --> 2009-09-12
12462 12:45 --> today 12:45
12463 22 sept 0:34 --> currentyear-09-22 0:34
12464 12 --> currentyear-currentmonth-12
12465 Fri --> nearest Friday (today or later)
12466 etc.
12468 Furthermore you can specify a relative date by giving, as the *first* thing
12469 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12470 change in days weeks, months, years.
12471 With a single plus or minus, the date is relative to today. With a double
12472 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12473 +4d --> four days from today
12474 +4 --> same as above
12475 +2w --> two weeks from today
12476 ++5 --> five days from default date
12478 The function understands only English month and weekday abbreviations,
12479 but this can be configured with the variables `parse-time-months' and
12480 `parse-time-weekdays'.
12482 While prompting, a calendar is popped up - you can also select the
12483 date with the mouse (button 1). The calendar shows a period of three
12484 months. To scroll it to other months, use the keys `>' and `<'.
12485 If you don't like the calendar, turn it off with
12486 \(setq org-read-date-popup-calendar nil)
12488 With optional argument TO-TIME, the date will immediately be converted
12489 to an internal time.
12490 With an optional argument WITH-TIME, the prompt will suggest to also
12491 insert a time. Note that when WITH-TIME is not set, you can still
12492 enter a time, and this function will inform the calling routine about
12493 this change. The calling routine may then choose to change the format
12494 used to insert the time stamp into the buffer to include the time.
12495 With optional argument FROM-STRING, read from this string instead from
12496 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12497 the time/date that is used for everything that is not specified by the
12498 user."
12499 (require 'parse-time)
12500 (let* ((org-time-stamp-rounding-minutes
12501 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12502 (org-dcst org-display-custom-times)
12503 (ct (org-current-time))
12504 (def (or org-overriding-default-time default-time ct))
12505 (defdecode (decode-time def))
12506 (dummy (progn
12507 (when (< (nth 2 defdecode) org-extend-today-until)
12508 (setcar (nthcdr 2 defdecode) -1)
12509 (setcar (nthcdr 1 defdecode) 59)
12510 (setq def (apply 'encode-time defdecode)
12511 defdecode (decode-time def)))))
12512 (calendar-frame-setup nil)
12513 (calendar-move-hook nil)
12514 (calendar-view-diary-initially-flag nil)
12515 (view-diary-entries-initially nil)
12516 (calendar-view-holidays-initially-flag nil)
12517 (view-calendar-holidays-initially nil)
12518 (timestr (format-time-string
12519 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12520 (prompt (concat (if prompt (concat prompt " ") "")
12521 (format "Date+time [%s]: " timestr)))
12522 ans (org-ans0 "") org-ans1 org-ans2 final)
12524 (cond
12525 (from-string (setq ans from-string))
12526 (org-read-date-popup-calendar
12527 (save-excursion
12528 (save-window-excursion
12529 (calendar)
12530 (calendar-forward-day (- (time-to-days def)
12531 (calendar-absolute-from-gregorian
12532 (calendar-current-date))))
12533 (org-eval-in-calendar nil t)
12534 (let* ((old-map (current-local-map))
12535 (map (copy-keymap calendar-mode-map))
12536 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12537 (org-defkey map (kbd "RET") 'org-calendar-select)
12538 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12539 'org-calendar-select-mouse)
12540 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12541 'org-calendar-select-mouse)
12542 (org-defkey minibuffer-local-map [(meta shift left)]
12543 (lambda () (interactive)
12544 (org-eval-in-calendar '(calendar-backward-month 1))))
12545 (org-defkey minibuffer-local-map [(meta shift right)]
12546 (lambda () (interactive)
12547 (org-eval-in-calendar '(calendar-forward-month 1))))
12548 (org-defkey minibuffer-local-map [(meta shift up)]
12549 (lambda () (interactive)
12550 (org-eval-in-calendar '(calendar-backward-year 1))))
12551 (org-defkey minibuffer-local-map [(meta shift down)]
12552 (lambda () (interactive)
12553 (org-eval-in-calendar '(calendar-forward-year 1))))
12554 (org-defkey minibuffer-local-map [?\e (shift left)]
12555 (lambda () (interactive)
12556 (org-eval-in-calendar '(calendar-backward-month 1))))
12557 (org-defkey minibuffer-local-map [?\e (shift right)]
12558 (lambda () (interactive)
12559 (org-eval-in-calendar '(calendar-forward-month 1))))
12560 (org-defkey minibuffer-local-map [?\e (shift up)]
12561 (lambda () (interactive)
12562 (org-eval-in-calendar '(calendar-backward-year 1))))
12563 (org-defkey minibuffer-local-map [?\e (shift down)]
12564 (lambda () (interactive)
12565 (org-eval-in-calendar '(calendar-forward-year 1))))
12566 (org-defkey minibuffer-local-map [(shift up)]
12567 (lambda () (interactive)
12568 (org-eval-in-calendar '(calendar-backward-week 1))))
12569 (org-defkey minibuffer-local-map [(shift down)]
12570 (lambda () (interactive)
12571 (org-eval-in-calendar '(calendar-forward-week 1))))
12572 (org-defkey minibuffer-local-map [(shift left)]
12573 (lambda () (interactive)
12574 (org-eval-in-calendar '(calendar-backward-day 1))))
12575 (org-defkey minibuffer-local-map [(shift right)]
12576 (lambda () (interactive)
12577 (org-eval-in-calendar '(calendar-forward-day 1))))
12578 (org-defkey minibuffer-local-map ">"
12579 (lambda () (interactive)
12580 (org-eval-in-calendar '(scroll-calendar-left 1))))
12581 (org-defkey minibuffer-local-map "<"
12582 (lambda () (interactive)
12583 (org-eval-in-calendar '(scroll-calendar-right 1))))
12584 (run-hooks 'org-read-date-minibuffer-setup-hook)
12585 (unwind-protect
12586 (progn
12587 (use-local-map map)
12588 (add-hook 'post-command-hook 'org-read-date-display)
12589 (setq org-ans0 (read-string prompt default-input
12590 'org-read-date-history nil))
12591 ;; org-ans0: from prompt
12592 ;; org-ans1: from mouse click
12593 ;; org-ans2: from calendar motion
12594 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12595 (remove-hook 'post-command-hook 'org-read-date-display)
12596 (use-local-map old-map)
12597 (when org-read-date-overlay
12598 (org-delete-overlay org-read-date-overlay)
12599 (setq org-read-date-overlay nil)))))))
12601 (t ; Naked prompt only
12602 (unwind-protect
12603 (setq ans (read-string prompt default-input
12604 'org-read-date-history timestr))
12605 (when org-read-date-overlay
12606 (org-delete-overlay org-read-date-overlay)
12607 (setq org-read-date-overlay nil)))))
12609 (setq final (org-read-date-analyze ans def defdecode))
12610 (setq org-read-date-final-answer ans)
12612 (if to-time
12613 (apply 'encode-time final)
12614 (if (and (boundp 'org-time-was-given) org-time-was-given)
12615 (format "%04d-%02d-%02d %02d:%02d"
12616 (nth 5 final) (nth 4 final) (nth 3 final)
12617 (nth 2 final) (nth 1 final))
12618 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12620 (defvar def)
12621 (defvar defdecode)
12622 (defvar with-time)
12623 (defun org-read-date-display ()
12624 "Display the current date prompt interpretation in the minibuffer."
12625 (when org-read-date-display-live
12626 (when org-read-date-overlay
12627 (org-delete-overlay org-read-date-overlay))
12628 (let ((p (point)))
12629 (end-of-line 1)
12630 (while (not (equal (buffer-substring
12631 (max (point-min) (- (point) 4)) (point))
12632 " "))
12633 (insert " "))
12634 (goto-char p))
12635 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12636 " " (or org-ans1 org-ans2)))
12637 (org-end-time-was-given nil)
12638 (f (org-read-date-analyze ans def defdecode))
12639 (fmts (if org-dcst
12640 org-time-stamp-custom-formats
12641 org-time-stamp-formats))
12642 (fmt (if (or with-time
12643 (and (boundp 'org-time-was-given) org-time-was-given))
12644 (cdr fmts)
12645 (car fmts)))
12646 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12647 (when (and org-end-time-was-given
12648 (string-match org-plain-time-of-day-regexp txt))
12649 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12650 org-end-time-was-given
12651 (substring txt (match-end 0)))))
12652 (setq org-read-date-overlay
12653 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12654 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12656 (defun org-read-date-analyze (ans def defdecode)
12657 "Analyse the combined answer of the date prompt."
12658 ;; FIXME: cleanup and comment
12659 (let (delta deltan deltaw deltadef year month day
12660 hour minute second wday pm h2 m2 tl wday1
12661 iso-year iso-weekday iso-week iso-year iso-date)
12663 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12664 (setq ans "+0"))
12666 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12667 (setq ans (replace-match "" t t ans)
12668 deltan (car delta)
12669 deltaw (nth 1 delta)
12670 deltadef (nth 2 delta)))
12672 ;; Check if there is an iso week date in there
12673 ;; If yes, sore the info and postpone interpreting it until the rest
12674 ;; of the parsing is done
12675 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12676 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12677 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12678 iso-week (string-to-number (match-string 2 ans)))
12679 (setq ans (replace-match "" t t ans)))
12681 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12682 (when (string-match
12683 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12684 (setq year (if (match-end 2)
12685 (string-to-number (match-string 2 ans))
12686 (string-to-number (format-time-string "%Y")))
12687 month (string-to-number (match-string 3 ans))
12688 day (string-to-number (match-string 4 ans)))
12689 (if (< year 100) (setq year (+ 2000 year)))
12690 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12691 t nil ans)))
12692 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12693 ;; If there is a time with am/pm, and *no* time without it, we convert
12694 ;; so that matching will be successful.
12695 (loop for i from 1 to 2 do ; twice, for end time as well
12696 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12697 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12698 (setq hour (string-to-number (match-string 1 ans))
12699 minute (if (match-end 3)
12700 (string-to-number (match-string 3 ans))
12702 pm (equal ?p
12703 (string-to-char (downcase (match-string 4 ans)))))
12704 (if (and (= hour 12) (not pm))
12705 (setq hour 0)
12706 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12707 (setq ans (replace-match (format "%02d:%02d" hour minute)
12708 t t ans))))
12710 ;; Check if a time range is given as a duration
12711 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12712 (setq hour (string-to-number (match-string 1 ans))
12713 h2 (+ hour (string-to-number (match-string 3 ans)))
12714 minute (string-to-number (match-string 2 ans))
12715 m2 (+ minute (if (match-end 5) (string-to-number
12716 (match-string 5 ans))0)))
12717 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12718 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12719 t t ans)))
12721 ;; Check if there is a time range
12722 (when (boundp 'org-end-time-was-given)
12723 (setq org-time-was-given nil)
12724 (when (and (string-match org-plain-time-of-day-regexp ans)
12725 (match-end 8))
12726 (setq org-end-time-was-given (match-string 8 ans))
12727 (setq ans (concat (substring ans 0 (match-beginning 7))
12728 (substring ans (match-end 7))))))
12730 (setq tl (parse-time-string ans)
12731 day (or (nth 3 tl) (nth 3 defdecode))
12732 month (or (nth 4 tl)
12733 (if (and org-read-date-prefer-future
12734 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12735 (1+ (nth 4 defdecode))
12736 (nth 4 defdecode)))
12737 year (or (nth 5 tl)
12738 (if (and org-read-date-prefer-future
12739 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12740 (1+ (nth 5 defdecode))
12741 (nth 5 defdecode)))
12742 hour (or (nth 2 tl) (nth 2 defdecode))
12743 minute (or (nth 1 tl) (nth 1 defdecode))
12744 second (or (nth 0 tl) 0)
12745 wday (nth 6 tl))
12747 ;; Special date definitions below
12748 (cond
12749 (iso-week
12750 ;; There was an iso week
12751 (setq year (or iso-year year)
12752 day (or iso-weekday wday 1)
12753 wday nil ; to make sure that the trigger below does not match
12754 iso-date (calendar-gregorian-from-absolute
12755 (calendar-absolute-from-iso
12756 (list iso-week day year))))
12757 ; FIXME: Should we also push ISO weeks into the future?
12758 ; (when (and org-read-date-prefer-future
12759 ; (not iso-year)
12760 ; (< (calendar-absolute-from-gregorian iso-date)
12761 ; (time-to-days (current-time))))
12762 ; (setq year (1+ year)
12763 ; iso-date (calendar-gregorian-from-absolute
12764 ; (calendar-absolute-from-iso
12765 ; (list iso-week day year)))))
12766 (setq month (car iso-date)
12767 year (nth 2 iso-date)
12768 day (nth 1 iso-date)))
12769 (deltan
12770 (unless deltadef
12771 (let ((now (decode-time (current-time))))
12772 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12773 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12774 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12775 ((equal deltaw "m") (setq month (+ month deltan)))
12776 ((equal deltaw "y") (setq year (+ year deltan)))))
12777 ((and wday (not (nth 3 tl)))
12778 ;; Weekday was given, but no day, so pick that day in the week
12779 ;; on or after the derived date.
12780 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12781 (unless (equal wday wday1)
12782 (setq day (+ day (% (- wday wday1 -7) 7))))))
12783 (if (and (boundp 'org-time-was-given)
12784 (nth 2 tl))
12785 (setq org-time-was-given t))
12786 (if (< year 100) (setq year (+ 2000 year)))
12787 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12788 (list second minute hour day month year)))
12790 (defvar parse-time-weekdays)
12792 (defun org-read-date-get-relative (s today default)
12793 "Check string S for special relative date string.
12794 TODAY and DEFAULT are internal times, for today and for a default.
12795 Return shift list (N what def-flag)
12796 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12797 N is the number of WHATs to shift.
12798 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12799 the DEFAULT date rather than TODAY."
12800 (when (and
12801 (string-match
12802 (concat
12803 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12804 "\\([0-9]+\\)?"
12805 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12806 "\\([ \t]\\|$\\)") s)
12807 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12808 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12809 (string-to-char (substring (match-string 1 s) -1))
12810 ?+))
12811 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12812 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12813 (what (if (match-end 3) (match-string 3 s) "d"))
12814 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12815 (date (if rel default today))
12816 (wday (nth 6 (decode-time date)))
12817 delta)
12818 (if wday1
12819 (progn
12820 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12821 (if (= dir ?-) (setq delta (- delta 7)))
12822 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12823 (list delta "d" rel))
12824 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12826 (defun org-eval-in-calendar (form &optional keepdate)
12827 "Eval FORM in the calendar window and return to current window.
12828 Also, store the cursor date in variable org-ans2."
12829 (let ((sf (selected-frame))
12830 (sw (selected-window)))
12831 (select-window (get-buffer-window "*Calendar*" t))
12832 (eval form)
12833 (when (and (not keepdate) (calendar-cursor-to-date))
12834 (let* ((date (calendar-cursor-to-date))
12835 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12836 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12837 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12838 (select-window sw)
12839 (org-select-frame-set-input-focus sf)))
12841 (defun org-calendar-select ()
12842 "Return to `org-read-date' with the date currently selected.
12843 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12844 (interactive)
12845 (when (calendar-cursor-to-date)
12846 (let* ((date (calendar-cursor-to-date))
12847 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12848 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12849 (if (active-minibuffer-window) (exit-minibuffer))))
12851 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12852 "Insert a date stamp for the date given by the internal TIME.
12853 WITH-HM means, use the stamp format that includes the time of the day.
12854 INACTIVE means use square brackets instead of angular ones, so that the
12855 stamp will not contribute to the agenda.
12856 PRE and POST are optional strings to be inserted before and after the
12857 stamp.
12858 The command returns the inserted time stamp."
12859 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12860 stamp)
12861 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12862 (insert-before-markers (or pre ""))
12863 (insert-before-markers (setq stamp (format-time-string fmt time)))
12864 (when (listp extra)
12865 (setq extra (car extra))
12866 (if (and (stringp extra)
12867 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12868 (setq extra (format "-%02d:%02d"
12869 (string-to-number (match-string 1 extra))
12870 (string-to-number (match-string 2 extra))))
12871 (setq extra nil)))
12872 (when extra
12873 (backward-char 1)
12874 (insert-before-markers extra)
12875 (forward-char 1))
12876 (insert-before-markers (or post ""))
12877 (setq org-last-inserted-timestamp stamp)))
12879 (defun org-toggle-time-stamp-overlays ()
12880 "Toggle the use of custom time stamp formats."
12881 (interactive)
12882 (setq org-display-custom-times (not org-display-custom-times))
12883 (unless org-display-custom-times
12884 (let ((p (point-min)) (bmp (buffer-modified-p)))
12885 (while (setq p (next-single-property-change p 'display))
12886 (if (and (get-text-property p 'display)
12887 (eq (get-text-property p 'face) 'org-date))
12888 (remove-text-properties
12889 p (setq p (next-single-property-change p 'display))
12890 '(display t))))
12891 (set-buffer-modified-p bmp)))
12892 (if (featurep 'xemacs)
12893 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12894 (org-restart-font-lock)
12895 (setq org-table-may-need-update t)
12896 (if org-display-custom-times
12897 (message "Time stamps are overlayed with custom format")
12898 (message "Time stamp overlays removed")))
12900 (defun org-display-custom-time (beg end)
12901 "Overlay modified time stamp format over timestamp between BEG and END."
12902 (let* ((ts (buffer-substring beg end))
12903 t1 w1 with-hm tf time str w2 (off 0))
12904 (save-match-data
12905 (setq t1 (org-parse-time-string ts t))
12906 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12907 (setq off (- (match-end 0) (match-beginning 0)))))
12908 (setq end (- end off))
12909 (setq w1 (- end beg)
12910 with-hm (and (nth 1 t1) (nth 2 t1))
12911 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12912 time (org-fix-decoded-time t1)
12913 str (org-add-props
12914 (format-time-string
12915 (substring tf 1 -1) (apply 'encode-time time))
12916 nil 'mouse-face 'highlight)
12917 w2 (length str))
12918 (if (not (= w2 w1))
12919 (add-text-properties (1+ beg) (+ 2 beg)
12920 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12921 (if (featurep 'xemacs)
12922 (progn
12923 (put-text-property beg end 'invisible t)
12924 (put-text-property beg end 'end-glyph (make-glyph str)))
12925 (put-text-property beg end 'display str))))
12927 (defun org-translate-time (string)
12928 "Translate all timestamps in STRING to custom format.
12929 But do this only if the variable `org-display-custom-times' is set."
12930 (when org-display-custom-times
12931 (save-match-data
12932 (let* ((start 0)
12933 (re org-ts-regexp-both)
12934 t1 with-hm inactive tf time str beg end)
12935 (while (setq start (string-match re string start))
12936 (setq beg (match-beginning 0)
12937 end (match-end 0)
12938 t1 (save-match-data
12939 (org-parse-time-string (substring string beg end) t))
12940 with-hm (and (nth 1 t1) (nth 2 t1))
12941 inactive (equal (substring string beg (1+ beg)) "[")
12942 tf (funcall (if with-hm 'cdr 'car)
12943 org-time-stamp-custom-formats)
12944 time (org-fix-decoded-time t1)
12945 str (format-time-string
12946 (concat
12947 (if inactive "[" "<") (substring tf 1 -1)
12948 (if inactive "]" ">"))
12949 (apply 'encode-time time))
12950 string (replace-match str t t string)
12951 start (+ start (length str)))))))
12952 string)
12954 (defun org-fix-decoded-time (time)
12955 "Set 0 instead of nil for the first 6 elements of time.
12956 Don't touch the rest."
12957 (let ((n 0))
12958 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12960 (defun org-days-to-time (timestamp-string)
12961 "Difference between TIMESTAMP-STRING and now in days."
12962 (- (time-to-days (org-time-string-to-time timestamp-string))
12963 (time-to-days (current-time))))
12965 (defun org-deadline-close (timestamp-string &optional ndays)
12966 "Is the time in TIMESTAMP-STRING close to the current date?"
12967 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12968 (and (< (org-days-to-time timestamp-string) ndays)
12969 (not (org-entry-is-done-p))))
12971 (defun org-get-wdays (ts)
12972 "Get the deadline lead time appropriate for timestring TS."
12973 (cond
12974 ((<= org-deadline-warning-days 0)
12975 ;; 0 or negative, enforce this value no matter what
12976 (- org-deadline-warning-days))
12977 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12978 ;; lead time is specified.
12979 (floor (* (string-to-number (match-string 1 ts))
12980 (cdr (assoc (match-string 2 ts)
12981 '(("d" . 1) ("w" . 7)
12982 ("m" . 30.4) ("y" . 365.25)))))))
12983 ;; go for the default.
12984 (t org-deadline-warning-days)))
12986 (defun org-calendar-select-mouse (ev)
12987 "Return to `org-read-date' with the date currently selected.
12988 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12989 (interactive "e")
12990 (mouse-set-point ev)
12991 (when (calendar-cursor-to-date)
12992 (let* ((date (calendar-cursor-to-date))
12993 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12994 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12995 (if (active-minibuffer-window) (exit-minibuffer))))
12997 (defun org-check-deadlines (ndays)
12998 "Check if there are any deadlines due or past due.
12999 A deadline is considered due if it happens within `org-deadline-warning-days'
13000 days from today's date. If the deadline appears in an entry marked DONE,
13001 it is not shown. The prefix arg NDAYS can be used to test that many
13002 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13003 (interactive "P")
13004 (let* ((org-warn-days
13005 (cond
13006 ((equal ndays '(4)) 100000)
13007 (ndays (prefix-numeric-value ndays))
13008 (t (abs org-deadline-warning-days))))
13009 (case-fold-search nil)
13010 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13011 (callback
13012 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13014 (message "%d deadlines past-due or due within %d days"
13015 (org-occur regexp nil callback)
13016 org-warn-days)))
13018 (defun org-check-before-date (date)
13019 "Check if there are deadlines or scheduled entries before DATE."
13020 (interactive (list (org-read-date)))
13021 (let ((case-fold-search nil)
13022 (regexp (concat "\\<\\(" org-deadline-string
13023 "\\|" org-scheduled-string
13024 "\\) *<\\([^>]+\\)>"))
13025 (callback
13026 (lambda () (time-less-p
13027 (org-time-string-to-time (match-string 2))
13028 (org-time-string-to-time date)))))
13029 (message "%d entries before %s"
13030 (org-occur regexp nil callback) date)))
13032 (defun org-check-after-date (date)
13033 "Check if there are deadlines or scheduled entries after DATE."
13034 (interactive (list (org-read-date)))
13035 (let ((case-fold-search nil)
13036 (regexp (concat "\\<\\(" org-deadline-string
13037 "\\|" org-scheduled-string
13038 "\\) *<\\([^>]+\\)>"))
13039 (callback
13040 (lambda () (not
13041 (time-less-p
13042 (org-time-string-to-time (match-string 2))
13043 (org-time-string-to-time date))))))
13044 (message "%d entries after %s"
13045 (org-occur regexp nil callback) date)))
13047 (defun org-evaluate-time-range (&optional to-buffer)
13048 "Evaluate a time range by computing the difference between start and end.
13049 Normally the result is just printed in the echo area, but with prefix arg
13050 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13051 If the time range is actually in a table, the result is inserted into the
13052 next column.
13053 For time difference computation, a year is assumed to be exactly 365
13054 days in order to avoid rounding problems."
13055 (interactive "P")
13057 (org-clock-update-time-maybe)
13058 (save-excursion
13059 (unless (org-at-date-range-p t)
13060 (goto-char (point-at-bol))
13061 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13062 (if (not (org-at-date-range-p t))
13063 (error "Not at a time-stamp range, and none found in current line")))
13064 (let* ((ts1 (match-string 1))
13065 (ts2 (match-string 2))
13066 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13067 (match-end (match-end 0))
13068 (time1 (org-time-string-to-time ts1))
13069 (time2 (org-time-string-to-time ts2))
13070 (t1 (org-float-time time1))
13071 (t2 (org-float-time time2))
13072 (diff (abs (- t2 t1)))
13073 (negative (< (- t2 t1) 0))
13074 ;; (ys (floor (* 365 24 60 60)))
13075 (ds (* 24 60 60))
13076 (hs (* 60 60))
13077 (fy "%dy %dd %02d:%02d")
13078 (fy1 "%dy %dd")
13079 (fd "%dd %02d:%02d")
13080 (fd1 "%dd")
13081 (fh "%02d:%02d")
13082 y d h m align)
13083 (if havetime
13084 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13086 d (floor (/ diff ds)) diff (mod diff ds)
13087 h (floor (/ diff hs)) diff (mod diff hs)
13088 m (floor (/ diff 60)))
13089 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13091 d (floor (+ (/ diff ds) 0.5))
13092 h 0 m 0))
13093 (if (not to-buffer)
13094 (message "%s" (org-make-tdiff-string y d h m))
13095 (if (org-at-table-p)
13096 (progn
13097 (goto-char match-end)
13098 (setq align t)
13099 (and (looking-at " *|") (goto-char (match-end 0))))
13100 (goto-char match-end))
13101 (if (looking-at
13102 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13103 (replace-match ""))
13104 (if negative (insert " -"))
13105 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13106 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13107 (insert " " (format fh h m))))
13108 (if align (org-table-align))
13109 (message "Time difference inserted")))))
13111 (defun org-make-tdiff-string (y d h m)
13112 (let ((fmt "")
13113 (l nil))
13114 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13115 l (push y l)))
13116 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13117 l (push d l)))
13118 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13119 l (push h l)))
13120 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13121 l (push m l)))
13122 (apply 'format fmt (nreverse l))))
13124 (defun org-time-string-to-time (s)
13125 (apply 'encode-time (org-parse-time-string s)))
13126 (defun org-time-string-to-seconds (s)
13127 (org-float-time (org-time-string-to-time s)))
13129 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13130 "Convert a time stamp to an absolute day number.
13131 If there is a specifyer for a cyclic time stamp, get the closest date to
13132 DAYNR.
13133 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13134 the variable date is bound by the calendar when this is called."
13135 (cond
13136 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13137 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13138 daynr
13139 (+ daynr 1000)))
13140 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13141 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13142 (time-to-days (current-time))) (match-string 0 s)
13143 prefer show-all))
13144 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13146 (defun org-days-to-iso-week (days)
13147 "Return the iso week number."
13148 (require 'cal-iso)
13149 (car (calendar-iso-from-absolute days)))
13151 (defun org-small-year-to-year (year)
13152 "Convert 2-digit years into 4-digit years.
13153 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13154 The year 2000 cannot be abbreviated. Any year larger than 99
13155 is returned unchanged."
13156 (if (< year 38)
13157 (setq year (+ 2000 year))
13158 (if (< year 100)
13159 (setq year (+ 1900 year))))
13160 year)
13162 (defun org-time-from-absolute (d)
13163 "Return the time corresponding to date D.
13164 D may be an absolute day number, or a calendar-type list (month day year)."
13165 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13166 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13168 (defun org-calendar-holiday ()
13169 "List of holidays, for Diary display in Org-mode."
13170 (require 'holidays)
13171 (let ((hl (funcall
13172 (if (fboundp 'calendar-check-holidays)
13173 'calendar-check-holidays 'check-calendar-holidays) date)))
13174 (if hl (mapconcat 'identity hl "; "))))
13176 (defun org-diary-sexp-entry (sexp entry date)
13177 "Process a SEXP diary ENTRY for DATE."
13178 (require 'diary-lib)
13179 (let ((result (if calendar-debug-sexp
13180 (let ((stack-trace-on-error t))
13181 (eval (car (read-from-string sexp))))
13182 (condition-case nil
13183 (eval (car (read-from-string sexp)))
13184 (error
13185 (beep)
13186 (message "Bad sexp at line %d in %s: %s"
13187 (org-current-line)
13188 (buffer-file-name) sexp)
13189 (sleep-for 2))))))
13190 (cond ((stringp result) result)
13191 ((and (consp result)
13192 (stringp (cdr result))) (cdr result))
13193 (result entry)
13194 (t nil))))
13196 (defun org-diary-to-ical-string (frombuf)
13197 "Get iCalendar entries from diary entries in buffer FROMBUF.
13198 This uses the icalendar.el library."
13199 (let* ((tmpdir (if (featurep 'xemacs)
13200 (temp-directory)
13201 temporary-file-directory))
13202 (tmpfile (make-temp-name
13203 (expand-file-name "orgics" tmpdir)))
13204 buf rtn b e)
13205 (save-excursion
13206 (set-buffer frombuf)
13207 (icalendar-export-region (point-min) (point-max) tmpfile)
13208 (setq buf (find-buffer-visiting tmpfile))
13209 (set-buffer buf)
13210 (goto-char (point-min))
13211 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13212 (setq b (match-beginning 0)))
13213 (goto-char (point-max))
13214 (if (re-search-backward "^END:VEVENT" nil t)
13215 (setq e (match-end 0)))
13216 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13217 (kill-buffer buf)
13218 (delete-file tmpfile)
13219 rtn))
13221 (defun org-closest-date (start current change prefer show-all)
13222 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13223 When PREFER is `past' return a date that is either CURRENT or past.
13224 When PREFER is `future', return a date that is either CURRENT or future.
13225 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13226 ;; Make the proper lists from the dates
13227 (catch 'exit
13228 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13229 dn dw sday cday n1 n2 n0
13230 d m y y1 y2 date1 date2 nmonths nm ny m2)
13232 (setq start (org-date-to-gregorian start)
13233 current (org-date-to-gregorian
13234 (if show-all
13235 current
13236 (time-to-days (current-time))))
13237 sday (calendar-absolute-from-gregorian start)
13238 cday (calendar-absolute-from-gregorian current))
13240 (if (<= cday sday) (throw 'exit sday))
13242 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13243 (setq dn (string-to-number (match-string 1 change))
13244 dw (cdr (assoc (match-string 2 change) a1)))
13245 (error "Invalid change specifyer: %s" change))
13246 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13247 (cond
13248 ((eq dw 'day)
13249 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13250 n2 (+ n1 dn)))
13251 ((eq dw 'year)
13252 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13253 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13254 (setq date1 (list m d y1)
13255 n1 (calendar-absolute-from-gregorian date1)
13256 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13257 n2 (calendar-absolute-from-gregorian date2)))
13258 ((eq dw 'month)
13259 ;; approx number of month between the two dates
13260 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13261 ;; How often does dn fit in there?
13262 (setq d (nth 1 start) m (car start) y (nth 2 start)
13263 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13264 m (+ m nm)
13265 ny (floor (/ m 12))
13266 y (+ y ny)
13267 m (- m (* ny 12)))
13268 (while (> m 12) (setq m (- m 12) y (1+ y)))
13269 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13270 (setq m2 (+ m dn) y2 y)
13271 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13272 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13273 (while (<= n2 cday)
13274 (setq n1 n2 m m2 y y2)
13275 (setq m2 (+ m dn) y2 y)
13276 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13277 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13278 ;; Make sure n1 is the earlier date
13279 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13280 (if show-all
13281 (cond
13282 ((eq prefer 'past) n1)
13283 ((eq prefer 'future) (if (= cday n1) n1 n2))
13284 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13285 (cond
13286 ((eq prefer 'past) n1)
13287 ((eq prefer 'future) (if (= cday n1) n1 n2))
13288 (t (if (= cday n1) n1 n2)))))))
13290 (defun org-date-to-gregorian (date)
13291 "Turn any specification of DATE into a gregorian date for the calendar."
13292 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13293 ((and (listp date) (= (length date) 3)) date)
13294 ((stringp date)
13295 (setq date (org-parse-time-string date))
13296 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13297 ((listp date)
13298 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13300 (defun org-parse-time-string (s &optional nodefault)
13301 "Parse the standard Org-mode time string.
13302 This should be a lot faster than the normal `parse-time-string'.
13303 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13304 hour and minute fields will be nil if not given."
13305 (if (string-match org-ts-regexp0 s)
13306 (list 0
13307 (if (or (match-beginning 8) (not nodefault))
13308 (string-to-number (or (match-string 8 s) "0")))
13309 (if (or (match-beginning 7) (not nodefault))
13310 (string-to-number (or (match-string 7 s) "0")))
13311 (string-to-number (match-string 4 s))
13312 (string-to-number (match-string 3 s))
13313 (string-to-number (match-string 2 s))
13314 nil nil nil)
13315 (error "Not a standard Org-mode time string: %s" s)))
13317 (defun org-timestamp-up (&optional arg)
13318 "Increase the date item at the cursor by one.
13319 If the cursor is on the year, change the year. If it is on the month or
13320 the day, change that.
13321 With prefix ARG, change by that many units."
13322 (interactive "p")
13323 (org-timestamp-change (prefix-numeric-value arg)))
13325 (defun org-timestamp-down (&optional arg)
13326 "Decrease the date item at the cursor by one.
13327 If the cursor is on the year, change the year. If it is on the month or
13328 the day, change that.
13329 With prefix ARG, change by that many units."
13330 (interactive "p")
13331 (org-timestamp-change (- (prefix-numeric-value arg))))
13333 (defun org-timestamp-up-day (&optional arg)
13334 "Increase the date in the time stamp by one day.
13335 With prefix ARG, change that many days."
13336 (interactive "p")
13337 (if (and (not (org-at-timestamp-p t))
13338 (org-on-heading-p))
13339 (org-todo 'up)
13340 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13342 (defun org-timestamp-down-day (&optional arg)
13343 "Decrease the date in the time stamp by one day.
13344 With prefix ARG, change that many days."
13345 (interactive "p")
13346 (if (and (not (org-at-timestamp-p t))
13347 (org-on-heading-p))
13348 (org-todo 'down)
13349 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13351 (defun org-at-timestamp-p (&optional inactive-ok)
13352 "Determine if the cursor is in or at a timestamp."
13353 (interactive)
13354 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13355 (pos (point))
13356 (ans (or (looking-at tsr)
13357 (save-excursion
13358 (skip-chars-backward "^[<\n\r\t")
13359 (if (> (point) (point-min)) (backward-char 1))
13360 (and (looking-at tsr)
13361 (> (- (match-end 0) pos) -1))))))
13362 (and ans
13363 (boundp 'org-ts-what)
13364 (setq org-ts-what
13365 (cond
13366 ((= pos (match-beginning 0)) 'bracket)
13367 ((= pos (1- (match-end 0))) 'bracket)
13368 ((org-pos-in-match-range pos 2) 'year)
13369 ((org-pos-in-match-range pos 3) 'month)
13370 ((org-pos-in-match-range pos 7) 'hour)
13371 ((org-pos-in-match-range pos 8) 'minute)
13372 ((or (org-pos-in-match-range pos 4)
13373 (org-pos-in-match-range pos 5)) 'day)
13374 ((and (> pos (or (match-end 8) (match-end 5)))
13375 (< pos (match-end 0)))
13376 (- pos (or (match-end 8) (match-end 5))))
13377 (t 'day))))
13378 ans))
13380 (defun org-toggle-timestamp-type ()
13381 "Toggle the type (<active> or [inactive]) of a time stamp."
13382 (interactive)
13383 (when (org-at-timestamp-p t)
13384 (let ((beg (match-beginning 0)) (end (match-end 0))
13385 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13386 (save-excursion
13387 (goto-char beg)
13388 (while (re-search-forward "[][<>]" end t)
13389 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13390 t t)))
13391 (message "Timestamp is now %sactive"
13392 (if (equal (char-after beg) ?<) "" "in")))))
13394 (defun org-timestamp-change (n &optional what)
13395 "Change the date in the time stamp at point.
13396 The date will be changed by N times WHAT. WHAT can be `day', `month',
13397 `year', `minute', `second'. If WHAT is not given, the cursor position
13398 in the timestamp determines what will be changed."
13399 (let ((pos (point))
13400 with-hm inactive
13401 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13402 org-ts-what
13403 extra rem
13404 ts time time0)
13405 (if (not (org-at-timestamp-p t))
13406 (error "Not at a timestamp"))
13407 (if (and (not what) (eq org-ts-what 'bracket))
13408 (org-toggle-timestamp-type)
13409 (if (and (not what) (not (eq org-ts-what 'day))
13410 org-display-custom-times
13411 (get-text-property (point) 'display)
13412 (not (get-text-property (1- (point)) 'display)))
13413 (setq org-ts-what 'day))
13414 (setq org-ts-what (or what org-ts-what)
13415 inactive (= (char-after (match-beginning 0)) ?\[)
13416 ts (match-string 0))
13417 (replace-match "")
13418 (if (string-match
13419 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13421 (setq extra (match-string 1 ts)))
13422 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13423 (setq with-hm t))
13424 (setq time0 (org-parse-time-string ts))
13425 (when (and (eq org-ts-what 'minute)
13426 (eq current-prefix-arg nil))
13427 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13428 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13429 (setcar (cdr time0) (+ (nth 1 time0)
13430 (if (> n 0) (- rem) (- dm rem))))))
13431 (setq time
13432 (encode-time (or (car time0) 0)
13433 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13434 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13435 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13436 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13437 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13438 (nthcdr 6 time0)))
13439 (when (and (member org-ts-what '(hour minute))
13440 extra
13441 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13442 (setq extra (org-modify-ts-extra
13443 extra
13444 (if (eq org-ts-what 'hour) 2 5)
13445 n dm)))
13446 (when (integerp org-ts-what)
13447 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13448 (if (eq what 'calendar)
13449 (let ((cal-date (org-get-date-from-calendar)))
13450 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13451 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13452 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13453 (setcar time0 (or (car time0) 0))
13454 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13455 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13456 (setq time (apply 'encode-time time0))))
13457 (setq org-last-changed-timestamp
13458 (org-insert-time-stamp time with-hm inactive nil nil extra))
13459 (org-clock-update-time-maybe)
13460 (goto-char pos)
13461 ;; Try to recenter the calendar window, if any
13462 (if (and org-calendar-follow-timestamp-change
13463 (get-buffer-window "*Calendar*" t)
13464 (memq org-ts-what '(day month year)))
13465 (org-recenter-calendar (time-to-days time))))))
13467 (defun org-modify-ts-extra (s pos n dm)
13468 "Change the different parts of the lead-time and repeat fields in timestamp."
13469 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13470 ng h m new rem)
13471 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13472 (cond
13473 ((or (org-pos-in-match-range pos 2)
13474 (org-pos-in-match-range pos 3))
13475 (setq m (string-to-number (match-string 3 s))
13476 h (string-to-number (match-string 2 s)))
13477 (if (org-pos-in-match-range pos 2)
13478 (setq h (+ h n))
13479 (setq n (* dm (org-no-warnings (signum n))))
13480 (when (not (= 0 (setq rem (% m dm))))
13481 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13482 (setq m (+ m n)))
13483 (if (< m 0) (setq m (+ m 60) h (1- h)))
13484 (if (> m 59) (setq m (- m 60) h (1+ h)))
13485 (setq h (min 24 (max 0 h)))
13486 (setq ng 1 new (format "-%02d:%02d" h m)))
13487 ((org-pos-in-match-range pos 6)
13488 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13489 ((org-pos-in-match-range pos 5)
13490 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13492 ((org-pos-in-match-range pos 9)
13493 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13494 ((org-pos-in-match-range pos 8)
13495 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13497 (when ng
13498 (setq s (concat
13499 (substring s 0 (match-beginning ng))
13501 (substring s (match-end ng))))))
13504 (defun org-recenter-calendar (date)
13505 "If the calendar is visible, recenter it to DATE."
13506 (let* ((win (selected-window))
13507 (cwin (get-buffer-window "*Calendar*" t))
13508 (calendar-move-hook nil))
13509 (when cwin
13510 (select-window cwin)
13511 (calendar-goto-date (if (listp date) date
13512 (calendar-gregorian-from-absolute date)))
13513 (select-window win))))
13515 (defun org-goto-calendar (&optional arg)
13516 "Go to the Emacs calendar at the current date.
13517 If there is a time stamp in the current line, go to that date.
13518 A prefix ARG can be used to force the current date."
13519 (interactive "P")
13520 (let ((tsr org-ts-regexp) diff
13521 (calendar-move-hook nil)
13522 (calendar-view-holidays-initially-flag nil)
13523 (view-calendar-holidays-initially nil)
13524 (calendar-view-diary-initially-flag nil)
13525 (view-diary-entries-initially nil))
13526 (if (or (org-at-timestamp-p)
13527 (save-excursion
13528 (beginning-of-line 1)
13529 (looking-at (concat ".*" tsr))))
13530 (let ((d1 (time-to-days (current-time)))
13531 (d2 (time-to-days
13532 (org-time-string-to-time (match-string 1)))))
13533 (setq diff (- d2 d1))))
13534 (calendar)
13535 (calendar-goto-today)
13536 (if (and diff (not arg)) (calendar-forward-day diff))))
13538 (defun org-get-date-from-calendar ()
13539 "Return a list (month day year) of date at point in calendar."
13540 (with-current-buffer "*Calendar*"
13541 (save-match-data
13542 (calendar-cursor-to-date))))
13544 (defun org-date-from-calendar ()
13545 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13546 If there is already a time stamp at the cursor position, update it."
13547 (interactive)
13548 (if (org-at-timestamp-p t)
13549 (org-timestamp-change 0 'calendar)
13550 (let ((cal-date (org-get-date-from-calendar)))
13551 (org-insert-time-stamp
13552 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13554 (defun org-minutes-to-hh:mm-string (m)
13555 "Compute H:MM from a number of minutes."
13556 (let ((h (/ m 60)))
13557 (setq m (- m (* 60 h)))
13558 (format org-time-clocksum-format h m)))
13560 (defun org-hh:mm-string-to-minutes (s)
13561 "Convert a string H:MM to a number of minutes.
13562 If the string is just a number, interprete it as minutes.
13563 In fact, the first hh:mm or number in the string will be taken,
13564 there can be extra stuff in the string.
13565 If no number is found, the return value is 0."
13566 (cond
13567 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13568 (+ (* (string-to-number (match-string 1 s)) 60)
13569 (string-to-number (match-string 2 s))))
13570 ((string-match "\\([0-9]+\\)" s)
13571 (string-to-number (match-string 1 s)))
13572 (t 0)))
13574 ;;;; Files
13576 (defun org-save-all-org-buffers ()
13577 "Save all Org-mode buffers without user confirmation."
13578 (interactive)
13579 (message "Saving all Org-mode buffers...")
13580 (save-some-buffers t 'org-mode-p)
13581 (when (featurep 'org-id) (org-id-locations-save))
13582 (message "Saving all Org-mode buffers... done"))
13584 (defun org-revert-all-org-buffers ()
13585 "Revert all Org-mode buffers.
13586 Prompt for confirmation when there are unsaved changes.
13587 Be sure you know what you are doing before letting this function
13588 overwrite your changes.
13590 This function is useful in a setup where one tracks org files
13591 with a version control system, to revert on one machine after pulling
13592 changes from another. I believe the procedure must be like this:
13594 1. M-x org-save-all-org-buffers
13595 2. Pull changes from the other machine, resolve conflicts
13596 3. M-x org-revert-all-org-buffers"
13597 (interactive)
13598 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13599 (error "Abort"))
13600 (save-excursion
13601 (save-window-excursion
13602 (mapc
13603 (lambda (b)
13604 (when (and (with-current-buffer b (org-mode-p))
13605 (with-current-buffer b buffer-file-name))
13606 (switch-to-buffer b)
13607 (revert-buffer t 'no-confirm)))
13608 (buffer-list))
13609 (when (and (featurep 'org-id) org-id-track-globally)
13610 (org-id-locations-load)))))
13612 ;;;; Agenda files
13614 ;;;###autoload
13615 (defun org-iswitchb (&optional arg)
13616 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13617 With a prefix argument, restrict available to files.
13618 With two prefix arguments, restrict available buffers to agenda files."
13619 (interactive "P")
13620 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13621 ((equal arg '(16)) (org-buffer-list 'agenda))
13622 (t (org-buffer-list)))))
13623 (switch-to-buffer
13624 (org-icompleting-read "Org buffer: "
13625 (mapcar 'list (mapcar 'buffer-name blist))
13626 nil t))))
13628 ;;;###autoload
13629 (defalias 'org-ido-switchb 'org-iswitchb)
13631 (defun org-buffer-list (&optional predicate exclude-tmp)
13632 "Return a list of Org buffers.
13633 PREDICATE can be `export', `files' or `agenda'.
13635 export restrict the list to Export buffers.
13636 files restrict the list to buffers visiting Org files.
13637 agenda restrict the list to buffers visiting agenda files.
13639 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13640 (let* ((bfn nil)
13641 (agenda-files (and (eq predicate 'agenda)
13642 (mapcar 'file-truename (org-agenda-files t))))
13643 (filter
13644 (cond
13645 ((eq predicate 'files)
13646 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13647 ((eq predicate 'export)
13648 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13649 ((eq predicate 'agenda)
13650 (lambda (b)
13651 (with-current-buffer b
13652 (and (eq major-mode 'org-mode)
13653 (setq bfn (buffer-file-name b))
13654 (member (file-truename bfn) agenda-files)))))
13655 (t (lambda (b) (with-current-buffer b
13656 (or (eq major-mode 'org-mode)
13657 (string-match "\*Org .*Export"
13658 (buffer-name b)))))))))
13659 (delq nil
13660 (mapcar
13661 (lambda(b)
13662 (if (and (funcall filter b)
13663 (or (not exclude-tmp)
13664 (not (string-match "tmp" (buffer-name b)))))
13666 nil))
13667 (buffer-list)))))
13669 (defun org-agenda-files (&optional unrestricted archives)
13670 "Get the list of agenda files.
13671 Optional UNRESTRICTED means return the full list even if a restriction
13672 is currently in place.
13673 When ARCHIVES is t, include all archive files hat are really being
13674 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13675 `org-agenda-archives-mode' is t."
13676 (let ((files
13677 (cond
13678 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13679 ((stringp org-agenda-files) (org-read-agenda-file-list))
13680 ((listp org-agenda-files) org-agenda-files)
13681 (t (error "Invalid value of `org-agenda-files'")))))
13682 (setq files (apply 'append
13683 (mapcar (lambda (f)
13684 (if (file-directory-p f)
13685 (directory-files
13686 f t org-agenda-file-regexp)
13687 (list f)))
13688 files)))
13689 (when org-agenda-skip-unavailable-files
13690 (setq files (delq nil
13691 (mapcar (function
13692 (lambda (file)
13693 (and (file-readable-p file) file)))
13694 files))))
13695 (when (or (eq archives t)
13696 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13697 (setq files (org-add-archive-files files)))
13698 files))
13700 (defun org-edit-agenda-file-list ()
13701 "Edit the list of agenda files.
13702 Depending on setup, this either uses customize to edit the variable
13703 `org-agenda-files', or it visits the file that is holding the list. In the
13704 latter case, the buffer is set up in a way that saving it automatically kills
13705 the buffer and restores the previous window configuration."
13706 (interactive)
13707 (if (stringp org-agenda-files)
13708 (let ((cw (current-window-configuration)))
13709 (find-file org-agenda-files)
13710 (org-set-local 'org-window-configuration cw)
13711 (org-add-hook 'after-save-hook
13712 (lambda ()
13713 (set-window-configuration
13714 (prog1 org-window-configuration
13715 (kill-buffer (current-buffer))))
13716 (org-install-agenda-files-menu)
13717 (message "New agenda file list installed"))
13718 nil 'local)
13719 (message "%s" (substitute-command-keys
13720 "Edit list and finish with \\[save-buffer]")))
13721 (customize-variable 'org-agenda-files)))
13723 (defun org-store-new-agenda-file-list (list)
13724 "Set new value for the agenda file list and save it correctly."
13725 (if (stringp org-agenda-files)
13726 (let ((f org-agenda-files) b)
13727 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13728 (with-temp-file f
13729 (insert (mapconcat 'identity list "\n") "\n")))
13730 (let ((org-mode-hook nil) (org-inhibit-startup t)
13731 (org-insert-mode-line-in-empty-file nil))
13732 (setq org-agenda-files list)
13733 (customize-save-variable 'org-agenda-files org-agenda-files))))
13735 (defun org-read-agenda-file-list ()
13736 "Read the list of agenda files from a file."
13737 (when (file-directory-p org-agenda-files)
13738 (error "`org-agenda-files' cannot be a single directory"))
13739 (when (stringp org-agenda-files)
13740 (with-temp-buffer
13741 (insert-file-contents org-agenda-files)
13742 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13745 ;;;###autoload
13746 (defun org-cycle-agenda-files ()
13747 "Cycle through the files in `org-agenda-files'.
13748 If the current buffer visits an agenda file, find the next one in the list.
13749 If the current buffer does not, find the first agenda file."
13750 (interactive)
13751 (let* ((fs (org-agenda-files t))
13752 (files (append fs (list (car fs))))
13753 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13754 file)
13755 (unless files (error "No agenda files"))
13756 (catch 'exit
13757 (while (setq file (pop files))
13758 (if (equal (file-truename file) tcf)
13759 (when (car files)
13760 (find-file (car files))
13761 (throw 'exit t))))
13762 (find-file (car fs)))
13763 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13765 (defun org-agenda-file-to-front (&optional to-end)
13766 "Move/add the current file to the top of the agenda file list.
13767 If the file is not present in the list, it is added to the front. If it is
13768 present, it is moved there. With optional argument TO-END, add/move to the
13769 end of the list."
13770 (interactive "P")
13771 (let ((org-agenda-skip-unavailable-files nil)
13772 (file-alist (mapcar (lambda (x)
13773 (cons (file-truename x) x))
13774 (org-agenda-files t)))
13775 (ctf (file-truename buffer-file-name))
13776 x had)
13777 (setq x (assoc ctf file-alist) had x)
13779 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13780 (if to-end
13781 (setq file-alist (append (delq x file-alist) (list x)))
13782 (setq file-alist (cons x (delq x file-alist))))
13783 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13784 (org-install-agenda-files-menu)
13785 (message "File %s to %s of agenda file list"
13786 (if had "moved" "added") (if to-end "end" "front"))))
13788 (defun org-remove-file (&optional file)
13789 "Remove current file from the list of files in variable `org-agenda-files'.
13790 These are the files which are being checked for agenda entries.
13791 Optional argument FILE means, use this file instead of the current."
13792 (interactive)
13793 (let* ((org-agenda-skip-unavailable-files nil)
13794 (file (or file buffer-file-name))
13795 (true-file (file-truename file))
13796 (afile (abbreviate-file-name file))
13797 (files (delq nil (mapcar
13798 (lambda (x)
13799 (if (equal true-file
13800 (file-truename x))
13801 nil x))
13802 (org-agenda-files t)))))
13803 (if (not (= (length files) (length (org-agenda-files t))))
13804 (progn
13805 (org-store-new-agenda-file-list files)
13806 (org-install-agenda-files-menu)
13807 (message "Removed file: %s" afile))
13808 (message "File was not in list: %s (not removed)" afile))))
13810 (defun org-file-menu-entry (file)
13811 (vector file (list 'find-file file) t))
13813 (defun org-check-agenda-file (file)
13814 "Make sure FILE exists. If not, ask user what to do."
13815 (when (not (file-exists-p file))
13816 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
13817 (abbreviate-file-name file))
13818 (let ((r (downcase (read-char-exclusive))))
13819 (cond
13820 ((equal r ?r)
13821 (org-remove-file file)
13822 (throw 'nextfile t))
13823 (t (error "Abort"))))))
13825 (defun org-get-agenda-file-buffer (file)
13826 "Get a buffer visiting FILE. If the buffer needs to be created, add
13827 it to the list of buffers which might be released later."
13828 (let ((buf (org-find-base-buffer-visiting file)))
13829 (if buf
13830 buf ; just return it
13831 ;; Make a new buffer and remember it
13832 (setq buf (find-file-noselect file))
13833 (if buf (push buf org-agenda-new-buffers))
13834 buf)))
13836 (defun org-release-buffers (blist)
13837 "Release all buffers in list, asking the user for confirmation when needed.
13838 When a buffer is unmodified, it is just killed. When modified, it is saved
13839 \(if the user agrees) and then killed."
13840 (let (buf file)
13841 (while (setq buf (pop blist))
13842 (setq file (buffer-file-name buf))
13843 (when (and (buffer-modified-p buf)
13844 file
13845 (y-or-n-p (format "Save file %s? " file)))
13846 (with-current-buffer buf (save-buffer)))
13847 (kill-buffer buf))))
13849 (defun org-prepare-agenda-buffers (files)
13850 "Create buffers for all agenda files, protect archived trees and comments."
13851 (interactive)
13852 (let ((pa '(:org-archived t))
13853 (pc '(:org-comment t))
13854 (pall '(:org-archived t :org-comment t))
13855 (inhibit-read-only t)
13856 (rea (concat ":" org-archive-tag ":"))
13857 bmp file re)
13858 (save-excursion
13859 (save-restriction
13860 (while (setq file (pop files))
13861 (catch 'nextfile
13862 (if (bufferp file)
13863 (set-buffer file)
13864 (org-check-agenda-file file)
13865 (set-buffer (org-get-agenda-file-buffer file)))
13866 (widen)
13867 (setq bmp (buffer-modified-p))
13868 (org-refresh-category-properties)
13869 (setq org-todo-keywords-for-agenda
13870 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13871 (setq org-done-keywords-for-agenda
13872 (append org-done-keywords-for-agenda org-done-keywords))
13873 (setq org-todo-keyword-alist-for-agenda
13874 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13875 (setq org-tag-alist-for-agenda
13876 (append org-tag-alist-for-agenda org-tag-alist))
13878 (save-excursion
13879 (remove-text-properties (point-min) (point-max) pall)
13880 (when org-agenda-skip-archived-trees
13881 (goto-char (point-min))
13882 (while (re-search-forward rea nil t)
13883 (if (org-on-heading-p t)
13884 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13885 (goto-char (point-min))
13886 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13887 (while (re-search-forward re nil t)
13888 (add-text-properties
13889 (match-beginning 0) (org-end-of-subtree t) pc)))
13890 (set-buffer-modified-p bmp)))))
13891 (setq org-todo-keyword-alist-for-agenda
13892 (org-uniquify org-todo-keyword-alist-for-agenda)
13893 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13895 ;;;; Embedded LaTeX
13897 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13898 "Keymap for the minor `org-cdlatex-mode'.")
13900 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13901 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13902 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13903 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13904 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13906 (defvar org-cdlatex-texmathp-advice-is-done nil
13907 "Flag remembering if we have applied the advice to texmathp already.")
13909 (define-minor-mode org-cdlatex-mode
13910 "Toggle the minor `org-cdlatex-mode'.
13911 This mode supports entering LaTeX environment and math in LaTeX fragments
13912 in Org-mode.
13913 \\{org-cdlatex-mode-map}"
13914 nil " OCDL" nil
13915 (when org-cdlatex-mode (require 'cdlatex))
13916 (unless org-cdlatex-texmathp-advice-is-done
13917 (setq org-cdlatex-texmathp-advice-is-done t)
13918 (defadvice texmathp (around org-math-always-on activate)
13919 "Always return t in org-mode buffers.
13920 This is because we want to insert math symbols without dollars even outside
13921 the LaTeX math segments. If Orgmode thinks that point is actually inside
13922 an embedded LaTeX fragment, let texmathp do its job.
13923 \\[org-cdlatex-mode-map]"
13924 (interactive)
13925 (let (p)
13926 (cond
13927 ((not (org-mode-p)) ad-do-it)
13928 ((eq this-command 'cdlatex-math-symbol)
13929 (setq ad-return-value t
13930 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13932 (let ((p (org-inside-LaTeX-fragment-p)))
13933 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13934 (setq ad-return-value t
13935 texmathp-why '("Org-mode embedded math" . 0))
13936 (if p ad-do-it)))))))))
13938 (defun turn-on-org-cdlatex ()
13939 "Unconditionally turn on `org-cdlatex-mode'."
13940 (org-cdlatex-mode 1))
13942 (defun org-inside-LaTeX-fragment-p ()
13943 "Test if point is inside a LaTeX fragment.
13944 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13945 sequence appearing also before point.
13946 Even though the matchers for math are configurable, this function assumes
13947 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13948 delimiters are skipped when they have been removed by customization.
13949 The return value is nil, or a cons cell with the delimiter and
13950 and the position of this delimiter.
13952 This function does a reasonably good job, but can locally be fooled by
13953 for example currency specifications. For example it will assume being in
13954 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13955 fragments that are properly closed, but during editing, we have to live
13956 with the uncertainty caused by missing closing delimiters. This function
13957 looks only before point, not after."
13958 (catch 'exit
13959 (let ((pos (point))
13960 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13961 (lim (progn
13962 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13963 (point)))
13964 dd-on str (start 0) m re)
13965 (goto-char pos)
13966 (when dodollar
13967 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13968 re (nth 1 (assoc "$" org-latex-regexps)))
13969 (while (string-match re str start)
13970 (cond
13971 ((= (match-end 0) (length str))
13972 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13973 ((= (match-end 0) (- (length str) 5))
13974 (throw 'exit nil))
13975 (t (setq start (match-end 0))))))
13976 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13977 (goto-char pos)
13978 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13979 (and (match-beginning 2) (throw 'exit nil))
13980 ;; count $$
13981 (while (re-search-backward "\\$\\$" lim t)
13982 (setq dd-on (not dd-on)))
13983 (goto-char pos)
13984 (if dd-on (cons "$$" m))))))
13987 (defun org-try-cdlatex-tab ()
13988 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13989 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13990 - inside a LaTeX fragment, or
13991 - after the first word in a line, where an abbreviation expansion could
13992 insert a LaTeX environment."
13993 (when org-cdlatex-mode
13994 (cond
13995 ((save-excursion
13996 (skip-chars-backward "a-zA-Z0-9*")
13997 (skip-chars-backward " \t")
13998 (bolp))
13999 (cdlatex-tab) t)
14000 ((org-inside-LaTeX-fragment-p)
14001 (cdlatex-tab) t)
14002 (t nil))))
14004 (defun org-cdlatex-underscore-caret (&optional arg)
14005 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14006 Revert to the normal definition outside of these fragments."
14007 (interactive "P")
14008 (if (org-inside-LaTeX-fragment-p)
14009 (call-interactively 'cdlatex-sub-superscript)
14010 (let (org-cdlatex-mode)
14011 (call-interactively (key-binding (vector last-input-event))))))
14013 (defun org-cdlatex-math-modify (&optional arg)
14014 "Execute `cdlatex-math-modify' in LaTeX fragments.
14015 Revert to the normal definition outside of these fragments."
14016 (interactive "P")
14017 (if (org-inside-LaTeX-fragment-p)
14018 (call-interactively 'cdlatex-math-modify)
14019 (let (org-cdlatex-mode)
14020 (call-interactively (key-binding (vector last-input-event))))))
14022 (defvar org-latex-fragment-image-overlays nil
14023 "List of overlays carrying the images of latex fragments.")
14024 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14026 (defun org-remove-latex-fragment-image-overlays ()
14027 "Remove all overlays with LaTeX fragment images in current buffer."
14028 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14029 (setq org-latex-fragment-image-overlays nil))
14031 (defun org-preview-latex-fragment (&optional subtree)
14032 "Preview the LaTeX fragment at point, or all locally or globally.
14033 If the cursor is in a LaTeX fragment, create the image and overlay
14034 it over the source code. If there is no fragment at point, display
14035 all fragments in the current text, from one headline to the next. With
14036 prefix SUBTREE, display all fragments in the current subtree. With a
14037 double prefix `C-u C-u', or when the cursor is before the first headline,
14038 display all fragments in the buffer.
14039 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14040 (interactive "P")
14041 (org-remove-latex-fragment-image-overlays)
14042 (save-excursion
14043 (save-restriction
14044 (let (beg end at msg)
14045 (cond
14046 ((or (equal subtree '(16))
14047 (not (save-excursion
14048 (re-search-backward (concat "^" outline-regexp) nil t))))
14049 (setq beg (point-min) end (point-max)
14050 msg "Creating images for buffer...%s"))
14051 ((equal subtree '(4))
14052 (org-back-to-heading)
14053 (setq beg (point) end (org-end-of-subtree t)
14054 msg "Creating images for subtree...%s"))
14056 (if (setq at (org-inside-LaTeX-fragment-p))
14057 (goto-char (max (point-min) (- (cdr at) 2)))
14058 (org-back-to-heading))
14059 (setq beg (point) end (progn (outline-next-heading) (point))
14060 msg (if at "Creating image...%s"
14061 "Creating images for entry...%s"))))
14062 (message msg "")
14063 (narrow-to-region beg end)
14064 (goto-char beg)
14065 (org-format-latex
14066 (concat "ltxpng/" (file-name-sans-extension
14067 (file-name-nondirectory
14068 buffer-file-name)))
14069 default-directory 'overlays msg at 'forbuffer)
14070 (message msg "done. Use `C-c C-c' to remove images.")))))
14072 (defvar org-latex-regexps
14073 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14074 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14075 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14076 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14077 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14078 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14079 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14080 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14081 "Regular expressions for matching embedded LaTeX.")
14083 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14084 "Replace LaTeX fragments with links to an image, and produce images."
14085 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14086 (let* ((prefixnodir (file-name-nondirectory prefix))
14087 (absprefix (expand-file-name prefix dir))
14088 (todir (file-name-directory absprefix))
14089 (opt org-format-latex-options)
14090 (matchers (plist-get opt :matchers))
14091 (re-list org-latex-regexps)
14092 (cnt 0) txt link beg end re e checkdir
14093 executables-checked
14094 m n block linkfile movefile ov)
14095 ;; Check if there are old images files with this prefix, and remove them
14096 (when (file-directory-p todir)
14097 (mapc 'delete-file
14098 (directory-files
14099 todir 'full
14100 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14101 ;; Check the different regular expressions
14102 (while (setq e (pop re-list))
14103 (setq m (car e) re (nth 1 e) n (nth 2 e)
14104 block (if (nth 3 e) "\n\n" ""))
14105 (when (member m matchers)
14106 (goto-char (point-min))
14107 (while (re-search-forward re nil t)
14108 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14109 (not (get-text-property (match-beginning n)
14110 'org-protected))
14111 (or (not overlays)
14112 (not (eq (get-char-property (match-beginning n)
14113 'org-overlay-type)
14114 'org-latex-overlay))))
14115 (setq txt (match-string n)
14116 beg (match-beginning n) end (match-end n)
14117 cnt (1+ cnt)
14118 linkfile (format "%s_%04d.png" prefix cnt)
14119 movefile (format "%s_%04d.png" absprefix cnt)
14120 link (concat block "[[file:" linkfile "]]" block))
14121 (if msg (message msg cnt))
14122 (goto-char beg)
14123 (unless checkdir ; make sure the directory exists
14124 (setq checkdir t)
14125 (or (file-directory-p todir) (make-directory todir)))
14127 (unless executables-checked
14128 (org-check-external-command
14129 "latex" "needed to convert LaTeX fragments to images")
14130 (org-check-external-command
14131 "dvipng" "needed to convert LaTeX fragments to images")
14132 (setq executables-checked t))
14134 (org-create-formula-image
14135 txt movefile opt forbuffer)
14136 (if overlays
14137 (progn
14138 (mapc (lambda (o)
14139 (if (eq (org-overlay-get o 'org-overlay-type)
14140 'org-latex-overlay)
14141 (org-delete-overlay o)))
14142 (org-overlays-in beg end))
14143 (setq ov (org-make-overlay beg end))
14144 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14145 (if (featurep 'xemacs)
14146 (progn
14147 (org-overlay-put ov 'invisible t)
14148 (org-overlay-put
14149 ov 'end-glyph
14150 (make-glyph (vector 'png :file movefile))))
14151 (org-overlay-put
14152 ov 'display
14153 (list 'image :type 'png :file movefile :ascent 'center)))
14154 (push ov org-latex-fragment-image-overlays)
14155 (goto-char end))
14156 (delete-region beg end)
14157 (insert link))))))))
14159 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14160 ;; This function borrows from Ganesh Swami's latex2png.el
14161 (defun org-create-formula-image (string tofile options buffer)
14162 (require 'org-latex)
14163 (let* ((tmpdir (if (featurep 'xemacs)
14164 (temp-directory)
14165 temporary-file-directory))
14166 (texfilebase (make-temp-name
14167 (expand-file-name "orgtex" tmpdir)))
14168 (texfile (concat texfilebase ".tex"))
14169 (dvifile (concat texfilebase ".dvi"))
14170 (pngfile (concat texfilebase ".png"))
14171 (fnh (if (featurep 'xemacs)
14172 (font-height (get-face-font 'default))
14173 (face-attribute 'default :height nil)))
14174 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14175 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14176 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14177 "Black"))
14178 (bg (or (plist-get options (if buffer :background :html-background))
14179 "Transparent")))
14180 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14181 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14182 (with-temp-file texfile
14183 (insert org-format-latex-header
14184 (if org-export-latex-packages-alist
14185 (concat "\n"
14186 (mapconcat (lambda(p)
14187 (if (equal "" (car p))
14188 (format "\\usepackage{%s}" (cadr p))
14189 (format "\\usepackage[%s]{%s}"
14190 (car p) (cadr p))))
14191 org-export-latex-packages-alist "\n"))
14193 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14194 (let ((dir default-directory))
14195 (condition-case nil
14196 (progn
14197 (cd tmpdir)
14198 (call-process "latex" nil nil nil texfile))
14199 (error nil))
14200 (cd dir))
14201 (if (not (file-exists-p dvifile))
14202 (progn (message "Failed to create dvi file from %s" texfile) nil)
14203 (condition-case nil
14204 (call-process "dvipng" nil nil nil
14205 "-fg" fg "-bg" bg
14206 "-D" dpi
14207 ;;"-x" scale "-y" scale
14208 "-T" "tight"
14209 "-o" pngfile
14210 dvifile)
14211 (error nil))
14212 (if (not (file-exists-p pngfile))
14213 (progn (message "Failed to create png file from %s" texfile) nil)
14214 ;; Use the requested file name and clean up
14215 (copy-file pngfile tofile 'replace)
14216 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14217 (delete-file (concat texfilebase e)))
14218 pngfile))))
14220 (defun org-dvipng-color (attr)
14221 "Return an rgb color specification for dvipng."
14222 (apply 'format "rgb %s %s %s"
14223 (mapcar 'org-normalize-color
14224 (color-values (face-attribute 'default attr nil)))))
14226 (defun org-normalize-color (value)
14227 "Return string to be used as color value for an RGB component."
14228 (format "%g" (/ value 65535.0)))
14230 ;;;; Key bindings
14232 ;; Make `C-c C-x' a prefix key
14233 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14235 ;; TAB key with modifiers
14236 (org-defkey org-mode-map "\C-i" 'org-cycle)
14237 (org-defkey org-mode-map [(tab)] 'org-cycle)
14238 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14239 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14240 (org-defkey org-mode-map "\M-\t" 'org-complete)
14241 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14242 ;; The following line is necessary under Suse GNU/Linux
14243 (unless (featurep 'xemacs)
14244 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14245 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14246 (define-key org-mode-map [backtab] 'org-shifttab)
14248 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14249 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14250 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14252 ;; Cursor keys with modifiers
14253 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14254 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14255 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14256 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14258 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14259 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14260 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14261 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14263 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14264 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14265 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14266 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14268 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14269 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14271 ;;; Extra keys for tty access.
14272 ;; We only set them when really needed because otherwise the
14273 ;; menus don't show the simple keys
14275 (when (or org-use-extra-keys
14276 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14277 (not window-system))
14278 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14279 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14280 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14281 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14282 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14283 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14284 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14285 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14286 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14287 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14288 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14289 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14290 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14291 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14292 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14293 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14294 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14295 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14296 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14297 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14298 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14299 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14300 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14301 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14302 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14303 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14304 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14305 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14307 ;; All the other keys
14309 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14310 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14311 (if (boundp 'narrow-map)
14312 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14313 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14314 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14315 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14316 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14317 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14318 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14319 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14320 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14321 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14322 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14323 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14324 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14325 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14326 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14327 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14328 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14329 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14330 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14331 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14332 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14333 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14334 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14335 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14336 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14337 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14338 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14339 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14340 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14341 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14342 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14343 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14344 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14345 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14346 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14347 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14348 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14349 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14350 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14351 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14352 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14353 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14354 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14355 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14356 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14357 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14358 (org-defkey org-mode-map "\C-c^" 'org-sort)
14359 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14360 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14361 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14362 (org-defkey org-mode-map "\C-m" 'org-return)
14363 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14364 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14365 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14366 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14367 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14368 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14369 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14370 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14371 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14372 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14373 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14374 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14375 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14376 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14377 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14378 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14379 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14380 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14381 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14383 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14384 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14385 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14386 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14388 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14389 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14390 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14391 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14392 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14393 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14394 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14395 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14396 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14397 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14398 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14399 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14400 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14401 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14402 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14404 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14405 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14406 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14407 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14409 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14411 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14413 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14414 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14416 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14419 (when (featurep 'xemacs)
14420 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14423 (defvar org-self-insert-command-undo-counter 0)
14425 (defvar org-table-auto-blank-field) ; defined in org-table.el
14426 (defun org-self-insert-command (N)
14427 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14428 If the cursor is in a table looking at whitespace, the whitespace is
14429 overwritten, and the table is not marked as requiring realignment."
14430 (interactive "p")
14431 (if (and
14432 (org-table-p)
14433 (progn
14434 ;; check if we blank the field, and if that triggers align
14435 (and (featurep 'org-table) org-table-auto-blank-field
14436 (member last-command
14437 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14438 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14439 ;; got extra space, this field does not determine column width
14440 (let (org-table-may-need-update) (org-table-blank-field))
14441 ;; no extra space, this field may determine column width
14442 (org-table-blank-field)))
14444 (eq N 1)
14445 (looking-at "[^|\n]* |"))
14446 (let (org-table-may-need-update)
14447 (goto-char (1- (match-end 0)))
14448 (delete-backward-char 1)
14449 (goto-char (match-beginning 0))
14450 (self-insert-command N))
14451 (setq org-table-may-need-update t)
14452 (self-insert-command N)
14453 (org-fix-tags-on-the-fly)
14454 (if org-self-insert-cluster-for-undo
14455 (if (not (eq last-command 'org-self-insert-command))
14456 (setq org-self-insert-command-undo-counter 1)
14457 (if (>= org-self-insert-command-undo-counter 20)
14458 (setq org-self-insert-command-undo-counter 1)
14459 (and (> org-self-insert-command-undo-counter 0)
14460 buffer-undo-list
14461 (not (cadr buffer-undo-list)) ; remove nil entry
14462 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14463 (setq org-self-insert-command-undo-counter
14464 (1+ org-self-insert-command-undo-counter)))))))
14466 (defun org-fix-tags-on-the-fly ()
14467 (when (and (equal (char-after (point-at-bol)) ?*)
14468 (org-on-heading-p))
14469 (org-align-tags-here org-tags-column)))
14471 (defun org-delete-backward-char (N)
14472 "Like `delete-backward-char', insert whitespace at field end in tables.
14473 When deleting backwards, in tables this function will insert whitespace in
14474 front of the next \"|\" separator, to keep the table aligned. The table will
14475 still be marked for re-alignment if the field did fill the entire column,
14476 because, in this case the deletion might narrow the column."
14477 (interactive "p")
14478 (if (and (org-table-p)
14479 (eq N 1)
14480 (string-match "|" (buffer-substring (point-at-bol) (point)))
14481 (looking-at ".*?|"))
14482 (let ((pos (point))
14483 (noalign (looking-at "[^|\n\r]* |"))
14484 (c org-table-may-need-update))
14485 (backward-delete-char N)
14486 (skip-chars-forward "^|")
14487 (insert " ")
14488 (goto-char (1- pos))
14489 ;; noalign: if there were two spaces at the end, this field
14490 ;; does not determine the width of the column.
14491 (if noalign (setq org-table-may-need-update c)))
14492 (backward-delete-char N)
14493 (org-fix-tags-on-the-fly)))
14495 (defun org-delete-char (N)
14496 "Like `delete-char', but insert whitespace at field end in tables.
14497 When deleting characters, in tables this function will insert whitespace in
14498 front of the next \"|\" separator, to keep the table aligned. The table will
14499 still be marked for re-alignment if the field did fill the entire column,
14500 because, in this case the deletion might narrow the column."
14501 (interactive "p")
14502 (if (and (org-table-p)
14503 (not (bolp))
14504 (not (= (char-after) ?|))
14505 (eq N 1))
14506 (if (looking-at ".*?|")
14507 (let ((pos (point))
14508 (noalign (looking-at "[^|\n\r]* |"))
14509 (c org-table-may-need-update))
14510 (replace-match (concat
14511 (substring (match-string 0) 1 -1)
14512 " |"))
14513 (goto-char pos)
14514 ;; noalign: if there were two spaces at the end, this field
14515 ;; does not determine the width of the column.
14516 (if noalign (setq org-table-may-need-update c)))
14517 (delete-char N))
14518 (delete-char N)
14519 (org-fix-tags-on-the-fly)))
14521 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14522 (put 'org-self-insert-command 'delete-selection t)
14523 (put 'orgtbl-self-insert-command 'delete-selection t)
14524 (put 'org-delete-char 'delete-selection 'supersede)
14525 (put 'org-delete-backward-char 'delete-selection 'supersede)
14526 (put 'org-yank 'delete-selection 'yank)
14528 ;; Make `flyspell-mode' delay after some commands
14529 (put 'org-self-insert-command 'flyspell-delayed t)
14530 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14531 (put 'org-delete-char 'flyspell-delayed t)
14532 (put 'org-delete-backward-char 'flyspell-delayed t)
14534 ;; Make pabbrev-mode expand after org-mode commands
14535 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14536 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14538 ;; How to do this: Measure non-white length of current string
14539 ;; If equal to column width, we should realign.
14541 (defun org-remap (map &rest commands)
14542 "In MAP, remap the functions given in COMMANDS.
14543 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14544 (let (new old)
14545 (while commands
14546 (setq old (pop commands) new (pop commands))
14547 (if (fboundp 'command-remapping)
14548 (org-defkey map (vector 'remap old) new)
14549 (substitute-key-definition old new map global-map)))))
14551 (when (eq org-enable-table-editor 'optimized)
14552 ;; If the user wants maximum table support, we need to hijack
14553 ;; some standard editing functions
14554 (org-remap org-mode-map
14555 'self-insert-command 'org-self-insert-command
14556 'delete-char 'org-delete-char
14557 'delete-backward-char 'org-delete-backward-char)
14558 (org-defkey org-mode-map "|" 'org-force-self-insert))
14560 (defvar org-ctrl-c-ctrl-c-hook nil
14561 "Hook for functions attaching themselves to `C-c C-c'.
14562 This can be used to add additional functionality to the C-c C-c key which
14563 executes context-dependent commands.
14564 Each function will be called with no arguments. The function must check
14565 if the context is appropriate for it to act. If yes, it should do its
14566 thing and then return a non-nil value. If the context is wrong,
14567 just do nothing and return nil.")
14569 (defvar org-tab-first-hook nil
14570 "Hook for functions to attach themselves to TAB.
14571 See `org-ctrl-c-ctrl-c-hook' for more information.
14572 This hook runs as the first action when TAB is pressed, even before
14573 `org-cycle' messes around with the `outline-regexp' to cater for
14574 inline tasks and plain list item folding.
14575 If any function in this hook returns t, not other actions like table
14576 field motion visibility cycling will be done.")
14578 (defvar org-tab-after-check-for-table-hook nil
14579 "Hook for functions to attach themselves to TAB.
14580 See `org-ctrl-c-ctrl-c-hook' for more information.
14581 This hook runs after it has been established that the cursor is not in a
14582 table, but before checking if the cursor is in a headline or if global cycling
14583 should be done.
14584 If any function in this hook returns t, not other actions like visibility
14585 cycling will be done.")
14587 (defvar org-tab-after-check-for-cycling-hook nil
14588 "Hook for functions to attach themselves to TAB.
14589 See `org-ctrl-c-ctrl-c-hook' for more information.
14590 This hook runs after it has been established that not table field motion and
14591 not visibility should be done because of current context. This is probably
14592 the place where a package like yasnippets can hook in.")
14594 (defvar org-metaleft-hook nil
14595 "Hook for functions attaching themselves to `M-left'.
14596 See `org-ctrl-c-ctrl-c-hook' for more information.")
14597 (defvar org-metaright-hook nil
14598 "Hook for functions attaching themselves to `M-right'.
14599 See `org-ctrl-c-ctrl-c-hook' for more information.")
14600 (defvar org-metaup-hook nil
14601 "Hook for functions attaching themselves to `M-up'.
14602 See `org-ctrl-c-ctrl-c-hook' for more information.")
14603 (defvar org-metadown-hook nil
14604 "Hook for functions attaching themselves to `M-down'.
14605 See `org-ctrl-c-ctrl-c-hook' for more information.")
14606 (defvar org-shiftmetaleft-hook nil
14607 "Hook for functions attaching themselves to `M-S-left'.
14608 See `org-ctrl-c-ctrl-c-hook' for more information.")
14609 (defvar org-shiftmetaright-hook nil
14610 "Hook for functions attaching themselves to `M-S-right'.
14611 See `org-ctrl-c-ctrl-c-hook' for more information.")
14612 (defvar org-shiftmetaup-hook nil
14613 "Hook for functions attaching themselves to `M-S-up'.
14614 See `org-ctrl-c-ctrl-c-hook' for more information.")
14615 (defvar org-shiftmetadown-hook nil
14616 "Hook for functions attaching themselves to `M-S-down'.
14617 See `org-ctrl-c-ctrl-c-hook' for more information.")
14618 (defvar org-metareturn-hook nil
14619 "Hook for functions attaching themselves to `M-RET'.
14620 See `org-ctrl-c-ctrl-c-hook' for more information.")
14622 (defun org-modifier-cursor-error ()
14623 "Throw an error, a modified cursor command was applied in wrong context."
14624 (error "This command is active in special context like tables, headlines or items"))
14626 (defun org-shiftselect-error ()
14627 "Throw an error because Shift-Cursor command was applied in wrong context."
14628 (if (and (boundp 'shift-select-mode) shift-select-mode)
14629 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14630 (error "This command works only in special context like headlines or timestamps.")))
14632 (defun org-call-for-shift-select (cmd)
14633 (let ((this-command-keys-shift-translated t))
14634 (call-interactively cmd)))
14636 (defun org-shifttab (&optional arg)
14637 "Global visibility cycling or move to previous table field.
14638 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14639 on context.
14640 See the individual commands for more information."
14641 (interactive "P")
14642 (cond
14643 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14644 ((integerp arg)
14645 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
14646 (message "Content view to level: %d" arg)
14647 (org-content (prefix-numeric-value arg2))
14648 (setq org-cycle-global-status 'overview)))
14649 (t (call-interactively 'org-global-cycle))))
14651 (defun org-shiftmetaleft ()
14652 "Promote subtree or delete table column.
14653 Calls `org-promote-subtree', `org-outdent-item',
14654 or `org-table-delete-column', depending on context.
14655 See the individual commands for more information."
14656 (interactive)
14657 (cond
14658 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14659 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14660 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14661 ((org-at-item-p) (call-interactively 'org-outdent-item))
14662 (t (org-modifier-cursor-error))))
14664 (defun org-shiftmetaright ()
14665 "Demote subtree or insert table column.
14666 Calls `org-demote-subtree', `org-indent-item',
14667 or `org-table-insert-column', depending on context.
14668 See the individual commands for more information."
14669 (interactive)
14670 (cond
14671 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14672 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14673 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14674 ((org-at-item-p) (call-interactively 'org-indent-item))
14675 (t (org-modifier-cursor-error))))
14677 (defun org-shiftmetaup (&optional arg)
14678 "Move subtree up or kill table row.
14679 Calls `org-move-subtree-up' or `org-table-kill-row' or
14680 `org-move-item-up' depending on context. See the individual commands
14681 for more information."
14682 (interactive "P")
14683 (cond
14684 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14685 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14686 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14687 ((org-at-item-p) (call-interactively 'org-move-item-up))
14688 (t (org-modifier-cursor-error))))
14690 (defun org-shiftmetadown (&optional arg)
14691 "Move subtree down or insert table row.
14692 Calls `org-move-subtree-down' or `org-table-insert-row' or
14693 `org-move-item-down', depending on context. See the individual
14694 commands for more information."
14695 (interactive "P")
14696 (cond
14697 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14698 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14699 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14700 ((org-at-item-p) (call-interactively 'org-move-item-down))
14701 (t (org-modifier-cursor-error))))
14703 (defun org-metaleft (&optional arg)
14704 "Promote heading or move table column to left.
14705 Calls `org-do-promote' or `org-table-move-column', depending on context.
14706 With no specific context, calls the Emacs default `backward-word'.
14707 See the individual commands for more information."
14708 (interactive "P")
14709 (cond
14710 ((run-hook-with-args-until-success 'org-metaleft-hook))
14711 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14712 ((or (org-on-heading-p)
14713 (and (org-region-active-p)
14714 (save-excursion
14715 (goto-char (region-beginning))
14716 (org-on-heading-p))))
14717 (call-interactively 'org-do-promote))
14718 ((or (org-at-item-p)
14719 (and (org-region-active-p)
14720 (save-excursion
14721 (goto-char (region-beginning))
14722 (org-at-item-p))))
14723 (call-interactively 'org-outdent-item))
14724 (t (call-interactively 'backward-word))))
14726 (defun org-metaright (&optional arg)
14727 "Demote subtree or move table column to right.
14728 Calls `org-do-demote' or `org-table-move-column', depending on context.
14729 With no specific context, calls the Emacs default `forward-word'.
14730 See the individual commands for more information."
14731 (interactive "P")
14732 (cond
14733 ((run-hook-with-args-until-success 'org-metaright-hook))
14734 ((org-at-table-p) (call-interactively 'org-table-move-column))
14735 ((or (org-on-heading-p)
14736 (and (org-region-active-p)
14737 (save-excursion
14738 (goto-char (region-beginning))
14739 (org-on-heading-p))))
14740 (call-interactively 'org-do-demote))
14741 ((or (org-at-item-p)
14742 (and (org-region-active-p)
14743 (save-excursion
14744 (goto-char (region-beginning))
14745 (org-at-item-p))))
14746 (call-interactively 'org-indent-item))
14747 (t (call-interactively 'forward-word))))
14749 (defun org-metaup (&optional arg)
14750 "Move subtree up or move table row up.
14751 Calls `org-move-subtree-up' or `org-table-move-row' or
14752 `org-move-item-up', depending on context. See the individual commands
14753 for more information."
14754 (interactive "P")
14755 (cond
14756 ((run-hook-with-args-until-success 'org-metaup-hook))
14757 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14758 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14759 ((org-at-item-p) (call-interactively 'org-move-item-up))
14760 (t (transpose-lines 1) (beginning-of-line -1))))
14762 (defun org-metadown (&optional arg)
14763 "Move subtree down or move table row down.
14764 Calls `org-move-subtree-down' or `org-table-move-row' or
14765 `org-move-item-down', depending on context. See the individual
14766 commands for more information."
14767 (interactive "P")
14768 (cond
14769 ((run-hook-with-args-until-success 'org-metadown-hook))
14770 ((org-at-table-p) (call-interactively 'org-table-move-row))
14771 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14772 ((org-at-item-p) (call-interactively 'org-move-item-down))
14773 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14775 (defun org-shiftup (&optional arg)
14776 "Increase item in timestamp or increase priority of current headline.
14777 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14778 depending on context. See the individual commands for more information."
14779 (interactive "P")
14780 (cond
14781 ((and org-support-shift-select (org-region-active-p))
14782 (org-call-for-shift-select 'previous-line))
14783 ((org-at-timestamp-p t)
14784 (call-interactively (if org-edit-timestamp-down-means-later
14785 'org-timestamp-down 'org-timestamp-up)))
14786 ((and (not (eq org-support-shift-select 'always))
14787 org-enable-priority-commands
14788 (org-on-heading-p))
14789 (call-interactively 'org-priority-up))
14790 ((and (not org-support-shift-select) (org-at-item-p))
14791 (call-interactively 'org-previous-item))
14792 ((org-clocktable-try-shift 'up arg))
14793 (org-support-shift-select
14794 (org-call-for-shift-select 'previous-line))
14795 (t (org-shiftselect-error))))
14797 (defun org-shiftdown (&optional arg)
14798 "Decrease item in timestamp or decrease priority of current headline.
14799 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14800 depending on context. See the individual commands for more information."
14801 (interactive "P")
14802 (cond
14803 ((and org-support-shift-select (org-region-active-p))
14804 (org-call-for-shift-select 'next-line))
14805 ((org-at-timestamp-p t)
14806 (call-interactively (if org-edit-timestamp-down-means-later
14807 'org-timestamp-up 'org-timestamp-down)))
14808 ((and (not (eq org-support-shift-select 'always))
14809 org-enable-priority-commands
14810 (org-on-heading-p))
14811 (call-interactively 'org-priority-down))
14812 ((and (not org-support-shift-select) (org-at-item-p))
14813 (call-interactively 'org-next-item))
14814 ((org-clocktable-try-shift 'down arg))
14815 (org-support-shift-select
14816 (org-call-for-shift-select 'next-line))
14817 (t (org-shiftselect-error))))
14819 (defun org-shiftright (&optional arg)
14820 "Cycle the thing at point or in the current line, depending on context.
14821 Depending on context, this does one of the following:
14823 - switch a timestamp at point one day into the future
14824 - on a headline, switch to the next TODO keyword.
14825 - on an item, switch entire list to the next bullet type
14826 - on a property line, switch to the next allowed value
14827 - on a clocktable definition line, move time block into the future"
14828 (interactive "P")
14829 (cond
14830 ((and org-support-shift-select (org-region-active-p))
14831 (org-call-for-shift-select 'forward-char))
14832 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14833 ((and (not (eq org-support-shift-select 'always))
14834 (org-on-heading-p))
14835 (let ((org-inhibit-logging
14836 (not org-treat-S-cursor-todo-selection-as-state-change))
14837 (org-inhibit-blocking
14838 (not org-treat-S-cursor-todo-selection-as-state-change)))
14839 (org-call-with-arg 'org-todo 'right)))
14840 ((or (and org-support-shift-select
14841 (not (eq org-support-shift-select 'always))
14842 (org-at-item-bullet-p))
14843 (and (not org-support-shift-select) (org-at-item-p)))
14844 (org-call-with-arg 'org-cycle-list-bullet nil))
14845 ((and (not (eq org-support-shift-select 'always))
14846 (org-at-property-p))
14847 (call-interactively 'org-property-next-allowed-value))
14848 ((org-clocktable-try-shift 'right arg))
14849 (org-support-shift-select
14850 (org-call-for-shift-select 'forward-char))
14851 (t (org-shiftselect-error))))
14853 (defun org-shiftleft (&optional arg)
14854 "Cycle the thing at point or in the current line, depending on context.
14855 Depending on context, this does one of the following:
14857 - switch a timestamp at point one day into the past
14858 - on a headline, switch to the previous TODO keyword.
14859 - on an item, switch entire list to the previous bullet type
14860 - on a property line, switch to the previous allowed value
14861 - on a clocktable definition line, move time block into the past"
14862 (interactive "P")
14863 (cond
14864 ((and org-support-shift-select (org-region-active-p))
14865 (org-call-for-shift-select 'backward-char))
14866 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14867 ((and (not (eq org-support-shift-select 'always))
14868 (org-on-heading-p))
14869 (let ((org-inhibit-logging
14870 (not org-treat-S-cursor-todo-selection-as-state-change))
14871 (org-inhibit-blocking
14872 (not org-treat-S-cursor-todo-selection-as-state-change)))
14873 (org-call-with-arg 'org-todo 'left)))
14874 ((or (and org-support-shift-select
14875 (not (eq org-support-shift-select 'always))
14876 (org-at-item-bullet-p))
14877 (and (not org-support-shift-select) (org-at-item-p)))
14878 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14879 ((and (not (eq org-support-shift-select 'always))
14880 (org-at-property-p))
14881 (call-interactively 'org-property-previous-allowed-value))
14882 ((org-clocktable-try-shift 'left arg))
14883 (org-support-shift-select
14884 (org-call-for-shift-select 'backward-char))
14885 (t (org-shiftselect-error))))
14887 (defun org-shiftcontrolright ()
14888 "Switch to next TODO set."
14889 (interactive)
14890 (cond
14891 ((and org-support-shift-select (org-region-active-p))
14892 (org-call-for-shift-select 'forward-word))
14893 ((and (not (eq org-support-shift-select 'always))
14894 (org-on-heading-p))
14895 (org-call-with-arg 'org-todo 'nextset))
14896 (org-support-shift-select
14897 (org-call-for-shift-select 'forward-word))
14898 (t (org-shiftselect-error))))
14900 (defun org-shiftcontrolleft ()
14901 "Switch to previous TODO set."
14902 (interactive)
14903 (cond
14904 ((and org-support-shift-select (org-region-active-p))
14905 (org-call-for-shift-select 'backward-word))
14906 ((and (not (eq org-support-shift-select 'always))
14907 (org-on-heading-p))
14908 (org-call-with-arg 'org-todo 'previousset))
14909 (org-support-shift-select
14910 (org-call-for-shift-select 'backward-word))
14911 (t (org-shiftselect-error))))
14913 (defun org-ctrl-c-ret ()
14914 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14915 (interactive)
14916 (cond
14917 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14918 (t (call-interactively 'org-insert-heading))))
14920 (defun org-copy-special ()
14921 "Copy region in table or copy current subtree.
14922 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14923 See the individual commands for more information."
14924 (interactive)
14925 (call-interactively
14926 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14928 (defun org-cut-special ()
14929 "Cut region in table or cut current subtree.
14930 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14931 See the individual commands for more information."
14932 (interactive)
14933 (call-interactively
14934 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14936 (defun org-paste-special (arg)
14937 "Paste rectangular region into table, or past subtree relative to level.
14938 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14939 See the individual commands for more information."
14940 (interactive "P")
14941 (if (org-at-table-p)
14942 (org-table-paste-rectangle)
14943 (org-paste-subtree arg)))
14945 (defun org-edit-special ()
14946 "Call a special editor for the stuff at point.
14947 When at a table, call the formula editor with `org-table-edit-formulas'.
14948 When at the first line of an src example, call `org-edit-src-code'.
14949 When in an #+include line, visit the include file. Otherwise call
14950 `ffap' to visit the file at point."
14951 (interactive)
14952 (cond
14953 ((org-at-table-p)
14954 (call-interactively 'org-table-edit-formulas))
14955 ((save-excursion
14956 (beginning-of-line 1)
14957 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14958 (find-file (org-trim (match-string 1))))
14959 ((org-edit-src-code))
14960 ((org-edit-fixed-width-region))
14961 (t (call-interactively 'ffap))))
14964 (defun org-ctrl-c-ctrl-c (&optional arg)
14965 "Set tags in headline, or update according to changed information at point.
14967 This command does many different things, depending on context:
14969 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14970 this is what we do.
14972 - If the cursor is on a statistics cookie, update it.
14974 - If the cursor is in a headline, prompt for tags and insert them
14975 into the current line, aligned to `org-tags-column'. When called
14976 with prefix arg, realign all tags in the current buffer.
14978 - If the cursor is in one of the special #+KEYWORD lines, this
14979 triggers scanning the buffer for these lines and updating the
14980 information.
14982 - If the cursor is inside a table, realign the table. This command
14983 works even if the automatic table editor has been turned off.
14985 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14986 the entire table.
14988 - If the cursor is at a footnote reference or definition, jump to
14989 the corresponding definition or references, respectively.
14991 - If the cursor is a the beginning of a dynamic block, update it.
14993 - If the cursor is inside a table created by the table.el package,
14994 activate that table.
14996 - If the current buffer is a remember buffer, close note and file
14997 it. A prefix argument of 1 files to the default location
14998 without further interaction. A prefix argument of 2 files to
14999 the currently clocking task.
15001 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15002 links in this buffer.
15004 - If the cursor is on a numbered item in a plain list, renumber the
15005 ordered list.
15007 - If the cursor is on a checkbox, toggle it."
15008 (interactive "P")
15009 (let ((org-enable-table-editor t))
15010 (cond
15011 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15012 org-occur-highlights
15013 org-latex-fragment-image-overlays)
15014 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15015 (org-remove-occur-highlights)
15016 (org-remove-latex-fragment-image-overlays)
15017 (message "Temporary highlights/overlays removed from current buffer"))
15018 ((and (local-variable-p 'org-finish-function (current-buffer))
15019 (fboundp org-finish-function))
15020 (funcall org-finish-function))
15021 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15022 ((org-at-property-p)
15023 (call-interactively 'org-property-action))
15024 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15025 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15026 (or (org-on-heading-p) (org-at-item-p)))
15027 (call-interactively 'org-update-statistics-cookies))
15028 ((org-on-heading-p) (call-interactively 'org-set-tags))
15029 ((org-at-table.el-p)
15030 (require 'table)
15031 (beginning-of-line 1)
15032 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15033 (call-interactively 'table-recognize-table))
15034 ((org-at-table-p)
15035 (org-table-maybe-eval-formula)
15036 (if arg
15037 (call-interactively 'org-table-recalculate)
15038 (org-table-maybe-recalculate-line))
15039 (call-interactively 'org-table-align))
15040 ((or (org-footnote-at-reference-p)
15041 (org-footnote-at-definition-p))
15042 (call-interactively 'org-footnote-action))
15043 ((org-at-item-checkbox-p)
15044 (call-interactively 'org-toggle-checkbox))
15045 ((org-at-item-p)
15046 (if arg
15047 (call-interactively 'org-toggle-checkbox)
15048 (call-interactively 'org-maybe-renumber-ordered-list)))
15049 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
15050 ;; Dynamic block
15051 (beginning-of-line 1)
15052 (save-excursion (org-update-dblock)))
15053 ((save-excursion
15054 (beginning-of-line 1)
15055 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15056 (cond
15057 ((equal (match-string 1) "TBLFM")
15058 ;; Recalculate the table before this line
15059 (save-excursion
15060 (beginning-of-line 1)
15061 (skip-chars-backward " \r\n\t")
15062 (if (org-at-table-p)
15063 (org-call-with-arg 'org-table-recalculate t))))
15065 ; (org-set-regexps-and-options)
15066 ; (org-restart-font-lock)
15067 (let ((org-inhibit-startup t)) (org-mode-restart))
15068 (message "Local setup has been refreshed"))))
15069 ((org-clock-update-time-maybe))
15070 (t (error "C-c C-c can do nothing useful at this location.")))))
15072 (defun org-mode-restart ()
15073 "Restart Org-mode, to scan again for special lines.
15074 Also updates the keyword regular expressions."
15075 (interactive)
15076 (org-mode)
15077 (message "Org-mode restarted"))
15079 (defun org-kill-note-or-show-branches ()
15080 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15081 (interactive)
15082 (if (not org-finish-function)
15083 (call-interactively 'show-branches)
15084 (let ((org-note-abort t))
15085 (funcall org-finish-function))))
15087 (defun org-return (&optional indent)
15088 "Goto next table row or insert a newline.
15089 Calls `org-table-next-row' or `newline', depending on context.
15090 See the individual commands for more information."
15091 (interactive)
15092 (cond
15093 ((bobp) (if indent (newline-and-indent) (newline)))
15094 ((org-at-table-p)
15095 (org-table-justify-field-maybe)
15096 (call-interactively 'org-table-next-row))
15097 ((and org-return-follows-link
15098 (eq (get-text-property (point) 'face) 'org-link))
15099 (call-interactively 'org-open-at-point))
15100 ((and (org-at-heading-p)
15101 (looking-at
15102 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15103 (org-show-entry)
15104 (end-of-line 1)
15105 (newline))
15106 (t (if indent (newline-and-indent) (newline)))))
15108 (defun org-return-indent ()
15109 "Goto next table row or insert a newline and indent.
15110 Calls `org-table-next-row' or `newline-and-indent', depending on
15111 context. See the individual commands for more information."
15112 (interactive)
15113 (org-return t))
15115 (defun org-ctrl-c-star ()
15116 "Compute table, or change heading status of lines.
15117 Calls `org-table-recalculate' or `org-toggle-heading',
15118 depending on context."
15119 (interactive)
15120 (cond
15121 ((org-at-table-p)
15122 (call-interactively 'org-table-recalculate))
15124 ;; Convert all lines in region to list items
15125 (call-interactively 'org-toggle-heading))))
15127 (defun org-ctrl-c-minus ()
15128 "Insert separator line in table or modify bullet status of line.
15129 Also turns a plain line or a region of lines into list items.
15130 Calls `org-table-insert-hline', `org-toggle-item', or
15131 `org-cycle-list-bullet', depending on context."
15132 (interactive)
15133 (cond
15134 ((org-at-table-p)
15135 (call-interactively 'org-table-insert-hline))
15136 ((org-region-active-p)
15137 (call-interactively 'org-toggle-item))
15138 ((org-in-item-p)
15139 (call-interactively 'org-cycle-list-bullet))
15141 (call-interactively 'org-toggle-item))))
15143 (defun org-toggle-item ()
15144 "Convert headings or normal lines to items, items to normal lines.
15145 If there is no active region, only the current line is considered.
15147 If the first line in the region is a headline, convert all headlines to items.
15149 If the first line in the region is an item, convert all items to normal lines.
15151 If the first line is normal text, add an item bullet to each line."
15152 (interactive)
15153 (let (l2 l beg end)
15154 (if (org-region-active-p)
15155 (setq beg (region-beginning) end (region-end))
15156 (setq beg (point-at-bol)
15157 end (min (1+ (point-at-eol)) (point-max))))
15158 (save-excursion
15159 (goto-char end)
15160 (setq l2 (org-current-line))
15161 (goto-char beg)
15162 (beginning-of-line 1)
15163 (setq l (1- (org-current-line)))
15164 (if (org-at-item-p)
15165 ;; We already have items, de-itemize
15166 (while (< (setq l (1+ l)) l2)
15167 (when (org-at-item-p)
15168 (goto-char (match-beginning 2))
15169 (delete-region (match-beginning 2) (match-end 2))
15170 (and (looking-at "[ \t]+") (replace-match "")))
15171 (beginning-of-line 2))
15172 (if (org-on-heading-p)
15173 ;; Headings, convert to items
15174 (while (< (setq l (1+ l)) l2)
15175 (if (looking-at org-outline-regexp)
15176 (replace-match "- " t t))
15177 (beginning-of-line 2))
15178 ;; normal lines, turn them into items
15179 (while (< (setq l (1+ l)) l2)
15180 (unless (org-at-item-p)
15181 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15182 (replace-match "\\1- \\2")))
15183 (beginning-of-line 2)))))))
15185 (defun org-toggle-heading (&optional nstars)
15186 "Convert headings to normal text, or items or text to headings.
15187 If there is no active region, only the current line is considered.
15189 If the first line is a heading, remove the stars from all headlines
15190 in the region.
15192 If the first line is a plain list item, turn all plain list items
15193 into headings.
15195 If the first line is a normal line, turn each and every line in the
15196 region into a heading.
15198 When converting a line into a heading, the number of stars is chosen
15199 such that the lines become children of the current entry. However,
15200 when a prefix argument is given, its value determines the number of
15201 stars to add."
15202 (interactive "P")
15203 (let (l2 l itemp beg end)
15204 (if (org-region-active-p)
15205 (setq beg (region-beginning) end (region-end))
15206 (setq beg (point-at-bol)
15207 end (min (1+ (point-at-eol)) (point-max))))
15208 (save-excursion
15209 (goto-char end)
15210 (setq l2 (org-current-line))
15211 (goto-char beg)
15212 (beginning-of-line 1)
15213 (setq l (1- (org-current-line)))
15214 (if (org-on-heading-p)
15215 ;; We already have headlines, de-star them
15216 (while (< (setq l (1+ l)) l2)
15217 (when (org-on-heading-p t)
15218 (and (looking-at outline-regexp) (replace-match "")))
15219 (beginning-of-line 2))
15220 (setq itemp (org-at-item-p))
15221 (let* ((stars
15222 (if nstars
15223 (make-string (prefix-numeric-value current-prefix-arg)
15225 (save-excursion
15226 (if (re-search-backward org-complex-heading-regexp nil t)
15227 (match-string 1) ""))))
15228 (add-stars (cond (nstars "")
15229 ((equal stars "") "*")
15230 (org-odd-levels-only "**")
15231 (t "*")))
15232 (rpl (concat stars add-stars " ")))
15233 (while (< (setq l (1+ l)) l2)
15234 (if itemp
15235 (and (org-at-item-p) (replace-match rpl t t))
15236 (unless (org-on-heading-p)
15237 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15238 (replace-match (concat rpl (match-string 2))))))
15239 (beginning-of-line 2)))))))
15241 (defun org-meta-return (&optional arg)
15242 "Insert a new heading or wrap a region in a table.
15243 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15244 See the individual commands for more information."
15245 (interactive "P")
15246 (cond
15247 ((run-hook-with-args-until-success 'org-metareturn-hook))
15248 ((org-at-table-p)
15249 (call-interactively 'org-table-wrap-region))
15250 (t (call-interactively 'org-insert-heading))))
15252 ;;; Menu entries
15254 ;; Define the Org-mode menus
15255 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15256 '("Tbl"
15257 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15258 ["Next Field" org-cycle (org-at-table-p)]
15259 ["Previous Field" org-shifttab (org-at-table-p)]
15260 ["Next Row" org-return (org-at-table-p)]
15261 "--"
15262 ["Blank Field" org-table-blank-field (org-at-table-p)]
15263 ["Edit Field" org-table-edit-field (org-at-table-p)]
15264 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15265 "--"
15266 ("Column"
15267 ["Move Column Left" org-metaleft (org-at-table-p)]
15268 ["Move Column Right" org-metaright (org-at-table-p)]
15269 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15270 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15271 ("Row"
15272 ["Move Row Up" org-metaup (org-at-table-p)]
15273 ["Move Row Down" org-metadown (org-at-table-p)]
15274 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15275 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15276 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15277 "--"
15278 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15279 ("Rectangle"
15280 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15281 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15282 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15283 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15284 "--"
15285 ("Calculate"
15286 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15287 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15288 ["Edit Formulas" org-edit-special (org-at-table-p)]
15289 "--"
15290 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15291 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15292 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15293 "--"
15294 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15295 "--"
15296 ["Sum Column/Rectangle" org-table-sum
15297 (or (org-at-table-p) (org-region-active-p))]
15298 ["Which Column?" org-table-current-column (org-at-table-p)])
15299 ["Debug Formulas"
15300 org-table-toggle-formula-debugger
15301 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15302 ["Show Col/Row Numbers"
15303 org-table-toggle-coordinate-overlays
15304 :style toggle
15305 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15306 "--"
15307 ["Create" org-table-create (and (not (org-at-table-p))
15308 org-enable-table-editor)]
15309 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15310 ["Import from File" org-table-import (not (org-at-table-p))]
15311 ["Export to File" org-table-export (org-at-table-p)]
15312 "--"
15313 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15315 (easy-menu-define org-org-menu org-mode-map "Org menu"
15316 '("Org"
15317 ("Show/Hide"
15318 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15319 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15320 ["Sparse Tree..." org-sparse-tree t]
15321 ["Reveal Context" org-reveal t]
15322 ["Show All" show-all t]
15323 "--"
15324 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15325 "--"
15326 ["New Heading" org-insert-heading t]
15327 ("Navigate Headings"
15328 ["Up" outline-up-heading t]
15329 ["Next" outline-next-visible-heading t]
15330 ["Previous" outline-previous-visible-heading t]
15331 ["Next Same Level" outline-forward-same-level t]
15332 ["Previous Same Level" outline-backward-same-level t]
15333 "--"
15334 ["Jump" org-goto t])
15335 ("Edit Structure"
15336 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15337 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15338 "--"
15339 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15340 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15341 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15342 "--"
15343 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15344 "--"
15345 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15346 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15347 ["Demote Heading" org-metaright (not (org-at-table-p))]
15348 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15349 "--"
15350 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15351 "--"
15352 ["Convert to odd levels" org-convert-to-odd-levels t]
15353 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15354 ("Editing"
15355 ["Emphasis..." org-emphasize t]
15356 ["Edit Source Example" org-edit-special t]
15357 "--"
15358 ["Footnote new/jump" org-footnote-action t]
15359 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15360 ("Archive"
15361 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15362 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15363 ; :active t :keys "C-u C-c C-x C-a"]
15364 ["Sparse trees open ARCHIVE trees"
15365 (setq org-sparse-tree-open-archived-trees
15366 (not org-sparse-tree-open-archived-trees))
15367 :style toggle :selected org-sparse-tree-open-archived-trees]
15368 ["Cycling opens ARCHIVE trees"
15369 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15370 :style toggle :selected org-cycle-open-archived-trees]
15371 "--"
15372 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15373 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15374 ; ["Check and Move Children" (org-archive-subtree '(4))
15375 ; :active t :keys "C-u C-c C-x C-s"]
15377 "--"
15378 ("Hyperlinks"
15379 ["Store Link (Global)" org-store-link t]
15380 ["Find existing link to here" org-occur-link-in-agenda-files t]
15381 ["Insert Link" org-insert-link t]
15382 ["Follow Link" org-open-at-point t]
15383 "--"
15384 ["Next link" org-next-link t]
15385 ["Previous link" org-previous-link t]
15386 "--"
15387 ["Descriptive Links"
15388 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15389 :style radio
15390 :selected (member '(org-link) buffer-invisibility-spec)]
15391 ["Literal Links"
15392 (progn
15393 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15394 :style radio
15395 :selected (not (member '(org-link) buffer-invisibility-spec))])
15396 "--"
15397 ("TODO Lists"
15398 ["TODO/DONE/-" org-todo t]
15399 ("Select keyword"
15400 ["Next keyword" org-shiftright (org-on-heading-p)]
15401 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15402 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15403 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15404 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15405 ["Show TODO Tree" org-show-todo-tree t]
15406 ["Global TODO list" org-todo-list t]
15407 "--"
15408 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15409 :selected org-enforce-todo-dependencies :style toggle :active t]
15410 "Settings for tree at point"
15411 ["Do Children sequentially" org-toggle-ordered-property :style radio
15412 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15413 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15414 ["Do Children parallel" org-toggle-ordered-property :style radio
15415 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15416 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15417 "--"
15418 ["Set Priority" org-priority t]
15419 ["Priority Up" org-shiftup t]
15420 ["Priority Down" org-shiftdown t]
15421 "--"
15422 ["Get news from all feeds" org-feed-update-all t]
15423 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15424 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15425 ("TAGS and Properties"
15426 ["Set Tags" org-set-tags-command t]
15427 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15428 "--"
15429 ["Set property" org-set-property t]
15430 ["Column view of properties" org-columns t]
15431 ["Insert Column View DBlock" org-insert-columns-dblock t])
15432 ("Dates and Scheduling"
15433 ["Timestamp" org-time-stamp t]
15434 ["Timestamp (inactive)" org-time-stamp-inactive t]
15435 ("Change Date"
15436 ["1 Day Later" org-shiftright t]
15437 ["1 Day Earlier" org-shiftleft t]
15438 ["1 ... Later" org-shiftup t]
15439 ["1 ... Earlier" org-shiftdown t])
15440 ["Compute Time Range" org-evaluate-time-range t]
15441 ["Schedule Item" org-schedule t]
15442 ["Deadline" org-deadline t]
15443 "--"
15444 ["Custom time format" org-toggle-time-stamp-overlays
15445 :style radio :selected org-display-custom-times]
15446 "--"
15447 ["Goto Calendar" org-goto-calendar t]
15448 ["Date from Calendar" org-date-from-calendar t]
15449 "--"
15450 ["Start/Restart Timer" org-timer-start t]
15451 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15452 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15453 ["Insert Timer String" org-timer t]
15454 ["Insert Timer Item" org-timer-item t])
15455 ("Logging work"
15456 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15457 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15458 ["Clock out" org-clock-out t]
15459 ["Clock cancel" org-clock-cancel t]
15460 "--"
15461 ["Mark as default task" org-clock-mark-default-task t]
15462 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15463 ["Goto running clock" org-clock-goto t]
15464 "--"
15465 ["Display times" org-clock-display t]
15466 ["Create clock table" org-clock-report t]
15467 "--"
15468 ["Record DONE time"
15469 (progn (setq org-log-done (not org-log-done))
15470 (message "Switching to %s will %s record a timestamp"
15471 (car org-done-keywords)
15472 (if org-log-done "automatically" "not")))
15473 :style toggle :selected org-log-done])
15474 "--"
15475 ["Agenda Command..." org-agenda t]
15476 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15477 ("File List for Agenda")
15478 ("Special views current file"
15479 ["TODO Tree" org-show-todo-tree t]
15480 ["Check Deadlines" org-check-deadlines t]
15481 ["Timeline" org-timeline t]
15482 ["Tags/Property tree" org-match-sparse-tree t])
15483 "--"
15484 ["Export/Publish..." org-export t]
15485 ("LaTeX"
15486 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15487 :selected org-cdlatex-mode]
15488 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15489 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15490 ["Modify math symbol" org-cdlatex-math-modify
15491 (org-inside-LaTeX-fragment-p)]
15492 ["Insert citation" org-reftex-citation t]
15493 "--"
15494 ["Export LaTeX fragments as images"
15495 (if (featurep 'org-exp)
15496 (setq org-export-with-LaTeX-fragments
15497 (not org-export-with-LaTeX-fragments))
15498 (require 'org-exp))
15499 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15500 org-export-with-LaTeX-fragments)])
15501 "--"
15502 ("Documentation"
15503 ["Show Version" org-version t]
15504 ["Info Documentation" org-info t])
15505 ("Customize"
15506 ["Browse Org Group" org-customize t]
15507 "--"
15508 ["Expand This Menu" org-create-customize-menu
15509 (fboundp 'customize-menu-create)])
15510 ["Send bug report" org-submit-bug-report t]
15511 "--"
15512 ("Refresh/Reload"
15513 ["Refresh setup current buffer" org-mode-restart t]
15514 ["Reload Org (after update)" org-reload t]
15515 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15518 (defun org-info (&optional node)
15519 "Read documentation for Org-mode in the info system.
15520 With optional NODE, go directly to that node."
15521 (interactive)
15522 (info (format "(org)%s" (or node ""))))
15524 ;;;###autoload
15525 (defun org-submit-bug-report ()
15526 "Submit a bug report on Org-mode via mail.
15528 Don't hesitate to report any problems or inaccurate documentation.
15530 If you don't have setup sending mail from (X)Emacs, please copy the
15531 output buffer into your mail program, as it gives us important
15532 information about your Org-mode version and configuration."
15533 (interactive)
15534 (require 'reporter)
15535 (org-load-modules-maybe)
15536 (org-require-autoloaded-modules)
15537 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
15538 (reporter-submit-bug-report
15539 "emacs-orgmode@gnu.org"
15540 (org-version)
15541 (let (list)
15542 (save-window-excursion
15543 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
15544 (delete-other-windows)
15545 (erase-buffer)
15546 (insert "You are about to submit a bug report to the Org-mode mailing list.
15548 We would like to add your full Org-mode and Outline configuration to the
15549 bug report. This greatly simplifies the work of the maintainer and
15550 other experts on the mailing list.
15552 HOWEVER, some variables you have customized may contain private
15553 information. The names of customers, colleagues, or friends, might
15554 appear in the form of file names, tags, todo states, or search strings.
15555 If you answer yes to the prompt, you might want to check and remove
15556 such private information before sending the email.")
15557 (add-text-properties (point-min) (point-max) '(face org-warning))
15558 (when (yes-or-no-p "Include your Org-mode configuration ")
15559 (mapatoms
15560 (lambda (v)
15561 (and (boundp v)
15562 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
15563 (or (and (symbol-value v)
15564 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
15565 (and
15566 (get v 'custom-type) (get v 'standard-value)
15567 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
15568 (push v list)))))
15569 (kill-buffer (get-buffer "*Warn about privacy*"))
15570 list))
15571 nil nil
15572 "Remember to cover the basics, that is, what you expected to happen and
15573 what in fact did happen. You don't know how to make a good report? See
15575 http://orgmode.org/manual/Feedback.html#Feedback
15577 Your bug report will be posted to the Org-mode mailing list.
15578 ------------------------------------------------------------------------")))
15580 (defun org-install-agenda-files-menu ()
15581 (let ((bl (buffer-list)))
15582 (save-excursion
15583 (while bl
15584 (set-buffer (pop bl))
15585 (if (org-mode-p) (setq bl nil)))
15586 (when (org-mode-p)
15587 (easy-menu-change
15588 '("Org") "File List for Agenda"
15589 (append
15590 (list
15591 ["Edit File List" (org-edit-agenda-file-list) t]
15592 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15593 ["Remove Current File from List" org-remove-file t]
15594 ["Cycle through agenda files" org-cycle-agenda-files t]
15595 ["Occur in all agenda files" org-occur-in-agenda-files t]
15596 "--")
15597 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15599 ;;;; Documentation
15601 ;;;###autoload
15602 (defun org-require-autoloaded-modules ()
15603 (interactive)
15604 (mapc 'require
15605 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15606 org-docbook org-exp org-html org-icalendar
15607 org-id org-latex
15608 org-publish org-remember org-table
15609 org-timer org-xoxo)))
15611 ;;;###autoload
15612 (defun org-reload (&optional uncompiled)
15613 "Reload all org lisp files.
15614 With prefix arg UNCOMPILED, load the uncompiled versions."
15615 (interactive "P")
15616 (require 'find-func)
15617 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15618 (dir-org (file-name-directory (org-find-library-name "org")))
15619 (dir-org-contrib (ignore-errors
15620 (file-name-directory
15621 (org-find-library-name "org-contribdir"))))
15622 (files
15623 (append (directory-files dir-org t file-re)
15624 (and dir-org-contrib
15625 (directory-files dir-org-contrib t file-re))))
15626 (remove-re (concat (if (featurep 'xemacs)
15627 "org-colview" "org-colview-xemacs")
15628 "\\'")))
15629 (setq files (mapcar 'file-name-sans-extension files))
15630 (setq files (mapcar
15631 (lambda (x) (if (string-match remove-re x) nil x))
15632 files))
15633 (setq files (delq nil files))
15634 (mapc
15635 (lambda (f)
15636 (when (featurep (intern (file-name-nondirectory f)))
15637 (if (and (not uncompiled)
15638 (file-exists-p (concat f ".elc")))
15639 (load (concat f ".elc") nil nil t)
15640 (load (concat f ".el") nil nil t))))
15641 files))
15642 (org-version))
15644 ;;;###autoload
15645 (defun org-customize ()
15646 "Call the customize function with org as argument."
15647 (interactive)
15648 (org-load-modules-maybe)
15649 (org-require-autoloaded-modules)
15650 (customize-browse 'org))
15652 (defun org-create-customize-menu ()
15653 "Create a full customization menu for Org-mode, insert it into the menu."
15654 (interactive)
15655 (org-load-modules-maybe)
15656 (org-require-autoloaded-modules)
15657 (if (fboundp 'customize-menu-create)
15658 (progn
15659 (easy-menu-change
15660 '("Org") "Customize"
15661 `(["Browse Org group" org-customize t]
15662 "--"
15663 ,(customize-menu-create 'org)
15664 ["Set" Custom-set t]
15665 ["Save" Custom-save t]
15666 ["Reset to Current" Custom-reset-current t]
15667 ["Reset to Saved" Custom-reset-saved t]
15668 ["Reset to Standard Settings" Custom-reset-standard t]))
15669 (message "\"Org\"-menu now contains full customization menu"))
15670 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15672 ;;;; Miscellaneous stuff
15674 ;;; Generally useful functions
15676 (defun org-find-text-property-in-string (prop s)
15677 "Return the first non-nil value of property PROP in string S."
15678 (or (get-text-property 0 prop s)
15679 (get-text-property (or (next-single-property-change 0 prop s) 0)
15680 prop s)))
15682 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15683 "Display the given MESSAGE as a warning."
15684 (if (fboundp 'display-warning)
15685 (display-warning 'org message
15686 (if (featurep 'xemacs)
15687 'warning
15688 :warning))
15689 (let ((buf (get-buffer-create "*Org warnings*")))
15690 (with-current-buffer buf
15691 (goto-char (point-max))
15692 (insert "Warning (Org): " message)
15693 (unless (bolp)
15694 (newline)))
15695 (display-buffer buf)
15696 (sit-for 0))))
15698 (defun org-in-commented-line ()
15699 "Is point in a line starting with `#'?"
15700 (equal (char-after (point-at-bol)) ?#))
15702 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15703 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15704 (if (and marker (marker-buffer marker)
15705 (buffer-live-p (marker-buffer marker)))
15706 (progn
15707 (switch-to-buffer (marker-buffer marker))
15708 (if (or (> marker (point-max)) (< marker (point-min)))
15709 (widen))
15710 (goto-char marker)
15711 (org-show-context 'org-goto))
15712 (if bookmark
15713 (bookmark-jump bookmark)
15714 (error "Cannot find location"))))
15716 (defun org-quote-csv-field (s)
15717 "Quote field for inclusion in CSV material."
15718 (if (string-match "[\",]" s)
15719 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15722 (defun org-plist-delete (plist property)
15723 "Delete PROPERTY from PLIST.
15724 This is in contrast to merely setting it to 0."
15725 (let (p)
15726 (while plist
15727 (if (not (eq property (car plist)))
15728 (setq p (plist-put p (car plist) (nth 1 plist))))
15729 (setq plist (cddr plist)))
15732 (defun org-force-self-insert (N)
15733 "Needed to enforce self-insert under remapping."
15734 (interactive "p")
15735 (self-insert-command N))
15737 (defun org-string-width (s)
15738 "Compute width of string, ignoring invisible characters.
15739 This ignores character with invisibility property `org-link', and also
15740 characters with property `org-cwidth', because these will become invisible
15741 upon the next fontification round."
15742 (let (b l)
15743 (when (or (eq t buffer-invisibility-spec)
15744 (assq 'org-link buffer-invisibility-spec))
15745 (while (setq b (text-property-any 0 (length s)
15746 'invisible 'org-link s))
15747 (setq s (concat (substring s 0 b)
15748 (substring s (or (next-single-property-change
15749 b 'invisible s) (length s)))))))
15750 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15751 (setq s (concat (substring s 0 b)
15752 (substring s (or (next-single-property-change
15753 b 'org-cwidth s) (length s))))))
15754 (setq l (string-width s) b -1)
15755 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15756 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15759 (defun org-get-indentation (&optional line)
15760 "Get the indentation of the current line, interpreting tabs.
15761 When LINE is given, assume it represents a line and compute its indentation."
15762 (if line
15763 (if (string-match "^ *" (org-remove-tabs line))
15764 (match-end 0))
15765 (save-excursion
15766 (beginning-of-line 1)
15767 (skip-chars-forward " \t")
15768 (current-column))))
15770 (defun org-remove-tabs (s &optional width)
15771 "Replace tabulators in S with spaces.
15772 Assumes that s is a single line, starting in column 0."
15773 (setq width (or width tab-width))
15774 (while (string-match "\t" s)
15775 (setq s (replace-match
15776 (make-string
15777 (- (* width (/ (+ (match-beginning 0) width) width))
15778 (match-beginning 0)) ?\ )
15779 t t s)))
15782 (defun org-fix-indentation (line ind)
15783 "Fix indentation in LINE.
15784 IND is a cons cell with target and minimum indentation.
15785 If the current indentation in LINE is smaller than the minimum,
15786 leave it alone. If it is larger than ind, set it to the target."
15787 (let* ((l (org-remove-tabs line))
15788 (i (org-get-indentation l))
15789 (i1 (car ind)) (i2 (cdr ind)))
15790 (if (>= i i2) (setq l (substring line i2)))
15791 (if (> i1 0)
15792 (concat (make-string i1 ?\ ) l)
15793 l)))
15795 (defun org-remove-indentation (code &optional n)
15796 "Remove the maximum common indentation from the lines in CODE.
15797 N may optionally be the number of spaces to remove."
15798 (with-temp-buffer
15799 (insert code)
15800 (org-do-remove-indentation n)
15801 (buffer-string)))
15803 (defun org-do-remove-indentation (&optional n)
15804 "Remove the maximum common indentation from the buffer."
15805 (untabify (point-min) (point-max))
15806 (let ((min 10000) re)
15807 (if n
15808 (setq min n)
15809 (goto-char (point-min))
15810 (while (re-search-forward "^ *[^ \n]" nil t)
15811 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15812 (unless (or (= min 0) (= min 10000))
15813 (setq re (format "^ \\{%d\\}" min))
15814 (goto-char (point-min))
15815 (while (re-search-forward re nil t)
15816 (replace-match "")
15817 (end-of-line 1))
15818 min)))
15820 (defun org-base-buffer (buffer)
15821 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15822 (if (not buffer)
15823 buffer
15824 (or (buffer-base-buffer buffer)
15825 buffer)))
15827 (defun org-trim (s)
15828 "Remove whitespace at beginning and end of string."
15829 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15830 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15833 (defun org-wrap (string &optional width lines)
15834 "Wrap string to either a number of lines, or a width in characters.
15835 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15836 that costs. If there is a word longer than WIDTH, the text is actually
15837 wrapped to the length of that word.
15838 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15839 many lines, whatever width that takes.
15840 The return value is a list of lines, without newlines at the end."
15841 (let* ((words (org-split-string string "[ \t\n]+"))
15842 (maxword (apply 'max (mapcar 'org-string-width words)))
15843 w ll)
15844 (cond (width
15845 (org-do-wrap words (max maxword width)))
15846 (lines
15847 (setq w maxword)
15848 (setq ll (org-do-wrap words maxword))
15849 (if (<= (length ll) lines)
15851 (setq ll words)
15852 (while (> (length ll) lines)
15853 (setq w (1+ w))
15854 (setq ll (org-do-wrap words w)))
15855 ll))
15856 (t (error "Cannot wrap this")))))
15858 (defun org-do-wrap (words width)
15859 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15860 (let (lines line)
15861 (while words
15862 (setq line (pop words))
15863 (while (and words (< (+ (length line) (length (car words))) width))
15864 (setq line (concat line " " (pop words))))
15865 (setq lines (push line lines)))
15866 (nreverse lines)))
15868 (defun org-split-string (string &optional separators)
15869 "Splits STRING into substrings at SEPARATORS.
15870 No empty strings are returned if there are matches at the beginning
15871 and end of string."
15872 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15873 (start 0)
15874 notfirst
15875 (list nil))
15876 (while (and (string-match rexp string
15877 (if (and notfirst
15878 (= start (match-beginning 0))
15879 (< start (length string)))
15880 (1+ start) start))
15881 (< (match-beginning 0) (length string)))
15882 (setq notfirst t)
15883 (or (eq (match-beginning 0) 0)
15884 (and (eq (match-beginning 0) (match-end 0))
15885 (eq (match-beginning 0) start))
15886 (setq list
15887 (cons (substring string start (match-beginning 0))
15888 list)))
15889 (setq start (match-end 0)))
15890 (or (eq start (length string))
15891 (setq list
15892 (cons (substring string start)
15893 list)))
15894 (nreverse list)))
15896 (defun org-quote-vert (s)
15897 "Replace \"|\" with \"\\vert\"."
15898 (while (string-match "|" s)
15899 (setq s (replace-match "\\vert" t t s)))
15902 (defun org-uuidgen-p (s)
15903 "Is S an ID created by UUIDGEN?"
15904 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15906 (defun org-context ()
15907 "Return a list of contexts of the current cursor position.
15908 If several contexts apply, all are returned.
15909 Each context entry is a list with a symbol naming the context, and
15910 two positions indicating start and end of the context. Possible
15911 contexts are:
15913 :headline anywhere in a headline
15914 :headline-stars on the leading stars in a headline
15915 :todo-keyword on a TODO keyword (including DONE) in a headline
15916 :tags on the TAGS in a headline
15917 :priority on the priority cookie in a headline
15918 :item on the first line of a plain list item
15919 :item-bullet on the bullet/number of a plain list item
15920 :checkbox on the checkbox in a plain list item
15921 :table in an org-mode table
15922 :table-special on a special filed in a table
15923 :table-table in a table.el table
15924 :link on a hyperlink
15925 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15926 :target on a <<target>>
15927 :radio-target on a <<<radio-target>>>
15928 :latex-fragment on a LaTeX fragment
15929 :latex-preview on a LaTeX fragment with overlayed preview image
15931 This function expects the position to be visible because it uses font-lock
15932 faces as a help to recognize the following contexts: :table-special, :link,
15933 and :keyword."
15934 (let* ((f (get-text-property (point) 'face))
15935 (faces (if (listp f) f (list f)))
15936 (p (point)) clist o)
15937 ;; First the large context
15938 (cond
15939 ((org-on-heading-p t)
15940 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15941 (when (progn
15942 (beginning-of-line 1)
15943 (looking-at org-todo-line-tags-regexp))
15944 (push (org-point-in-group p 1 :headline-stars) clist)
15945 (push (org-point-in-group p 2 :todo-keyword) clist)
15946 (push (org-point-in-group p 4 :tags) clist))
15947 (goto-char p)
15948 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15949 (if (looking-at "\\[#[A-Z0-9]\\]")
15950 (push (org-point-in-group p 0 :priority) clist)))
15952 ((org-at-item-p)
15953 (push (org-point-in-group p 2 :item-bullet) clist)
15954 (push (list :item (point-at-bol)
15955 (save-excursion (org-end-of-item) (point)))
15956 clist)
15957 (and (org-at-item-checkbox-p)
15958 (push (org-point-in-group p 0 :checkbox) clist)))
15960 ((org-at-table-p)
15961 (push (list :table (org-table-begin) (org-table-end)) clist)
15962 (if (memq 'org-formula faces)
15963 (push (list :table-special
15964 (previous-single-property-change p 'face)
15965 (next-single-property-change p 'face)) clist)))
15966 ((org-at-table-p 'any)
15967 (push (list :table-table) clist)))
15968 (goto-char p)
15970 ;; Now the small context
15971 (cond
15972 ((org-at-timestamp-p)
15973 (push (org-point-in-group p 0 :timestamp) clist))
15974 ((memq 'org-link faces)
15975 (push (list :link
15976 (previous-single-property-change p 'face)
15977 (next-single-property-change p 'face)) clist))
15978 ((memq 'org-special-keyword faces)
15979 (push (list :keyword
15980 (previous-single-property-change p 'face)
15981 (next-single-property-change p 'face)) clist))
15982 ((org-on-target-p)
15983 (push (org-point-in-group p 0 :target) clist)
15984 (goto-char (1- (match-beginning 0)))
15985 (if (looking-at org-radio-target-regexp)
15986 (push (org-point-in-group p 0 :radio-target) clist))
15987 (goto-char p))
15988 ((setq o (car (delq nil
15989 (mapcar
15990 (lambda (x)
15991 (if (memq x org-latex-fragment-image-overlays) x))
15992 (org-overlays-at (point))))))
15993 (push (list :latex-fragment
15994 (org-overlay-start o) (org-overlay-end o)) clist)
15995 (push (list :latex-preview
15996 (org-overlay-start o) (org-overlay-end o)) clist))
15997 ((org-inside-LaTeX-fragment-p)
15998 ;; FIXME: positions wrong.
15999 (push (list :latex-fragment (point) (point)) clist)))
16001 (setq clist (nreverse (delq nil clist)))
16002 clist))
16004 ;; FIXME: Compare with at-regexp-p Do we need both?
16005 (defun org-in-regexp (re &optional nlines visually)
16006 "Check if point is inside a match of regexp.
16007 Normally only the current line is checked, but you can include NLINES extra
16008 lines both before and after point into the search.
16009 If VISUALLY is set, require that the cursor is not after the match but
16010 really on, so that the block visually is on the match."
16011 (catch 'exit
16012 (let ((pos (point))
16013 (eol (point-at-eol (+ 1 (or nlines 0))))
16014 (inc (if visually 1 0)))
16015 (save-excursion
16016 (beginning-of-line (- 1 (or nlines 0)))
16017 (while (re-search-forward re eol t)
16018 (if (and (<= (match-beginning 0) pos)
16019 (>= (+ inc (match-end 0)) pos))
16020 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16022 (defun org-at-regexp-p (regexp)
16023 "Is point inside a match of REGEXP in the current line?"
16024 (catch 'exit
16025 (save-excursion
16026 (let ((pos (point)) (end (point-at-eol)))
16027 (beginning-of-line 1)
16028 (while (re-search-forward regexp end t)
16029 (if (and (<= (match-beginning 0) pos)
16030 (>= (match-end 0) pos))
16031 (throw 'exit t)))
16032 nil))))
16034 (defun org-occur-in-agenda-files (regexp &optional nlines)
16035 "Call `multi-occur' with buffers for all agenda files."
16036 (interactive "sOrg-files matching: \np")
16037 (let* ((files (org-agenda-files))
16038 (tnames (mapcar 'file-truename files))
16039 (extra org-agenda-text-search-extra-files)
16041 (when (eq (car extra) 'agenda-archives)
16042 (setq extra (cdr extra))
16043 (setq files (org-add-archive-files files)))
16044 (while (setq f (pop extra))
16045 (unless (member (file-truename f) tnames)
16046 (add-to-list 'files f 'append)
16047 (add-to-list 'tnames (file-truename f) 'append)))
16048 (multi-occur
16049 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16050 regexp)))
16052 (if (boundp 'occur-mode-find-occurrence-hook)
16053 ;; Emacs 23
16054 (add-hook 'occur-mode-find-occurrence-hook
16055 (lambda ()
16056 (when (org-mode-p)
16057 (org-reveal))))
16058 ;; Emacs 22
16059 (defadvice occur-mode-goto-occurrence
16060 (after org-occur-reveal activate)
16061 (and (org-mode-p) (org-reveal)))
16062 (defadvice occur-mode-goto-occurrence-other-window
16063 (after org-occur-reveal activate)
16064 (and (org-mode-p) (org-reveal)))
16065 (defadvice occur-mode-display-occurrence
16066 (after org-occur-reveal activate)
16067 (when (org-mode-p)
16068 (let ((pos (occur-mode-find-occurrence)))
16069 (with-current-buffer (marker-buffer pos)
16070 (save-excursion
16071 (goto-char pos)
16072 (org-reveal)))))))
16074 (defun org-occur-link-in-agenda-files ()
16075 "Create a link and search for it in the agendas.
16076 The link is not stored in `org-stored-links', it is just created
16077 for the search purpose."
16078 (interactive)
16079 (let ((link (condition-case nil
16080 (org-store-link nil)
16081 (error "Unable to create a link to here"))))
16082 (org-occur-in-agenda-files (regexp-quote link))))
16084 (defun org-uniquify (list)
16085 "Remove duplicate elements from LIST."
16086 (let (res)
16087 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16088 res))
16090 (defun org-delete-all (elts list)
16091 "Remove all elements in ELTS from LIST."
16092 (while elts
16093 (setq list (delete (pop elts) list)))
16094 list)
16096 (defun org-back-over-empty-lines ()
16097 "Move backwards over whitespace, to the beginning of the first empty line.
16098 Returns the number of empty lines passed."
16099 (let ((pos (point)))
16100 (skip-chars-backward " \t\n\r")
16101 (beginning-of-line 2)
16102 (goto-char (min (point) pos))
16103 (count-lines (point) pos)))
16105 (defun org-skip-whitespace ()
16106 (skip-chars-forward " \t\n\r"))
16108 (defun org-point-in-group (point group &optional context)
16109 "Check if POINT is in match-group GROUP.
16110 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16111 match. If the match group does ot exist or point is not inside it,
16112 return nil."
16113 (and (match-beginning group)
16114 (>= point (match-beginning group))
16115 (<= point (match-end group))
16116 (if context
16117 (list context (match-beginning group) (match-end group))
16118 t)))
16120 (defun org-switch-to-buffer-other-window (&rest args)
16121 "Switch to buffer in a second window on the current frame.
16122 In particular, do not allow pop-up frames."
16123 (let (pop-up-frames special-display-buffer-names special-display-regexps
16124 special-display-function)
16125 (apply 'switch-to-buffer-other-window args)))
16127 (defun org-combine-plists (&rest plists)
16128 "Create a single property list from all plists in PLISTS.
16129 The process starts by copying the first list, and then setting properties
16130 from the other lists. Settings in the last list are the most significant
16131 ones and overrule settings in the other lists."
16132 (let ((rtn (copy-sequence (pop plists)))
16133 p v ls)
16134 (while plists
16135 (setq ls (pop plists))
16136 (while ls
16137 (setq p (pop ls) v (pop ls))
16138 (setq rtn (plist-put rtn p v))))
16139 rtn))
16141 (defun org-move-line-down (arg)
16142 "Move the current line down. With prefix argument, move it past ARG lines."
16143 (interactive "p")
16144 (let ((col (current-column))
16145 beg end pos)
16146 (beginning-of-line 1) (setq beg (point))
16147 (beginning-of-line 2) (setq end (point))
16148 (beginning-of-line (+ 1 arg))
16149 (setq pos (move-marker (make-marker) (point)))
16150 (insert (delete-and-extract-region beg end))
16151 (goto-char pos)
16152 (org-move-to-column col)))
16154 (defun org-move-line-up (arg)
16155 "Move the current line up. With prefix argument, move it past ARG lines."
16156 (interactive "p")
16157 (let ((col (current-column))
16158 beg end pos)
16159 (beginning-of-line 1) (setq beg (point))
16160 (beginning-of-line 2) (setq end (point))
16161 (beginning-of-line (- arg))
16162 (setq pos (move-marker (make-marker) (point)))
16163 (insert (delete-and-extract-region beg end))
16164 (goto-char pos)
16165 (org-move-to-column col)))
16167 (defun org-replace-escapes (string table)
16168 "Replace %-escapes in STRING with values in TABLE.
16169 TABLE is an association list with keys like \"%a\" and string values.
16170 The sequences in STRING may contain normal field width and padding information,
16171 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16172 so values can contain further %-escapes if they are define later in TABLE."
16173 (let ((case-fold-search nil)
16174 e re rpl)
16175 (while (setq e (pop table))
16176 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16177 (while (string-match re string)
16178 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16179 (cdr e)))
16180 (setq string (replace-match rpl t t string))))
16181 string))
16184 (defun org-sublist (list start end)
16185 "Return a section of LIST, from START to END.
16186 Counting starts at 1."
16187 (let (rtn (c start))
16188 (setq list (nthcdr (1- start) list))
16189 (while (and list (<= c end))
16190 (push (pop list) rtn)
16191 (setq c (1+ c)))
16192 (nreverse rtn)))
16194 (defun org-find-base-buffer-visiting (file)
16195 "Like `find-buffer-visiting' but always return the base buffer and
16196 not an indirect buffer."
16197 (let ((buf (or (get-file-buffer file)
16198 (find-buffer-visiting file))))
16199 (if buf
16200 (or (buffer-base-buffer buf) buf)
16201 nil)))
16203 (defun org-image-file-name-regexp (&optional extensions)
16204 "Return regexp matching the file names of images.
16205 If EXTENSIONS is given, only match these."
16206 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16207 (image-file-name-regexp)
16208 (let ((image-file-name-extensions
16209 (or extensions
16210 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16211 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16212 (concat "\\."
16213 (regexp-opt (nconc (mapcar 'upcase
16214 image-file-name-extensions)
16215 image-file-name-extensions)
16217 "\\'"))))
16219 (defun org-file-image-p (file &optional extensions)
16220 "Return non-nil if FILE is an image."
16221 (save-match-data
16222 (string-match (org-image-file-name-regexp extensions) file)))
16224 (defun org-get-cursor-date ()
16225 "Return the date at cursor in as a time.
16226 This works in the calendar and in the agenda, anywhere else it just
16227 returns the current time."
16228 (let (date day defd)
16229 (cond
16230 ((eq major-mode 'calendar-mode)
16231 (setq date (calendar-cursor-to-date)
16232 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16233 ((eq major-mode 'org-agenda-mode)
16234 (setq day (get-text-property (point) 'day))
16235 (if day
16236 (setq date (calendar-gregorian-from-absolute day)
16237 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16238 (nth 2 date))))))
16239 (or defd (current-time))))
16241 (defvar org-agenda-action-marker (make-marker)
16242 "Marker pointing to the entry for the next agenda action.")
16244 (defun org-mark-entry-for-agenda-action ()
16245 "Mark the current entry as target of an agenda action.
16246 Agenda actions are actions executed from the agenda with the key `k',
16247 which make use of the date at the cursor."
16248 (interactive)
16249 (move-marker org-agenda-action-marker
16250 (save-excursion (org-back-to-heading t) (point))
16251 (current-buffer))
16252 (message
16253 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16255 ;;; Paragraph filling stuff.
16256 ;; We want this to be just right, so use the full arsenal.
16258 (defun org-indent-line-function ()
16259 "Indent line like previous, but further if previous was headline or item."
16260 (interactive)
16261 (let* ((pos (point))
16262 (itemp (org-at-item-p))
16263 (case-fold-search t)
16264 (org-drawer-regexp (or org-drawer-regexp "\000"))
16265 column bpos bcol tpos tcol bullet btype bullet-type)
16266 ;; Find the previous relevant line
16267 (beginning-of-line 1)
16268 (cond
16269 ((looking-at "#") (setq column 0))
16270 ((looking-at "\\*+ ") (setq column 0))
16271 ((and (looking-at "[ \t]*:END:")
16272 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16273 (save-excursion
16274 (goto-char (1- (match-beginning 1)))
16275 (setq column (current-column))))
16276 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16277 (save-excursion
16278 (re-search-backward
16279 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16280 (setq column (org-get-indentation (match-string 0))))
16282 (beginning-of-line 0)
16283 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16284 (not (looking-at "[ \t]*:END:"))
16285 (not (looking-at org-drawer-regexp)))
16286 (beginning-of-line 0))
16287 (cond
16288 ((looking-at "\\*+[ \t]+")
16289 (if (not org-adapt-indentation)
16290 (setq column 0)
16291 (goto-char (match-end 0))
16292 (setq column (current-column))))
16293 ((looking-at org-drawer-regexp)
16294 (goto-char (1- (match-beginning 1)))
16295 (setq column (current-column)))
16296 ((looking-at "\\([ \t]*\\):END:")
16297 (goto-char (match-end 1))
16298 (setq column (current-column)))
16299 ((org-in-item-p)
16300 (org-beginning-of-item)
16301 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16302 (setq bpos (match-beginning 1) tpos (match-end 0)
16303 bcol (progn (goto-char bpos) (current-column))
16304 tcol (progn (goto-char tpos) (current-column))
16305 bullet (match-string 1)
16306 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16307 (if (> tcol (+ bcol org-description-max-indent))
16308 (setq tcol (+ bcol 5)))
16309 (if (not itemp)
16310 (setq column tcol)
16311 (goto-char pos)
16312 (beginning-of-line 1)
16313 (if (looking-at "\\S-")
16314 (progn
16315 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16316 (setq bullet (match-string 1)
16317 btype (if (string-match "[0-9]" bullet) "n" bullet))
16318 (setq column (if (equal btype bullet-type) bcol tcol)))
16319 (setq column (org-get-indentation)))))
16320 (t (setq column (org-get-indentation))))))
16321 (goto-char pos)
16322 (if (<= (current-column) (current-indentation))
16323 (org-indent-line-to column)
16324 (save-excursion (org-indent-line-to column)))
16325 (setq column (current-column))
16326 (beginning-of-line 1)
16327 (if (looking-at
16328 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16329 (replace-match (concat "\\1" (format org-property-format
16330 (match-string 2) (match-string 3)))
16331 t nil))
16332 (org-move-to-column column)))
16334 (defun org-set-autofill-regexps ()
16335 (interactive)
16336 ;; In the paragraph separator we include headlines, because filling
16337 ;; text in a line directly attached to a headline would otherwise
16338 ;; fill the headline as well.
16339 (org-set-local 'comment-start-skip "^#+[ \t]*")
16340 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16341 ;; The paragraph starter includes hand-formatted lists.
16342 (org-set-local
16343 'paragraph-start
16344 (concat
16345 "\f" "\\|"
16346 "[ ]*$" "\\|"
16347 "\\*+ " "\\|"
16348 "[ \t]*#" "\\|"
16349 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16350 "[ \t]*[:|]" "\\|"
16351 "\\$\\$" "\\|"
16352 "\\\\\\(begin\\|end\\|[][]\\)"))
16353 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16354 ;; But only if the user has not turned off tables or fixed-width regions
16355 (org-set-local
16356 'auto-fill-inhibit-regexp
16357 (concat "\\*+ \\|#\\+"
16358 "\\|[ \t]*" org-keyword-time-regexp
16359 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16360 (concat
16361 "\\|[ \t]*["
16362 (if org-enable-table-editor "|" "")
16363 (if org-enable-fixed-width-editor ":" "")
16364 "]"))))
16365 ;; We use our own fill-paragraph function, to make sure that tables
16366 ;; and fixed-width regions are not wrapped. That function will pass
16367 ;; through to `fill-paragraph' when appropriate.
16368 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16369 ; Adaptive filling: To get full control, first make sure that
16370 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16371 (org-set-local 'adaptive-fill-regexp "\000")
16372 (org-set-local 'adaptive-fill-function
16373 'org-adaptive-fill-function)
16374 (org-set-local
16375 'align-mode-rules-list
16376 '((org-in-buffer-settings
16377 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16378 (modes . '(org-mode))))))
16380 (defun org-fill-paragraph (&optional justify)
16381 "Re-align a table, pass through to fill-paragraph if no table."
16382 (let ((table-p (org-at-table-p))
16383 (table.el-p (org-at-table.el-p)))
16384 (cond ((and (equal (char-after (point-at-bol)) ?*)
16385 (save-excursion (goto-char (point-at-bol))
16386 (looking-at outline-regexp)))
16387 t) ; skip headlines
16388 (table.el-p t) ; skip table.el tables
16389 (table-p (org-table-align) t) ; align org-mode tables
16390 (t nil)))) ; call paragraph-fill
16392 ;; For reference, this is the default value of adaptive-fill-regexp
16393 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16395 (defun org-adaptive-fill-function ()
16396 "Return a fill prefix for org-mode files.
16397 In particular, this makes sure hanging paragraphs for hand-formatted lists
16398 work correctly."
16399 (cond ((looking-at "#[ \t]+")
16400 (match-string 0))
16401 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16402 (save-excursion
16403 (if (> (match-end 1) (+ (match-beginning 1)
16404 org-description-max-indent))
16405 (goto-char (+ (match-beginning 1) 5))
16406 (goto-char (match-end 0)))
16407 (make-string (current-column) ?\ )))
16408 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16409 (save-excursion
16410 (goto-char (match-end 0))
16411 (make-string (current-column) ?\ )))
16412 (t nil)))
16414 ;;; Other stuff.
16416 (defun org-toggle-fixed-width-section (arg)
16417 "Toggle the fixed-width export.
16418 If there is no active region, the QUOTE keyword at the current headline is
16419 inserted or removed. When present, it causes the text between this headline
16420 and the next to be exported as fixed-width text, and unmodified.
16421 If there is an active region, this command adds or removes a colon as the
16422 first character of this line. If the first character of a line is a colon,
16423 this line is also exported in fixed-width font."
16424 (interactive "P")
16425 (let* ((cc 0)
16426 (regionp (org-region-active-p))
16427 (beg (if regionp (region-beginning) (point)))
16428 (end (if regionp (region-end)))
16429 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16430 (case-fold-search nil)
16431 (re "[ \t]*\\(: \\)")
16432 off)
16433 (if regionp
16434 (save-excursion
16435 (goto-char beg)
16436 (setq cc (current-column))
16437 (beginning-of-line 1)
16438 (setq off (looking-at re))
16439 (while (> nlines 0)
16440 (setq nlines (1- nlines))
16441 (beginning-of-line 1)
16442 (cond
16443 (arg
16444 (org-move-to-column cc t)
16445 (insert ": \n")
16446 (forward-line -1))
16447 ((and off (looking-at re))
16448 (replace-match "" t t nil 1))
16449 ((not off) (org-move-to-column cc t) (insert ": ")))
16450 (forward-line 1)))
16451 (save-excursion
16452 (org-back-to-heading)
16453 (if (looking-at (concat outline-regexp
16454 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16455 (replace-match "" t t nil 1)
16456 (if (looking-at outline-regexp)
16457 (progn
16458 (goto-char (match-end 0))
16459 (insert org-quote-string " "))))))))
16461 (defun org-reftex-citation ()
16462 "Use reftex-citation to insert a citation into the buffer.
16463 This looks for a line like
16465 #+BIBLIOGRAPHY: foo plain option:-d
16467 and derives from it that foo.bib is the bbliography file relevant
16468 for this document. It then installs the necessary environment for RefTeX
16469 to work in this buffer and calls `reftex-citation' to insert a citation
16470 into the buffer.
16472 Export of such citations to both LaTeX and HTML is handled by the contributed
16473 package org-exp-bibtex by Taru Karttunen."
16474 (interactive)
16475 (let ((reftex-docstruct-symbol 'rds)
16476 (reftex-cite-format "\\cite{%l}")
16477 rds bib)
16478 (save-excursion
16479 (save-restriction
16480 (widen)
16481 (let ((case-fold-search t)
16482 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16483 (if (not (save-excursion
16484 (or (re-search-forward re nil t)
16485 (re-search-backward re nil t))))
16486 (error "No bibliography defined in file")
16487 (setq bib (concat (match-string 1) ".bib")
16488 rds (list (list 'bib bib)))))))
16489 (call-interactively 'reftex-citation)))
16491 ;;;; Functions extending outline functionality
16493 (defun org-beginning-of-line (&optional arg)
16494 "Go to the beginning of the current line. If that is invisible, continue
16495 to a visible line beginning. This makes the function of C-a more intuitive.
16496 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16497 first attempt, and only move to after the tags when the cursor is already
16498 beyond the end of the headline."
16499 (interactive "P")
16500 (let ((pos (point))
16501 (special (if (consp org-special-ctrl-a/e)
16502 (car org-special-ctrl-a/e)
16503 org-special-ctrl-a/e))
16504 refpos)
16505 (if (org-bound-and-true-p line-move-visual)
16506 (beginning-of-visual-line 1)
16507 (beginning-of-line 1))
16508 (if (and arg (fboundp 'move-beginning-of-line))
16509 (call-interactively 'move-beginning-of-line)
16510 (if (bobp)
16512 (backward-char 1)
16513 (if (org-invisible-p)
16514 (while (and (not (bobp)) (org-invisible-p))
16515 (backward-char 1)
16516 (beginning-of-line 1))
16517 (forward-char 1))))
16518 (when special
16519 (cond
16520 ((and (looking-at org-complex-heading-regexp)
16521 (= (char-after (match-end 1)) ?\ ))
16522 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16523 (point-at-eol)))
16524 (goto-char
16525 (if (eq special t)
16526 (cond ((> pos refpos) refpos)
16527 ((= pos (point)) refpos)
16528 (t (point)))
16529 (cond ((> pos (point)) (point))
16530 ((not (eq last-command this-command)) (point))
16531 (t refpos)))))
16532 ((org-at-item-p)
16533 (goto-char
16534 (if (eq special t)
16535 (cond ((> pos (match-end 4)) (match-end 4))
16536 ((= pos (point)) (match-end 4))
16537 (t (point)))
16538 (cond ((> pos (point)) (point))
16539 ((not (eq last-command this-command)) (point))
16540 (t (match-end 4))))))))
16541 (org-no-warnings
16542 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16544 (defun org-end-of-line (&optional arg)
16545 "Go to the end of the line.
16546 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16547 first attempt, and only move to after the tags when the cursor is already
16548 beyond the end of the headline."
16549 (interactive "P")
16550 (let ((special (if (consp org-special-ctrl-a/e)
16551 (cdr org-special-ctrl-a/e)
16552 org-special-ctrl-a/e)))
16553 (if (or (not special)
16554 (not (org-on-heading-p))
16555 arg)
16556 (call-interactively
16557 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16558 ((fboundp 'move-end-of-line) 'move-end-of-line)
16559 (t 'end-of-line)))
16560 (let ((pos (point)))
16561 (beginning-of-line 1)
16562 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16563 (if (eq special t)
16564 (if (or (< pos (match-beginning 1))
16565 (= pos (match-end 0)))
16566 (goto-char (match-beginning 1))
16567 (goto-char (match-end 0)))
16568 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16569 (goto-char (match-end 0))
16570 (goto-char (match-beginning 1))))
16571 (call-interactively (if (fboundp 'move-end-of-line)
16572 'move-end-of-line
16573 'end-of-line)))))
16574 (org-no-warnings
16575 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16577 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16578 (define-key org-mode-map "\C-e" 'org-end-of-line)
16580 (defun org-backward-sentence (&optional arg)
16581 "Go to beginning of sentence, or beginning of table field.
16582 This will call `backward-sentence' or `org-table-beginning-of-field',
16583 depending on context."
16584 (interactive "P")
16585 (cond
16586 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16587 (t (call-interactively 'backward-sentence))))
16589 (defun org-forward-sentence (&optional arg)
16590 "Go to end of sentence, or end of table field.
16591 This will call `forward-sentence' or `org-table-end-of-field',
16592 depending on context."
16593 (interactive "P")
16594 (cond
16595 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16596 (t (call-interactively 'forward-sentence))))
16598 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16599 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16601 (defun org-kill-line (&optional arg)
16602 "Kill line, to tags or end of line."
16603 (interactive "P")
16604 (cond
16605 ((or (not org-special-ctrl-k)
16606 (bolp)
16607 (not (org-on-heading-p)))
16608 (call-interactively 'kill-line))
16609 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16610 (kill-region (point) (match-beginning 1))
16611 (org-set-tags nil t))
16612 (t (kill-region (point) (point-at-eol)))))
16614 (define-key org-mode-map "\C-k" 'org-kill-line)
16616 (defun org-yank (&optional arg)
16617 "Yank. If the kill is a subtree, treat it specially.
16618 This command will look at the current kill and check if is a single
16619 subtree, or a series of subtrees[1]. If it passes the test, and if the
16620 cursor is at the beginning of a line or after the stars of a currently
16621 empty headline, then the yank is handled specially. How exactly depends
16622 on the value of the following variables, both set by default.
16624 org-yank-folded-subtrees
16625 When set, the subtree(s) will be folded after insertion, but only
16626 if doing so would now swallow text after the yanked text.
16628 org-yank-adjusted-subtrees
16629 When set, the subtree will be promoted or demoted in order to
16630 fit into the local outline tree structure, which means that the level
16631 will be adjusted so that it becomes the smaller one of the two
16632 *visible* surrounding headings.
16634 Any prefix to this command will cause `yank' to be called directly with
16635 no special treatment. In particular, a simple `C-u' prefix will just
16636 plainly yank the text as it is.
16638 \[1] The test checks if the first non-white line is a heading
16639 and if there are no other headings with fewer stars."
16640 (interactive "P")
16641 (org-yank-generic 'yank arg))
16643 (defun org-yank-generic (command arg)
16644 "Perform some yank-like command.
16646 This function implements the behavior described in the `org-yank'
16647 documentation. However, it has been generalized to work for any
16648 interactive command with similar behavior."
16650 ;; pretend to be command COMMAND
16651 (setq this-command command)
16653 (if arg
16654 (call-interactively command)
16656 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16657 (and (org-kill-is-subtree-p)
16658 (or (bolp)
16659 (and (looking-at "[ \t]*$")
16660 (string-match
16661 "\\`\\*+\\'"
16662 (buffer-substring (point-at-bol) (point)))))))
16663 swallowp)
16664 (cond
16665 ((and subtreep org-yank-folded-subtrees)
16666 (let ((beg (point))
16667 end)
16668 (if (and subtreep org-yank-adjusted-subtrees)
16669 (org-paste-subtree nil nil 'for-yank)
16670 (call-interactively command))
16672 (setq end (point))
16673 (goto-char beg)
16674 (when (and (bolp) subtreep
16675 (not (setq swallowp
16676 (org-yank-folding-would-swallow-text beg end))))
16677 (or (looking-at outline-regexp)
16678 (re-search-forward (concat "^" outline-regexp) end t))
16679 (while (and (< (point) end) (looking-at outline-regexp))
16680 (hide-subtree)
16681 (org-cycle-show-empty-lines 'folded)
16682 (condition-case nil
16683 (outline-forward-same-level 1)
16684 (error (goto-char end)))))
16685 (when swallowp
16686 (message
16687 "Inserted text not folded because that would swallow text"))
16689 (goto-char end)
16690 (skip-chars-forward " \t\n\r")
16691 (beginning-of-line 1)
16692 (push-mark beg 'nomsg)))
16693 ((and subtreep org-yank-adjusted-subtrees)
16694 (let ((beg (point-at-bol)))
16695 (org-paste-subtree nil nil 'for-yank)
16696 (push-mark beg 'nomsg)))
16698 (call-interactively command))))))
16700 (defun org-yank-folding-would-swallow-text (beg end)
16701 "Would hide-subtree at BEG swallow any text after END?"
16702 (let (level)
16703 (save-excursion
16704 (goto-char beg)
16705 (when (or (looking-at outline-regexp)
16706 (re-search-forward (concat "^" outline-regexp) end t))
16707 (setq level (org-outline-level)))
16708 (goto-char end)
16709 (skip-chars-forward " \t\r\n\v\f")
16710 (if (or (eobp)
16711 (and (bolp) (looking-at org-outline-regexp)
16712 (<= (org-outline-level) level)))
16713 nil ; Nothing would be swallowed
16714 t)))) ; something would swallow
16716 (define-key org-mode-map "\C-y" 'org-yank)
16718 (defun org-invisible-p ()
16719 "Check if point is at a character currently not visible."
16720 ;; Early versions of noutline don't have `outline-invisible-p'.
16721 (if (fboundp 'outline-invisible-p)
16722 (outline-invisible-p)
16723 (get-char-property (point) 'invisible)))
16725 (defun org-invisible-p2 ()
16726 "Check if point is at a character currently not visible."
16727 (save-excursion
16728 (if (and (eolp) (not (bobp))) (backward-char 1))
16729 ;; Early versions of noutline don't have `outline-invisible-p'.
16730 (if (fboundp 'outline-invisible-p)
16731 (outline-invisible-p)
16732 (get-char-property (point) 'invisible))))
16734 (defun org-back-to-heading (&optional invisible-ok)
16735 "Call `outline-back-to-heading', but provide a better error message."
16736 (condition-case nil
16737 (outline-back-to-heading invisible-ok)
16738 (error (error "Before first headline at position %d in buffer %s"
16739 (point) (current-buffer)))))
16741 (defun org-before-first-heading-p ()
16742 "Before first heading?"
16743 (save-excursion
16744 (null (re-search-backward "^\\*+ " nil t))))
16746 (defalias 'org-on-heading-p 'outline-on-heading-p)
16747 (defalias 'org-at-heading-p 'outline-on-heading-p)
16748 (defun org-at-heading-or-item-p ()
16749 (or (org-on-heading-p) (org-at-item-p)))
16751 (defun org-on-target-p ()
16752 (or (org-in-regexp org-radio-target-regexp)
16753 (org-in-regexp org-target-regexp)))
16755 (defun org-up-heading-all (arg)
16756 "Move to the heading line of which the present line is a subheading.
16757 This function considers both visible and invisible heading lines.
16758 With argument, move up ARG levels."
16759 (if (fboundp 'outline-up-heading-all)
16760 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16761 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16763 (defun org-up-heading-safe ()
16764 "Move to the heading line of which the present line is a subheading.
16765 This version will not throw an error. It will return the level of the
16766 headline found, or nil if no higher level is found.
16768 Also, this function will be a lot faster than `outline-up-heading',
16769 because it relies on stars being the outline starters. This can really
16770 make a significant difference in outlines with very many siblings."
16771 (let (start-level re)
16772 (org-back-to-heading t)
16773 (setq start-level (funcall outline-level))
16774 (if (equal start-level 1)
16776 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16777 (if (re-search-backward re nil t)
16778 (funcall outline-level)))))
16780 (defun org-first-sibling-p ()
16781 "Is this heading the first child of its parents?"
16782 (interactive)
16783 (let ((re (concat "^" outline-regexp))
16784 level l)
16785 (unless (org-at-heading-p t)
16786 (error "Not at a heading"))
16787 (setq level (funcall outline-level))
16788 (save-excursion
16789 (if (not (re-search-backward re nil t))
16791 (setq l (funcall outline-level))
16792 (< l level)))))
16794 (defun org-goto-sibling (&optional previous)
16795 "Goto the next sibling, even if it is invisible.
16796 When PREVIOUS is set, go to the previous sibling instead. Returns t
16797 when a sibling was found. When none is found, return nil and don't
16798 move point."
16799 (let ((fun (if previous 're-search-backward 're-search-forward))
16800 (pos (point))
16801 (re (concat "^" outline-regexp))
16802 level l)
16803 (when (condition-case nil (org-back-to-heading t) (error nil))
16804 (setq level (funcall outline-level))
16805 (catch 'exit
16806 (or previous (forward-char 1))
16807 (while (funcall fun re nil t)
16808 (setq l (funcall outline-level))
16809 (when (< l level) (goto-char pos) (throw 'exit nil))
16810 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16811 (goto-char pos)
16812 nil))))
16814 (defun org-show-siblings ()
16815 "Show all siblings of the current headline."
16816 (save-excursion
16817 (while (org-goto-sibling) (org-flag-heading nil)))
16818 (save-excursion
16819 (while (org-goto-sibling 'previous)
16820 (org-flag-heading nil))))
16822 (defun org-show-hidden-entry ()
16823 "Show an entry where even the heading is hidden."
16824 (save-excursion
16825 (org-show-entry)))
16827 (defun org-flag-heading (flag &optional entry)
16828 "Flag the current heading. FLAG non-nil means make invisible.
16829 When ENTRY is non-nil, show the entire entry."
16830 (save-excursion
16831 (org-back-to-heading t)
16832 ;; Check if we should show the entire entry
16833 (if entry
16834 (progn
16835 (org-show-entry)
16836 (save-excursion
16837 (and (outline-next-heading)
16838 (org-flag-heading nil))))
16839 (outline-flag-region (max (point-min) (1- (point)))
16840 (save-excursion (outline-end-of-heading) (point))
16841 flag))))
16843 (defun org-get-next-sibling ()
16844 "Move to next heading of the same level, and return point.
16845 If there is no such heading, return nil.
16846 This is like outline-next-sibling, but invisible headings are ok."
16847 (let ((level (funcall outline-level)))
16848 (outline-next-heading)
16849 (while (and (not (eobp)) (> (funcall outline-level) level))
16850 (outline-next-heading))
16851 (if (or (eobp) (< (funcall outline-level) level))
16853 (point))))
16855 (defun org-get-last-sibling ()
16856 "Move to previous heading of the same level, and return point.
16857 If there is no such heading, return nil."
16858 (let ((opoint (point))
16859 (level (funcall outline-level)))
16860 (outline-previous-heading)
16861 (when (and (/= (point) opoint) (outline-on-heading-p t))
16862 (while (and (> (funcall outline-level) level)
16863 (not (bobp)))
16864 (outline-previous-heading))
16865 (if (< (funcall outline-level) level)
16867 (point)))))
16869 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16870 ;; This contains an exact copy of the original function, but it uses
16871 ;; `org-back-to-heading', to make it work also in invisible
16872 ;; trees. And is uses an invisible-OK argument.
16873 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16874 ;; Furthermore, when used inside Org, finding the end of a large subtree
16875 ;; with many children and grandchildren etc, this can be much faster
16876 ;; than the outline version.
16877 (org-back-to-heading invisible-OK)
16878 (let ((first t)
16879 (level (funcall outline-level)))
16880 (if (and (org-mode-p) (< level 1000))
16881 ;; A true heading (not a plain list item), in Org-mode
16882 ;; This means we can easily find the end by looking
16883 ;; only for the right number of stars. Using a regexp to do
16884 ;; this is so much faster than using a Lisp loop.
16885 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16886 (forward-char 1)
16887 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16888 ;; something else, do it the slow way
16889 (while (and (not (eobp))
16890 (or first (> (funcall outline-level) level)))
16891 (setq first nil)
16892 (outline-next-heading)))
16893 (unless to-heading
16894 (if (memq (preceding-char) '(?\n ?\^M))
16895 (progn
16896 ;; Go to end of line before heading
16897 (forward-char -1)
16898 (if (memq (preceding-char) '(?\n ?\^M))
16899 ;; leave blank line before heading
16900 (forward-char -1))))))
16901 (point))
16903 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16904 "Use Org version in org-mode, for dramatic speed-up."
16905 (if (eq major-mode 'org-mode)
16906 (progn
16907 (org-end-of-subtree nil t)
16908 (unless (eobp) (backward-char 1)))
16909 ad-do-it))
16911 (defun org-forward-same-level (arg &optional invisible-ok)
16912 "Move forward to the arg'th subheading at same level as this one.
16913 Stop at the first and last subheadings of a superior heading."
16914 (interactive "p")
16915 (org-back-to-heading invisible-ok)
16916 (org-on-heading-p)
16917 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16918 (re (format "^\\*\\{1,%d\\} " level))
16920 (forward-char 1)
16921 (while (> arg 0)
16922 (while (and (re-search-forward re nil 'move)
16923 (setq l (- (match-end 0) (match-beginning 0) 1))
16924 (= l level)
16925 (not invisible-ok)
16926 (org-invisible-p))
16927 (if (< l level) (setq arg 1)))
16928 (setq arg (1- arg)))
16929 (beginning-of-line 1)))
16931 (defun org-backward-same-level (arg &optional invisible-ok)
16932 "Move backward to the arg'th subheading at same level as this one.
16933 Stop at the first and last subheadings of a superior heading."
16934 (interactive "p")
16935 (org-back-to-heading)
16936 (org-on-heading-p)
16937 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16938 (re (format "^\\*\\{1,%d\\} " level))
16940 (while (> arg 0)
16941 (while (and (re-search-backward re nil 'move)
16942 (setq l (- (match-end 0) (match-beginning 0) 1))
16943 (= l level)
16944 (not invisible-ok)
16945 (org-invisible-p))
16946 (if (< l level) (setq arg 1)))
16947 (setq arg (1- arg)))))
16949 (defun org-show-subtree ()
16950 "Show everything after this heading at deeper levels."
16951 (outline-flag-region
16952 (point)
16953 (save-excursion
16954 (org-end-of-subtree t t))
16955 nil))
16957 (defun org-show-entry ()
16958 "Show the body directly following this heading.
16959 Show the heading too, if it is currently invisible."
16960 (interactive)
16961 (save-excursion
16962 (condition-case nil
16963 (progn
16964 (org-back-to-heading t)
16965 (outline-flag-region
16966 (max (point-min) (1- (point)))
16967 (save-excursion
16968 (if (re-search-forward
16969 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16970 (match-beginning 1)
16971 (point-max)))
16972 nil)
16973 (org-cycle-hide-drawers 'children))
16974 (error nil))))
16976 (defun org-make-options-regexp (kwds &optional extra)
16977 "Make a regular expression for keyword lines."
16978 (concat
16980 "#?[ \t]*\\+\\("
16981 (mapconcat 'regexp-quote kwds "\\|")
16982 (if extra (concat "\\|" extra))
16983 "\\):[ \t]*"
16984 "\\(.*\\)"))
16986 ;; Make isearch reveal the necessary context
16987 (defun org-isearch-end ()
16988 "Reveal context after isearch exits."
16989 (when isearch-success ; only if search was successful
16990 (if (featurep 'xemacs)
16991 ;; Under XEmacs, the hook is run in the correct place,
16992 ;; we directly show the context.
16993 (org-show-context 'isearch)
16994 ;; In Emacs the hook runs *before* restoring the overlays.
16995 ;; So we have to use a one-time post-command-hook to do this.
16996 ;; (Emacs 22 has a special variable, see function `org-mode')
16997 (unless (and (boundp 'isearch-mode-end-hook-quit)
16998 isearch-mode-end-hook-quit)
16999 ;; Only when the isearch was not quitted.
17000 (org-add-hook 'post-command-hook 'org-isearch-post-command
17001 'append 'local)))))
17003 (defun org-isearch-post-command ()
17004 "Remove self from hook, and show context."
17005 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17006 (org-show-context 'isearch))
17009 ;;;; Integration with and fixes for other packages
17011 ;;; Imenu support
17013 (defvar org-imenu-markers nil
17014 "All markers currently used by Imenu.")
17015 (make-variable-buffer-local 'org-imenu-markers)
17017 (defun org-imenu-new-marker (&optional pos)
17018 "Return a new marker for use by Imenu, and remember the marker."
17019 (let ((m (make-marker)))
17020 (move-marker m (or pos (point)))
17021 (push m org-imenu-markers)
17024 (defun org-imenu-get-tree ()
17025 "Produce the index for Imenu."
17026 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17027 (setq org-imenu-markers nil)
17028 (let* ((n org-imenu-depth)
17029 (re (concat "^" outline-regexp))
17030 (subs (make-vector (1+ n) nil))
17031 (last-level 0)
17032 m level head)
17033 (save-excursion
17034 (save-restriction
17035 (widen)
17036 (goto-char (point-max))
17037 (while (re-search-backward re nil t)
17038 (setq level (org-reduced-level (funcall outline-level)))
17039 (when (<= level n)
17040 (looking-at org-complex-heading-regexp)
17041 (setq head (org-link-display-format
17042 (org-match-string-no-properties 4))
17043 m (org-imenu-new-marker))
17044 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17045 (if (>= level last-level)
17046 (push (cons head m) (aref subs level))
17047 (push (cons head (aref subs (1+ level))) (aref subs level))
17048 (loop for i from (1+ level) to n do (aset subs i nil)))
17049 (setq last-level level)))))
17050 (aref subs 1)))
17052 (eval-after-load "imenu"
17053 '(progn
17054 (add-hook 'imenu-after-jump-hook
17055 (lambda ()
17056 (if (eq major-mode 'org-mode)
17057 (org-show-context 'org-goto))))))
17059 (defun org-link-display-format (link)
17060 "Replace a link with either the description, or the link target
17061 if no description is present"
17062 (save-match-data
17063 (if (string-match org-bracket-link-analytic-regexp link)
17064 (replace-match (or (match-string 5 link)
17065 (concat (match-string 1 link)
17066 (match-string 3 link)))
17067 nil nil link)
17068 link)))
17070 ;; Speedbar support
17072 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17073 "Overlay marking the agenda restriction line in speedbar.")
17074 (org-overlay-put org-speedbar-restriction-lock-overlay
17075 'face 'org-agenda-restriction-lock)
17076 (org-overlay-put org-speedbar-restriction-lock-overlay
17077 'help-echo "Agendas are currently limited to this item.")
17078 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17080 (defun org-speedbar-set-agenda-restriction ()
17081 "Restrict future agenda commands to the location at point in speedbar.
17082 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17083 (interactive)
17084 (require 'org-agenda)
17085 (let (p m tp np dir txt)
17086 (cond
17087 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17088 'org-imenu t))
17089 (setq m (get-text-property p 'org-imenu-marker))
17090 (save-excursion
17091 (save-restriction
17092 (set-buffer (marker-buffer m))
17093 (goto-char m)
17094 (org-agenda-set-restriction-lock 'subtree))))
17095 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17096 'speedbar-function 'speedbar-find-file))
17097 (setq tp (previous-single-property-change
17098 (1+ p) 'speedbar-function)
17099 np (next-single-property-change
17100 tp 'speedbar-function)
17101 dir (speedbar-line-directory)
17102 txt (buffer-substring-no-properties (or tp (point-min))
17103 (or np (point-max))))
17104 (save-excursion
17105 (save-restriction
17106 (set-buffer (find-file-noselect
17107 (let ((default-directory dir))
17108 (expand-file-name txt))))
17109 (unless (org-mode-p)
17110 (error "Cannot restrict to non-Org-mode file"))
17111 (org-agenda-set-restriction-lock 'file))))
17112 (t (error "Don't know how to restrict Org-mode's agenda")))
17113 (org-move-overlay org-speedbar-restriction-lock-overlay
17114 (point-at-bol) (point-at-eol))
17115 (setq current-prefix-arg nil)
17116 (org-agenda-maybe-redo)))
17118 (eval-after-load "speedbar"
17119 '(progn
17120 (speedbar-add-supported-extension ".org")
17121 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17122 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17123 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17124 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17125 (add-hook 'speedbar-visiting-tag-hook
17126 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17129 ;;; Fixes and Hacks for problems with other packages
17131 ;; Make flyspell not check words in links, to not mess up our keymap
17132 (defun org-mode-flyspell-verify ()
17133 "Don't let flyspell put overlays at active buttons."
17134 (and (not (get-text-property (point) 'keymap))
17135 (not (get-text-property (point) 'org-no-flyspell))))
17137 (defun org-remove-flyspell-overlays-in (beg end)
17138 "Remove flyspell overlays in region."
17139 (and (org-bound-and-true-p flyspell-mode)
17140 (fboundp 'flyspell-delete-region-overlays)
17141 (flyspell-delete-region-overlays beg end))
17142 (add-text-properties beg end '(org-no-flyspell t)))
17144 ;; Make `bookmark-jump' show the jump location if it was hidden.
17145 (eval-after-load "bookmark"
17146 '(if (boundp 'bookmark-after-jump-hook)
17147 ;; We can use the hook
17148 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17149 ;; Hook not available, use advice
17150 (defadvice bookmark-jump (after org-make-visible activate)
17151 "Make the position visible."
17152 (org-bookmark-jump-unhide))))
17154 ;; Make sure saveplace show the location if it was hidden
17155 (eval-after-load "saveplace"
17156 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17157 "Make the position visible."
17158 (org-bookmark-jump-unhide)))
17160 (defun org-bookmark-jump-unhide ()
17161 "Unhide the current position, to show the bookmark location."
17162 (and (org-mode-p)
17163 (or (org-invisible-p)
17164 (save-excursion (goto-char (max (point-min) (1- (point))))
17165 (org-invisible-p)))
17166 (org-show-context 'bookmark-jump)))
17168 ;; Make session.el ignore our circular variable
17169 (eval-after-load "session"
17170 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17172 ;;;; Experimental code
17174 (defun org-closed-in-range ()
17175 "Sparse tree of items closed in a certain time range.
17176 Still experimental, may disappear in the future."
17177 (interactive)
17178 ;; Get the time interval from the user.
17179 (let* ((time1 (org-float-time
17180 (org-read-date nil 'to-time nil "Starting date: ")))
17181 (time2 (org-float-time
17182 (org-read-date nil 'to-time nil "End date:")))
17183 ;; callback function
17184 (callback (lambda ()
17185 (let ((time
17186 (org-float-time
17187 (apply 'encode-time
17188 (org-parse-time-string
17189 (match-string 1))))))
17190 ;; check if time in interval
17191 (and (>= time time1) (<= time time2))))))
17192 ;; make tree, check each match with the callback
17193 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17195 ;;;; Finish up
17197 (provide 'org)
17199 (run-hooks 'org-load-hook)
17201 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17203 ;;; org.el ends here