New STARTUP keyword `showeverything'
[org-mode.git] / lisp / org.el
blob72e98e6850333f5a206206f4dfe454c5432cee9b
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.30trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.30trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let* ((version org-version)
106 (git-version)
107 (dir (concat (file-name-directory (locate-library "org")) "../" )))
108 (if (and (file-exists-p (expand-file-name ".git" dir))
109 (executable-find "git"))
110 (let ((pwd (substring (pwd) 10)))
111 (cd dir)
112 (if (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
113 (save-excursion
114 (set-buffer "*Shell Command Output*")
115 (goto-char (point-min))
116 (re-search-forward "[^\n]+")
117 (setq git-version (match-string 0))
118 (subst-char-in-string ?- ?. git-version t)
119 (shell-command "git diff-index --name-only HEAD --")
120 (unless (eql 1 (point-max))
121 (setq git-version (concat git-version ".dirty")))
122 (setq version (concat version " (" git-version ")")))
123 (cd pwd))))
124 (setq version (format "Org-mode version %s" version))
125 (if here (insert version))
126 (message version)
127 version))
129 ;;; Compatibility constants
131 ;;; The custom variables
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
140 (defcustom org-load-hook nil
141 "Hook that is run after org.el has been loaded."
142 :group 'org
143 :type 'hook)
145 (defvar org-modules) ; defined below
146 (defvar org-modules-loaded nil
147 "Have the modules been loaded already?")
149 (defun org-load-modules-maybe (&optional force)
150 "Load all extensions listed in `org-modules'."
151 (when (or force (not org-modules-loaded))
152 (mapc (lambda (ext)
153 (condition-case nil (require ext)
154 (error (message "Problems while trying to load feature `%s'" ext))))
155 org-modules)
156 (setq org-modules-loaded t)))
158 (defun org-set-modules (var value)
159 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
160 (set var value)
161 (when (featurep 'org)
162 (org-load-modules-maybe 'force)))
164 (when (org-bound-and-true-p org-modules)
165 (let ((a (member 'org-infojs org-modules)))
166 (and a (setcar a 'org-jsinfo))))
168 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
169 "Modules that should always be loaded together with org.el.
170 If a description starts with <C>, the file is not part of Emacs
171 and loading it will require that you have downloaded and properly installed
172 the org-mode distribution.
174 You can also use this system to load external packages (i.e. neither Org
175 core modules, nor modules from the CONTRIB directory). Just add symbols
176 to the end of the list. If the package is called org-xyz.el, then you need
177 to add the symbol `xyz', and the package must have a call to
179 (provide 'org-xyz)"
180 :group 'org
181 :set 'org-set-modules
182 :type
183 '(set :greedy t
184 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
185 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
186 (const :tag " crypt: Encryption of subtrees" org-crypt)
187 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
188 (const :tag " id: Global IDs for identifying entries" org-id)
189 (const :tag " info: Links to Info nodes" org-info)
190 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
191 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
192 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
193 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
194 (const :tag " mew Links to Mew folders/messages" org-mew)
195 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
196 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
197 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
198 (const :tag " vm: Links to VM folders/messages" org-vm)
199 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
200 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
201 (const :tag " mouse: Additional mouse support" org-mouse)
203 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
204 (const :tag "C annotation-helper: Call Remember directly from Browser\n\t\t\t(OBSOLETE, use org-protocol)" org-annotation-helper)
205 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
206 (const :tag "C browser-url: Store link, directly from Browser\n\t\t\t(OBSOLETE, use org-protocol)" org-browser-url)
207 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
208 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
209 (const :tag "C collector: Collect properties into tables" org-collector)
210 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
211 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
212 (const :tag "C eval: Include command output as text" org-eval)
213 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
214 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
215 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
216 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
218 (const :tag "C invoice Help manage client invoices in OrgMode" org-invoice)
220 (const :tag "C jira Add a jira:ticket protocol to Org" org-jira)
221 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
222 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
223 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
224 (const :tag "C mtags: Support for muse-like tags" org-mtags)
225 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
226 (const :tag "C R: Computation using the R language" org-R)
227 (const :tag "C registry: A registry for Org links" org-registry)
228 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
229 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
230 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
231 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
232 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
233 (const :tag "C track: Keep up with Org development" org-track)
234 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
236 (defcustom org-support-shift-select nil
237 "Non-nil means, make shift-cursor commands select text when possible.
239 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
240 selecting a region, or enlarge thusly regions started in this way.
241 In Org-mode, in special contexts, these same keys are used for other
242 purposes, important enough to compete with shift selection. Org tries
243 to balance these needs by supporting `shift-select-mode' outside these
244 special contexts, under control of this variable.
246 The default of this variable is nil, to avoid confusing behavior. Shifted
247 cursor keys will then execute Org commands in the following contexts:
248 - on a headline, changing TODO state (left/right) and priority (up/down)
249 - on a time stamp, changing the time
250 - in a plain list item, changing the bullet type
251 - in a property definition line, switching between allowed values
252 - in the BEGIN line of a clock table (changing the time block).
253 Outside these contexts, the commands will throw an error.
255 When this variable is t and the cursor is not in a special context,
256 Org-mode will support shift-selection for making and enlarging regions.
257 To make this more effective, the bullet cycling will no longer happen
258 anywhere in an item line, but only if the cursor is exactly on the bullet.
260 If you set this variable to the symbol `always', then the keys
261 will not be special in headlines, property lines, and item lines, to make
262 shift selection work there as well. If this is what you want, you can
263 use the following alternative commands: `C-c C-t' and `C-c ,' to
264 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
265 TODO sets, `C-c -' to cycle item bullet types, and properties can be
266 edited by hand or in column view.
268 However, when the cursor is on a timestamp, shift-cursor commands
269 will still edit the time stamp - this is just too good to give up.
271 XEmacs user should have this variable set to nil, because shift-select-mode
272 is Emacs 23 only."
273 :group 'org
274 :type '(choice
275 (const :tag "Never" nil)
276 (const :tag "When outside special context" t)
277 (const :tag "Everywhere except timestamps" always)))
279 (defgroup org-startup nil
280 "Options concerning startup of Org-mode."
281 :tag "Org Startup"
282 :group 'org)
284 (defcustom org-startup-folded t
285 "Non-nil means, entering Org-mode will switch to OVERVIEW.
286 This can also be configured on a per-file basis by adding one of
287 the following lines anywhere in the buffer:
289 #+STARTUP: fold (or `overview', this is equivalent)
290 #+STARTUP: nofold (or `showall', this is equivalent)
291 #+STARTUP: content
292 #+STARTUP: showeverything"
293 :group 'org-startup
294 :type '(choice
295 (const :tag "nofold: show all" nil)
296 (const :tag "fold: overview" t)
297 (const :tag "content: all headlines" content)
298 (const :tag "show everything, even drawers" showeverything)))
300 (defcustom org-startup-truncated t
301 "Non-nil means, entering Org-mode will set `truncate-lines'.
302 This is useful since some lines containing links can be very long and
303 uninteresting. Also tables look terrible when wrapped."
304 :group 'org-startup
305 :type 'boolean)
307 (defcustom org-startup-indented nil
308 "Non-nil means, turn on `org-indent-mode' on startup.
309 This can also be configured on a per-file basis by adding one of
310 the following lines anywhere in the buffer:
312 #+STARTUP: indent
313 #+STARTUP: noindent"
314 :group 'org-structure
315 :type '(choice
316 (const :tag "Not" nil)
317 (const :tag "Globally (slow on startup in large files)" t)))
319 (defcustom org-startup-align-all-tables nil
320 "Non-nil means, align all tables when visiting a file.
321 This is useful when the column width in tables is forced with <N> cookies
322 in table fields. Such tables will look correct only after the first re-align.
323 This can also be configured on a per-file basis by adding one of
324 the following lines anywhere in the buffer:
325 #+STARTUP: align
326 #+STARTUP: noalign"
327 :group 'org-startup
328 :type 'boolean)
330 (defcustom org-insert-mode-line-in-empty-file nil
331 "Non-nil means insert the first line setting Org-mode in empty files.
332 When the function `org-mode' is called interactively in an empty file, this
333 normally means that the file name does not automatically trigger Org-mode.
334 To ensure that the file will always be in Org-mode in the future, a
335 line enforcing Org-mode will be inserted into the buffer, if this option
336 has been set."
337 :group 'org-startup
338 :type 'boolean)
340 (defcustom org-replace-disputed-keys nil
341 "Non-nil means use alternative key bindings for some keys.
342 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
343 These keys are also used by other packages like shift-selection-mode'
344 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
345 If you want to use Org-mode together with one of these other modes,
346 or more generally if you would like to move some Org-mode commands to
347 other keys, set this variable and configure the keys with the variable
348 `org-disputed-keys'.
350 This option is only relevant at load-time of Org-mode, and must be set
351 *before* org.el is loaded. Changing it requires a restart of Emacs to
352 become effective."
353 :group 'org-startup
354 :type 'boolean)
356 (defcustom org-use-extra-keys nil
357 "Non-nil means use extra key sequence definitions for certain
358 commands. This happens automatically if you run XEmacs or if
359 window-system is nil. This variable lets you do the same
360 manually. You must set it before loading org.
362 Example: on Carbon Emacs 22 running graphically, with an external
363 keyboard on a Powerbook, the default way of setting M-left might
364 not work for either Alt or ESC. Setting this variable will make
365 it work for ESC."
366 :group 'org-startup
367 :type 'boolean)
369 (if (fboundp 'defvaralias)
370 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
372 (defcustom org-disputed-keys
373 '(([(shift up)] . [(meta p)])
374 ([(shift down)] . [(meta n)])
375 ([(shift left)] . [(meta -)])
376 ([(shift right)] . [(meta +)])
377 ([(control shift right)] . [(meta shift +)])
378 ([(control shift left)] . [(meta shift -)]))
379 "Keys for which Org-mode and other modes compete.
380 This is an alist, cars are the default keys, second element specifies
381 the alternative to use when `org-replace-disputed-keys' is t.
383 Keys can be specified in any syntax supported by `define-key'.
384 The value of this option takes effect only at Org-mode's startup,
385 therefore you'll have to restart Emacs to apply it after changing."
386 :group 'org-startup
387 :type 'alist)
389 (defun org-key (key)
390 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
391 Or return the original if not disputed."
392 (if org-replace-disputed-keys
393 (let* ((nkey (key-description key))
394 (x (org-find-if (lambda (x)
395 (equal (key-description (car x)) nkey))
396 org-disputed-keys)))
397 (if x (cdr x) key))
398 key))
400 (defun org-find-if (predicate seq)
401 (catch 'exit
402 (while seq
403 (if (funcall predicate (car seq))
404 (throw 'exit (car seq))
405 (pop seq)))))
407 (defun org-defkey (keymap key def)
408 "Define a key, possibly translated, as returned by `org-key'."
409 (define-key keymap (org-key key) def))
411 (defcustom org-ellipsis nil
412 "The ellipsis to use in the Org-mode outline.
413 When nil, just use the standard three dots. When a string, use that instead,
414 When a face, use the standard 3 dots, but with the specified face.
415 The change affects only Org-mode (which will then use its own display table).
416 Changing this requires executing `M-x org-mode' in a buffer to become
417 effective."
418 :group 'org-startup
419 :type '(choice (const :tag "Default" nil)
420 (face :tag "Face" :value org-warning)
421 (string :tag "String" :value "...#")))
423 (defvar org-display-table nil
424 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
426 (defgroup org-keywords nil
427 "Keywords in Org-mode."
428 :tag "Org Keywords"
429 :group 'org)
431 (defcustom org-deadline-string "DEADLINE:"
432 "String to mark deadline entries.
433 A deadline is this string, followed by a time stamp. Should be a word,
434 terminated by a colon. You can insert a schedule keyword and
435 a timestamp with \\[org-deadline].
436 Changes become only effective after restarting Emacs."
437 :group 'org-keywords
438 :type 'string)
440 (defcustom org-scheduled-string "SCHEDULED:"
441 "String to mark scheduled TODO entries.
442 A schedule is this string, followed by a time stamp. Should be a word,
443 terminated by a colon. You can insert a schedule keyword and
444 a timestamp with \\[org-schedule].
445 Changes become only effective after restarting Emacs."
446 :group 'org-keywords
447 :type 'string)
449 (defcustom org-closed-string "CLOSED:"
450 "String used as the prefix for timestamps logging closing a TODO entry."
451 :group 'org-keywords
452 :type 'string)
454 (defcustom org-clock-string "CLOCK:"
455 "String used as prefix for timestamps clocking work hours on an item."
456 :group 'org-keywords
457 :type 'string)
459 (defcustom org-comment-string "COMMENT"
460 "Entries starting with this keyword will never be exported.
461 An entry can be toggled between COMMENT and normal with
462 \\[org-toggle-comment].
463 Changes become only effective after restarting Emacs."
464 :group 'org-keywords
465 :type 'string)
467 (defcustom org-quote-string "QUOTE"
468 "Entries starting with this keyword will be exported in fixed-width font.
469 Quoting applies only to the text in the entry following the headline, and does
470 not extend beyond the next headline, even if that is lower level.
471 An entry can be toggled between QUOTE and normal with
472 \\[org-toggle-fixed-width-section]."
473 :group 'org-keywords
474 :type 'string)
476 (defconst org-repeat-re
477 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
478 "Regular expression for specifying repeated events.
479 After a match, group 1 contains the repeat expression.")
481 (defgroup org-structure nil
482 "Options concerning the general structure of Org-mode files."
483 :tag "Org Structure"
484 :group 'org)
486 (defgroup org-reveal-location nil
487 "Options about how to make context of a location visible."
488 :tag "Org Reveal Location"
489 :group 'org-structure)
491 (defconst org-context-choice
492 '(choice
493 (const :tag "Always" t)
494 (const :tag "Never" nil)
495 (repeat :greedy t :tag "Individual contexts"
496 (cons
497 (choice :tag "Context"
498 (const agenda)
499 (const org-goto)
500 (const occur-tree)
501 (const tags-tree)
502 (const link-search)
503 (const mark-goto)
504 (const bookmark-jump)
505 (const isearch)
506 (const default))
507 (boolean))))
508 "Contexts for the reveal options.")
510 (defcustom org-show-hierarchy-above '((default . t))
511 "Non-nil means, show full hierarchy when revealing a location.
512 Org-mode often shows locations in an org-mode file which might have
513 been invisible before. When this is set, the hierarchy of headings
514 above the exposed location is shown.
515 Turning this off for example for sparse trees makes them very compact.
516 Instead of t, this can also be an alist specifying this option for different
517 contexts. Valid contexts are
518 agenda when exposing an entry from the agenda
519 org-goto when using the command `org-goto' on key C-c C-j
520 occur-tree when using the command `org-occur' on key C-c /
521 tags-tree when constructing a sparse tree based on tags matches
522 link-search when exposing search matches associated with a link
523 mark-goto when exposing the jump goal of a mark
524 bookmark-jump when exposing a bookmark location
525 isearch when exiting from an incremental search
526 default default for all contexts not set explicitly"
527 :group 'org-reveal-location
528 :type org-context-choice)
530 (defcustom org-show-following-heading '((default . nil))
531 "Non-nil means, show following heading when revealing a location.
532 Org-mode often shows locations in an org-mode file which might have
533 been invisible before. When this is set, the heading following the
534 match is shown.
535 Turning this off for example for sparse trees makes them very compact,
536 but makes it harder to edit the location of the match. In such a case,
537 use the command \\[org-reveal] to show more context.
538 Instead of t, this can also be an alist specifying this option for different
539 contexts. See `org-show-hierarchy-above' for valid contexts."
540 :group 'org-reveal-location
541 :type org-context-choice)
543 (defcustom org-show-siblings '((default . nil) (isearch t))
544 "Non-nil means, show all sibling heading when revealing a location.
545 Org-mode often shows locations in an org-mode file which might have
546 been invisible before. When this is set, the sibling of the current entry
547 heading are all made visible. If `org-show-hierarchy-above' is t,
548 the same happens on each level of the hierarchy above the current entry.
550 By default this is on for the isearch context, off for all other contexts.
551 Turning this off for example for sparse trees makes them very compact,
552 but makes it harder to edit the location of the match. In such a case,
553 use the command \\[org-reveal] to show more context.
554 Instead of t, this can also be an alist specifying this option for different
555 contexts. See `org-show-hierarchy-above' for valid contexts."
556 :group 'org-reveal-location
557 :type org-context-choice)
559 (defcustom org-show-entry-below '((default . nil))
560 "Non-nil means, show the entry below a headline when revealing a location.
561 Org-mode often shows locations in an org-mode file which might have
562 been invisible before. When this is set, the text below the headline that is
563 exposed is also shown.
565 By default this is off for all contexts.
566 Instead of t, this can also be an alist specifying this option for different
567 contexts. See `org-show-hierarchy-above' for valid contexts."
568 :group 'org-reveal-location
569 :type org-context-choice)
571 (defcustom org-indirect-buffer-display 'other-window
572 "How should indirect tree buffers be displayed?
573 This applies to indirect buffers created with the commands
574 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
575 Valid values are:
576 current-window Display in the current window
577 other-window Just display in another window.
578 dedicated-frame Create one new frame, and re-use it each time.
579 new-frame Make a new frame each time. Note that in this case
580 previously-made indirect buffers are kept, and you need to
581 kill these buffers yourself."
582 :group 'org-structure
583 :group 'org-agenda-windows
584 :type '(choice
585 (const :tag "In current window" current-window)
586 (const :tag "In current frame, other window" other-window)
587 (const :tag "Each time a new frame" new-frame)
588 (const :tag "One dedicated frame" dedicated-frame)))
590 (defgroup org-cycle nil
591 "Options concerning visibility cycling in Org-mode."
592 :tag "Org Cycle"
593 :group 'org-structure)
595 (defcustom org-cycle-skip-children-state-if-no-children t
596 "Non-nil means, skip CHILDREN state in entries that don't have any."
597 :group 'org-cycle
598 :type 'boolean)
600 (defcustom org-cycle-max-level nil
601 "Maximum level which should still be subject to visibility cycling.
602 Levels higher than this will, for cycling, be treated as text, not a headline.
603 When `org-odd-levels-only' is set, a value of N in this variable actually
604 means 2N-1 stars as the limiting headline.
605 When nil, cycle all levels.
606 Note that the limiting level of cycling is also influenced by
607 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
608 `org-inlinetask-min-level' is, cycling will be limited to levels one less
609 than its value."
610 :group 'org-cycle
611 :type '(choice
612 (const :tag "No limit" nil)
613 (integer :tag "Maximum level")))
615 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
616 "Names of drawers. Drawers are not opened by cycling on the headline above.
617 Drawers only open with a TAB on the drawer line itself. A drawer looks like
618 this:
619 :DRAWERNAME:
620 .....
621 :END:
622 The drawer \"PROPERTIES\" is special for capturing properties through
623 the property API.
625 Drawers can be defined on the per-file basis with a line like:
627 #+DRAWERS: HIDDEN STATE PROPERTIES"
628 :group 'org-structure
629 :group 'org-cycle
630 :type '(repeat (string :tag "Drawer Name")))
632 (defcustom org-hide-block-startup nil
633 "Non-nil means, , entering Org-mode will fold all blocks.
634 This can also be set in on a per-file basis with
636 #+STARTUP: hideblocks
637 #+STARTUP: showblocks"
638 :group 'org-startup
639 :group 'org-cycle
640 :type 'boolean)
642 (defcustom org-cycle-global-at-bob nil
643 "Cycle globally if cursor is at beginning of buffer and not at a headline.
644 This makes it possible to do global cycling without having to use S-TAB or
645 C-u TAB. For this special case to work, the first line of the buffer
646 must not be a headline - it may be empty or some other text. When used in
647 this way, `org-cycle-hook' is disables temporarily, to make sure the
648 cursor stays at the beginning of the buffer.
649 When this option is nil, don't do anything special at the beginning
650 of the buffer."
651 :group 'org-cycle
652 :type 'boolean)
654 (defcustom org-cycle-emulate-tab t
655 "Where should `org-cycle' emulate TAB.
656 nil Never
657 white Only in completely white lines
658 whitestart Only at the beginning of lines, before the first non-white char
659 t Everywhere except in headlines
660 exc-hl-bol Everywhere except at the start of a headline
661 If TAB is used in a place where it does not emulate TAB, the current subtree
662 visibility is cycled."
663 :group 'org-cycle
664 :type '(choice (const :tag "Never" nil)
665 (const :tag "Only in completely white lines" white)
666 (const :tag "Before first char in a line" whitestart)
667 (const :tag "Everywhere except in headlines" t)
668 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
671 (defcustom org-cycle-separator-lines 2
672 "Number of empty lines needed to keep an empty line between collapsed trees.
673 If you leave an empty line between the end of a subtree and the following
674 headline, this empty line is hidden when the subtree is folded.
675 Org-mode will leave (exactly) one empty line visible if the number of
676 empty lines is equal or larger to the number given in this variable.
677 So the default 2 means, at least 2 empty lines after the end of a subtree
678 are needed to produce free space between a collapsed subtree and the
679 following headline.
681 If the number is negative, and the number of empty lines is at least -N,
682 all empty lines are shown.
684 Special case: when 0, never leave empty lines in collapsed view."
685 :group 'org-cycle
686 :type 'integer)
687 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
689 (defcustom org-pre-cycle-hook nil
690 "Hook that is run before visibility cycling is happening.
691 The function(s) in this hook must accept a single argument which indicates
692 the new state that will be set right after running this hook. The
693 argument is a symbol. Before a global state change, it can have the values
694 `overview', `content', or `all'. Before a local state change, it can have
695 the values `folded', `children', or `subtree'."
696 :group 'org-cycle
697 :type 'hook)
699 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
700 org-cycle-hide-drawers
701 org-cycle-show-empty-lines
702 org-optimize-window-after-visibility-change)
703 "Hook that is run after `org-cycle' has changed the buffer visibility.
704 The function(s) in this hook must accept a single argument which indicates
705 the new state that was set by the most recent `org-cycle' command. The
706 argument is a symbol. After a global state change, it can have the values
707 `overview', `content', or `all'. After a local state change, it can have
708 the values `folded', `children', or `subtree'."
709 :group 'org-cycle
710 :type 'hook)
712 (defgroup org-edit-structure nil
713 "Options concerning structure editing in Org-mode."
714 :tag "Org Edit Structure"
715 :group 'org-structure)
717 (defcustom org-odd-levels-only nil
718 "Non-nil means, skip even levels and only use odd levels for the outline.
719 This has the effect that two stars are being added/taken away in
720 promotion/demotion commands. It also influences how levels are
721 handled by the exporters.
722 Changing it requires restart of `font-lock-mode' to become effective
723 for fontification also in regions already fontified.
724 You may also set this on a per-file basis by adding one of the following
725 lines to the buffer:
727 #+STARTUP: odd
728 #+STARTUP: oddeven"
729 :group 'org-edit-structure
730 :group 'org-font-lock
731 :type 'boolean)
733 (defcustom org-adapt-indentation t
734 "Non-nil means, adapt indentation to outline node level.
736 When this variable is set, Org assumes that you write outlines by
737 indenting text in each node to align with the headline (after the stars).
738 The following issues are influenced by this variable:
740 - When this is set and the *entire* text in an entry is indented, the
741 indentation is increased by one space in a demotion command, and
742 decreased by one in a promotion command. If any line in the entry
743 body starts with text at column 0, indentation is not changed at all.
745 - Property drawers and planning information is inserted indented when
746 this variable s set. When nil, they will not be indented.
748 - TAB indents a line relative to context. The lines below a headline
749 will be indented when this variable is set.
751 Note that this is all about true indentation, by adding and removing
752 space characters. See also `org-indent.el' which does level-dependent
753 indentation in a virtual way, i.e. at display time in Emacs."
754 :group 'org-edit-structure
755 :type 'boolean)
757 (defcustom org-special-ctrl-a/e nil
758 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
760 When t, `C-a' will bring back the cursor to the beginning of the
761 headline text, i.e. after the stars and after a possible TODO keyword.
762 In an item, this will be the position after the bullet.
763 When the cursor is already at that position, another `C-a' will bring
764 it to the beginning of the line.
766 `C-e' will jump to the end of the headline, ignoring the presence of tags
767 in the headline. A second `C-e' will then jump to the true end of the
768 line, after any tags.
770 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
771 going to the true line boundary first. Only a directly following, identical
772 keypress will bring the cursor to the special positions.
774 This may also be a cons cell where the behavior for `C-a' and `C-e' is
775 set separately."
776 :group 'org-edit-structure
777 :type '(choice
778 (const :tag "off" nil)
779 (const :tag "after stars/bullet and before tags first" t)
780 (const :tag "true line boundary first" reversed)
781 (cons :tag "Set C-a and C-e separately"
782 (choice :tag "Special C-a"
783 (const :tag "off" nil)
784 (const :tag "after stars/bullet first" t)
785 (const :tag "before stars/bullet first" reversed))
786 (choice :tag "Special C-e"
787 (const :tag "off" nil)
788 (const :tag "before tags first" t)
789 (const :tag "after tags first" reversed)))))
790 (if (fboundp 'defvaralias)
791 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
793 (defcustom org-special-ctrl-k nil
794 "Non-nil means `C-k' will behave specially in headlines.
795 When nil, `C-k' will call the default `kill-line' command.
796 When t, the following will happen while the cursor is in the headline:
798 - When the cursor is at the beginning of a headline, kill the entire
799 line and possible the folded subtree below the line.
800 - When in the middle of the headline text, kill the headline up to the tags.
801 - When after the headline text, kill the tags."
802 :group 'org-edit-structure
803 :type 'boolean)
805 (defcustom org-yank-folded-subtrees t
806 "Non-nil means, when yanking subtrees, fold them.
807 If the kill is a single subtree, or a sequence of subtrees, i.e. if
808 it starts with a heading and all other headings in it are either children
809 or siblings, then fold all the subtrees. However, do this only if no
810 text after the yank would be swallowed into a folded tree by this action."
811 :group 'org-edit-structure
812 :type 'boolean)
814 (defcustom org-yank-adjusted-subtrees nil
815 "Non-nil means, when yanking subtrees, adjust the level.
816 With this setting, `org-paste-subtree' is used to insert the subtree, see
817 this function for details."
818 :group 'org-edit-structure
819 :type 'boolean)
821 (defcustom org-M-RET-may-split-line '((default . t))
822 "Non-nil means, M-RET will split the line at the cursor position.
823 When nil, it will go to the end of the line before making a
824 new line.
825 You may also set this option in a different way for different
826 contexts. Valid contexts are:
828 headline when creating a new headline
829 item when creating a new item
830 table in a table field
831 default the value to be used for all contexts not explicitly
832 customized"
833 :group 'org-structure
834 :group 'org-table
835 :type '(choice
836 (const :tag "Always" t)
837 (const :tag "Never" nil)
838 (repeat :greedy t :tag "Individual contexts"
839 (cons
840 (choice :tag "Context"
841 (const headline)
842 (const item)
843 (const table)
844 (const default))
845 (boolean)))))
848 (defcustom org-insert-heading-respect-content nil
849 "Non-nil means, insert new headings after the current subtree.
850 When nil, the new heading is created directly after the current line.
851 The commands \\[org-insert-heading-respect-content] and
852 \\[org-insert-todo-heading-respect-content] turn this variable on
853 for the duration of the command."
854 :group 'org-structure
855 :type 'boolean)
857 (defcustom org-blank-before-new-entry '((heading . auto)
858 (plain-list-item . auto))
859 "Should `org-insert-heading' leave a blank line before new heading/item?
860 The value is an alist, with `heading' and `plain-list-item' as car,
861 and a boolean flag as cdr. For plain lists, if the variable
862 `org-empty-line-terminates-plain-lists' is set, the setting here
863 is ignored and no empty line is inserted, to keep the list in tact."
864 :group 'org-edit-structure
865 :type '(list
866 (cons (const heading)
867 (choice (const :tag "Never" nil)
868 (const :tag "Always" t)
869 (const :tag "Auto" auto)))
870 (cons (const plain-list-item)
871 (choice (const :tag "Never" nil)
872 (const :tag "Always" t)
873 (const :tag "Auto" auto)))))
875 (defcustom org-insert-heading-hook nil
876 "Hook being run after inserting a new heading."
877 :group 'org-edit-structure
878 :type 'hook)
880 (defcustom org-enable-fixed-width-editor t
881 "Non-nil means, lines starting with \":\" are treated as fixed-width.
882 This currently only means, they are never auto-wrapped.
883 When nil, such lines will be treated like ordinary lines.
884 See also the QUOTE keyword."
885 :group 'org-edit-structure
886 :type 'boolean)
889 (defcustom org-goto-auto-isearch t
890 "Non-nil means, typing characters in org-goto starts incremental search."
891 :group 'org-edit-structure
892 :type 'boolean)
894 (defgroup org-sparse-trees nil
895 "Options concerning sparse trees in Org-mode."
896 :tag "Org Sparse Trees"
897 :group 'org-structure)
899 (defcustom org-highlight-sparse-tree-matches t
900 "Non-nil means, highlight all matches that define a sparse tree.
901 The highlights will automatically disappear the next time the buffer is
902 changed by an edit command."
903 :group 'org-sparse-trees
904 :type 'boolean)
906 (defcustom org-remove-highlights-with-change t
907 "Non-nil means, any change to the buffer will remove temporary highlights.
908 Such highlights are created by `org-occur' and `org-clock-display'.
909 When nil, `C-c C-c needs to be used to get rid of the highlights.
910 The highlights created by `org-preview-latex-fragment' always need
911 `C-c C-c' to be removed."
912 :group 'org-sparse-trees
913 :group 'org-time
914 :type 'boolean)
917 (defcustom org-occur-hook '(org-first-headline-recenter)
918 "Hook that is run after `org-occur' has constructed a sparse tree.
919 This can be used to recenter the window to show as much of the structure
920 as possible."
921 :group 'org-sparse-trees
922 :type 'hook)
924 (defgroup org-imenu-and-speedbar nil
925 "Options concerning imenu and speedbar in Org-mode."
926 :tag "Org Imenu and Speedbar"
927 :group 'org-structure)
929 (defcustom org-imenu-depth 2
930 "The maximum level for Imenu access to Org-mode headlines.
931 This also applied for speedbar access."
932 :group 'org-imenu-and-speedbar
933 :type 'integer)
935 (defgroup org-table nil
936 "Options concerning tables in Org-mode."
937 :tag "Org Table"
938 :group 'org)
940 (defcustom org-enable-table-editor 'optimized
941 "Non-nil means, lines starting with \"|\" are handled by the table editor.
942 When nil, such lines will be treated like ordinary lines.
944 When equal to the symbol `optimized', the table editor will be optimized to
945 do the following:
946 - Automatic overwrite mode in front of whitespace in table fields.
947 This makes the structure of the table stay in tact as long as the edited
948 field does not exceed the column width.
949 - Minimize the number of realigns. Normally, the table is aligned each time
950 TAB or RET are pressed to move to another field. With optimization this
951 happens only if changes to a field might have changed the column width.
952 Optimization requires replacing the functions `self-insert-command',
953 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
954 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
955 very good at guessing when a re-align will be necessary, but you can always
956 force one with \\[org-ctrl-c-ctrl-c].
958 If you would like to use the optimized version in Org-mode, but the
959 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
961 This variable can be used to turn on and off the table editor during a session,
962 but in order to toggle optimization, a restart is required.
964 See also the variable `org-table-auto-blank-field'."
965 :group 'org-table
966 :type '(choice
967 (const :tag "off" nil)
968 (const :tag "on" t)
969 (const :tag "on, optimized" optimized)))
971 (defcustom org-self-insert-cluster-for-undo t
972 "Non-nil means cluster self-insert commands for undo when possible.
973 If this is set, then, like in the Emacs command loop, 20 consequtive
974 characters will be undone together.
975 This is configurable, because there is some impact on typing performance."
976 :group 'org-table
977 :type 'boolean)
979 (defcustom org-table-tab-recognizes-table.el t
980 "Non-nil means, TAB will automatically notice a table.el table.
981 When it sees such a table, it moves point into it and - if necessary -
982 calls `table-recognize-table'."
983 :group 'org-table-editing
984 :type 'boolean)
986 (defgroup org-link nil
987 "Options concerning links in Org-mode."
988 :tag "Org Link"
989 :group 'org)
991 (defvar org-link-abbrev-alist-local nil
992 "Buffer-local version of `org-link-abbrev-alist', which see.
993 The value of this is taken from the #+LINK lines.")
994 (make-variable-buffer-local 'org-link-abbrev-alist-local)
996 (defcustom org-link-abbrev-alist nil
997 "Alist of link abbreviations.
998 The car of each element is a string, to be replaced at the start of a link.
999 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1000 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1002 [[linkkey:tag][description]]
1004 The 'linkkey' must be a word word, starting with a letter, followed
1005 by letters, numbers, '-' or '_'.
1007 If REPLACE is a string, the tag will simply be appended to create the link.
1008 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1009 the placeholder \"%h\" will cause a url-encoded version of the tag to
1010 be inserted at that point (see the function `url-hexify-string').
1012 REPLACE may also be a function that will be called with the tag as the
1013 only argument to create the link, which should be returned as a string.
1015 See the manual for examples."
1016 :group 'org-link
1017 :type '(repeat
1018 (cons
1019 (string :tag "Protocol")
1020 (choice
1021 (string :tag "Format")
1022 (function)))))
1024 (defcustom org-descriptive-links t
1025 "Non-nil means, hide link part and only show description of bracket links.
1026 Bracket links are like [[link][description]]. This variable sets the initial
1027 state in new org-mode buffers. The setting can then be toggled on a
1028 per-buffer basis from the Org->Hyperlinks menu."
1029 :group 'org-link
1030 :type 'boolean)
1032 (defcustom org-link-file-path-type 'adaptive
1033 "How the path name in file links should be stored.
1034 Valid values are:
1036 relative Relative to the current directory, i.e. the directory of the file
1037 into which the link is being inserted.
1038 absolute Absolute path, if possible with ~ for home directory.
1039 noabbrev Absolute path, no abbreviation of home directory.
1040 adaptive Use relative path for files in the current directory and sub-
1041 directories of it. For other files, use an absolute path."
1042 :group 'org-link
1043 :type '(choice
1044 (const relative)
1045 (const absolute)
1046 (const noabbrev)
1047 (const adaptive)))
1049 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1050 "Types of links that should be activated in Org-mode files.
1051 This is a list of symbols, each leading to the activation of a certain link
1052 type. In principle, it does not hurt to turn on most link types - there may
1053 be a small gain when turning off unused link types. The types are:
1055 bracket The recommended [[link][description]] or [[link]] links with hiding.
1056 angular Links in angular brackets that may contain whitespace like
1057 <bbdb:Carsten Dominik>.
1058 plain Plain links in normal text, no whitespace, like http://google.com.
1059 radio Text that is matched by a radio target, see manual for details.
1060 tag Tag settings in a headline (link to tag search).
1061 date Time stamps (link to calendar).
1062 footnote Footnote labels.
1064 Changing this variable requires a restart of Emacs to become effective."
1065 :group 'org-link
1066 :type '(set :greedy t
1067 (const :tag "Double bracket links (new style)" bracket)
1068 (const :tag "Angular bracket links (old style)" angular)
1069 (const :tag "Plain text links" plain)
1070 (const :tag "Radio target matches" radio)
1071 (const :tag "Tags" tag)
1072 (const :tag "Timestamps" date)
1073 (const :tag "Footnotes" footnote)))
1075 (defcustom org-make-link-description-function nil
1076 "Function to use to generate link descriptions from links. If
1077 nil the link location will be used. This function must take two
1078 parameters; the first is the link and the second the description
1079 org-insert-link has generated, and should return the description
1080 to use."
1081 :group 'org-link
1082 :type 'function)
1084 (defgroup org-link-store nil
1085 "Options concerning storing links in Org-mode."
1086 :tag "Org Store Link"
1087 :group 'org-link)
1089 (defcustom org-email-link-description-format "Email %c: %.30s"
1090 "Format of the description part of a link to an email or usenet message.
1091 The following %-escapes will be replaced by corresponding information:
1093 %F full \"From\" field
1094 %f name, taken from \"From\" field, address if no name
1095 %T full \"To\" field
1096 %t first name in \"To\" field, address if no name
1097 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1098 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1099 %s subject
1100 %m message-id.
1102 You may use normal field width specification between the % and the letter.
1103 This is for example useful to limit the length of the subject.
1105 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1106 :group 'org-link-store
1107 :type 'string)
1109 (defcustom org-from-is-user-regexp
1110 (let (r1 r2)
1111 (when (and user-mail-address (not (string= user-mail-address "")))
1112 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1113 (when (and user-full-name (not (string= user-full-name "")))
1114 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1115 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1116 "Regexp matched against the \"From:\" header of an email or usenet message.
1117 It should match if the message is from the user him/herself."
1118 :group 'org-link-store
1119 :type 'regexp)
1121 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1122 "Non-nil means, storing a link to an Org file will use entry IDs.
1124 Note that before this variable is even considered, org-id must be loaded,
1125 so please customize `org-modules' and turn it on.
1127 The variable can have the following values:
1129 t Create an ID if needed to make a link to the current entry.
1131 create-if-interactive
1132 If `org-store-link' is called directly (interactively, as a user
1133 command), do create an ID to support the link. But when doing the
1134 job for remember, only use the ID if it already exists. The
1135 purpose of this setting is to avoid proliferation of unwanted
1136 IDs, just because you happen to be in an Org file when you
1137 call `org-remember' that automatically and preemptively
1138 creates a link. If you do want to get an ID link in a remember
1139 template to an entry not having an ID, create it first by
1140 explicitly creating a link to it, using `C-c C-l' first.
1142 create-if-interactive-and-no-custom-id
1143 Like create-if-interactive, but do not create an ID if there is
1144 a CUSTOM_ID property defined in the entry. This is the default.
1146 use-existing
1147 Use existing ID, do not create one.
1149 nil Never use an ID to make a link, instead link using a text search for
1150 the headline text."
1151 :group 'org-link-store
1152 :type '(choice
1153 (const :tag "Create ID to make link" t)
1154 (const :tag "Create if storing link interactively"
1155 create-if-interactive)
1156 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1157 create-if-interactive-and-no-custom-id)
1158 (const :tag "Only use existing" use-existing)
1159 (const :tag "Do not use ID to create link" nil)))
1161 (defcustom org-context-in-file-links t
1162 "Non-nil means, file links from `org-store-link' contain context.
1163 A search string will be added to the file name with :: as separator and
1164 used to find the context when the link is activated by the command
1165 `org-open-at-point'.
1166 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1167 negates this setting for the duration of the command."
1168 :group 'org-link-store
1169 :type 'boolean)
1171 (defcustom org-keep-stored-link-after-insertion nil
1172 "Non-nil means, keep link in list for entire session.
1174 The command `org-store-link' adds a link pointing to the current
1175 location to an internal list. These links accumulate during a session.
1176 The command `org-insert-link' can be used to insert links into any
1177 Org-mode file (offering completion for all stored links). When this
1178 option is nil, every link which has been inserted once using \\[org-insert-link]
1179 will be removed from the list, to make completing the unused links
1180 more efficient."
1181 :group 'org-link-store
1182 :type 'boolean)
1184 (defgroup org-link-follow nil
1185 "Options concerning following links in Org-mode."
1186 :tag "Org Follow Link"
1187 :group 'org-link)
1189 (defcustom org-link-translation-function nil
1190 "Function to translate links with different syntax to Org syntax.
1191 This can be used to translate links created for example by the Planner
1192 or emacs-wiki packages to Org syntax.
1193 The function must accept two parameters, a TYPE containing the link
1194 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1195 which is everything after the link protocol. It should return a cons
1196 with possibly modified values of type and path.
1197 Org contains a function for this, so if you set this variable to
1198 `org-translate-link-from-planner', you should be able follow many
1199 links created by planner."
1200 :group 'org-link-follow
1201 :type 'function)
1203 (defcustom org-follow-link-hook nil
1204 "Hook that is run after a link has been followed."
1205 :group 'org-link-follow
1206 :type 'hook)
1208 (defcustom org-tab-follows-link nil
1209 "Non-nil means, on links TAB will follow the link.
1210 Needs to be set before org.el is loaded.
1211 This really should not be used, it does not make sense, and the
1212 implementation is bad."
1213 :group 'org-link-follow
1214 :type 'boolean)
1216 (defcustom org-return-follows-link nil
1217 "Non-nil means, on links RET will follow the link.
1218 Needs to be set before org.el is loaded."
1219 :group 'org-link-follow
1220 :type 'boolean)
1222 (defcustom org-mouse-1-follows-link
1223 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1224 "Non-nil means, mouse-1 on a link will follow the link.
1225 A longer mouse click will still set point. Does not work on XEmacs.
1226 Needs to be set before org.el is loaded."
1227 :group 'org-link-follow
1228 :type 'boolean)
1230 (defcustom org-mark-ring-length 4
1231 "Number of different positions to be recorded in the ring
1232 Changing this requires a restart of Emacs to work correctly."
1233 :group 'org-link-follow
1234 :type 'integer)
1236 (defcustom org-link-frame-setup
1237 '((vm . vm-visit-folder-other-frame)
1238 (gnus . gnus-other-frame)
1239 (file . find-file-other-window))
1240 "Setup the frame configuration for following links.
1241 When following a link with Emacs, it may often be useful to display
1242 this link in another window or frame. This variable can be used to
1243 set this up for the different types of links.
1244 For VM, use any of
1245 `vm-visit-folder'
1246 `vm-visit-folder-other-frame'
1247 For Gnus, use any of
1248 `gnus'
1249 `gnus-other-frame'
1250 `org-gnus-no-new-news'
1251 For FILE, use any of
1252 `find-file'
1253 `find-file-other-window'
1254 `find-file-other-frame'
1255 For the calendar, use the variable `calendar-setup'.
1256 For BBDB, it is currently only possible to display the matches in
1257 another window."
1258 :group 'org-link-follow
1259 :type '(list
1260 (cons (const vm)
1261 (choice
1262 (const vm-visit-folder)
1263 (const vm-visit-folder-other-window)
1264 (const vm-visit-folder-other-frame)))
1265 (cons (const gnus)
1266 (choice
1267 (const gnus)
1268 (const gnus-other-frame)
1269 (const org-gnus-no-new-news)))
1270 (cons (const file)
1271 (choice
1272 (const find-file)
1273 (const find-file-other-window)
1274 (const find-file-other-frame)))))
1276 (defcustom org-display-internal-link-with-indirect-buffer nil
1277 "Non-nil means, use indirect buffer to display infile links.
1278 Activating internal links (from one location in a file to another location
1279 in the same file) normally just jumps to the location. When the link is
1280 activated with a C-u prefix (or with mouse-3), the link is displayed in
1281 another window. When this option is set, the other window actually displays
1282 an indirect buffer clone of the current buffer, to avoid any visibility
1283 changes to the current buffer."
1284 :group 'org-link-follow
1285 :type 'boolean)
1287 (defcustom org-open-non-existing-files nil
1288 "Non-nil means, `org-open-file' will open non-existing files.
1289 When nil, an error will be generated.
1290 This variable applies only to external applications because they
1291 might choke on non-existing files. If the link is to a file that
1292 will be openend in Emacs, the variable is ignored."
1293 :group 'org-link-follow
1294 :type 'boolean)
1296 (defcustom org-open-directory-means-index-dot-org nil
1297 "Non-nil means, a link to a directory really means to index.org.
1298 When nil, following a directory link will run dired or open a finder/explorer
1299 window on that directory."
1300 :group 'org-link-follow
1301 :type 'boolean)
1303 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1304 "Function and arguments to call for following mailto links.
1305 This is a list with the first element being a lisp function, and the
1306 remaining elements being arguments to the function. In string arguments,
1307 %a will be replaced by the address, and %s will be replaced by the subject
1308 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1309 :group 'org-link-follow
1310 :type '(choice
1311 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1312 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1313 (const :tag "message-mail" (message-mail "%a" "%s"))
1314 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1316 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1317 "Non-nil means, ask for confirmation before executing shell links.
1318 Shell links can be dangerous: just think about a link
1320 [[shell:rm -rf ~/*][Google Search]]
1322 This link would show up in your Org-mode document as \"Google Search\",
1323 but really it would remove your entire home directory.
1324 Therefore we advise against setting this variable to nil.
1325 Just change it to `y-or-n-p' if you want to confirm with a
1326 single keystroke rather than having to type \"yes\"."
1327 :group 'org-link-follow
1328 :type '(choice
1329 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1330 (const :tag "with y-or-n (faster)" y-or-n-p)
1331 (const :tag "no confirmation (dangerous)" nil)))
1333 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1334 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1335 Elisp links can be dangerous: just think about a link
1337 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1339 This link would show up in your Org-mode document as \"Google Search\",
1340 but really it would remove your entire home directory.
1341 Therefore we advise against setting this variable to nil.
1342 Just change it to `y-or-n-p' if you want to confirm with a
1343 single keystroke rather than having to type \"yes\"."
1344 :group 'org-link-follow
1345 :type '(choice
1346 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1347 (const :tag "with y-or-n (faster)" y-or-n-p)
1348 (const :tag "no confirmation (dangerous)" nil)))
1350 (defconst org-file-apps-defaults-gnu
1351 '((remote . emacs)
1352 (system . mailcap)
1353 (t . mailcap))
1354 "Default file applications on a UNIX or GNU/Linux system.
1355 See `org-file-apps'.")
1357 (defconst org-file-apps-defaults-macosx
1358 '((remote . emacs)
1359 (t . "open %s")
1360 (system . "open %s")
1361 ("ps.gz" . "gv %s")
1362 ("eps.gz" . "gv %s")
1363 ("dvi" . "xdvi %s")
1364 ("fig" . "xfig %s"))
1365 "Default file applications on a MacOS X system.
1366 The system \"open\" is known as a default, but we use X11 applications
1367 for some files for which the OS does not have a good default.
1368 See `org-file-apps'.")
1370 (defconst org-file-apps-defaults-windowsnt
1371 (list
1372 '(remote . emacs)
1373 (cons t
1374 (list (if (featurep 'xemacs)
1375 'mswindows-shell-execute
1376 'w32-shell-execute)
1377 "open" 'file))
1378 (cons 'system
1379 (list (if (featurep 'xemacs)
1380 'mswindows-shell-execute
1381 'w32-shell-execute)
1382 "open" 'file)))
1383 "Default file applications on a Windows NT system.
1384 The system \"open\" is used for most files.
1385 See `org-file-apps'.")
1387 (defcustom org-file-apps
1389 (auto-mode . emacs)
1390 ("\\.x?html?\\'" . default)
1391 ("\\.pdf\\'" . default)
1393 "External applications for opening `file:path' items in a document.
1394 Org-mode uses system defaults for different file types, but
1395 you can use this variable to set the application for a given file
1396 extension. The entries in this list are cons cells where the car identifies
1397 files and the cdr the corresponding command. Possible values for the
1398 file identifier are
1399 \"regex\" Regular expression matched against the file name. For backward
1400 compatibility, this can also be a string with only alphanumeric
1401 characters, which is then interpreted as an extension.
1402 `directory' Matches a directory
1403 `remote' Matches a remote file, accessible through tramp or efs.
1404 Remote files most likely should be visited through Emacs
1405 because external applications cannot handle such paths.
1406 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1407 so all files Emacs knows how to handle. Using this with
1408 command `emacs' will open most files in Emacs. Beware that this
1409 will also open html files inside Emacs, unless you add
1410 (\"html\" . default) to the list as well.
1411 t Default for files not matched by any of the other options.
1412 `system' The system command to open files, like `open' on Windows
1413 and Mac OS X, and mailcap under GNU/Linux. This is the command
1414 that will be selected if you call `C-c C-o' with a double
1415 `C-u C-u' prefix.
1417 Possible values for the command are:
1418 `emacs' The file will be visited by the current Emacs process.
1419 `default' Use the default application for this file type, which is the
1420 association for t in the list, most likely in the system-specific
1421 part.
1422 This can be used to overrule an unwanted setting in the
1423 system-specific variable.
1424 `system' Use the system command for opening files, like \"open\".
1425 This command is specified by the entry whose car is `system'.
1426 Most likely, the system-specific version of this variable
1427 does define this command, but you can overrule/replace it
1428 here.
1429 string A command to be executed by a shell; %s will be replaced
1430 by the path to the file.
1431 sexp A Lisp form which will be evaluated. The file path will
1432 be available in the Lisp variable `file'.
1433 For more examples, see the system specific constants
1434 `org-file-apps-defaults-macosx'
1435 `org-file-apps-defaults-windowsnt'
1436 `org-file-apps-defaults-gnu'."
1437 :group 'org-link-follow
1438 :type '(repeat
1439 (cons (choice :value ""
1440 (string :tag "Extension")
1441 (const :tag "System command to open files" system)
1442 (const :tag "Default for unrecognized files" t)
1443 (const :tag "Remote file" remote)
1444 (const :tag "Links to a directory" directory)
1445 (const :tag "Any files that have Emacs modes"
1446 auto-mode))
1447 (choice :value ""
1448 (const :tag "Visit with Emacs" emacs)
1449 (const :tag "Use default" default)
1450 (const :tag "Use the system command" system)
1451 (string :tag "Command")
1452 (sexp :tag "Lisp form")))))
1454 (defgroup org-refile nil
1455 "Options concerning refiling entries in Org-mode."
1456 :tag "Org Refile"
1457 :group 'org)
1459 (defcustom org-directory "~/org"
1460 "Directory with org files.
1461 This is just a default location to look for Org files. There is no need
1462 at all to put your files into this directory. It is only used in the
1463 following situations:
1465 1. When a remember template specifies a target file that is not an
1466 absolute path. The path will then be interpreted relative to
1467 `org-directory'
1468 2. When a remember note is filed away in an interactive way (when exiting the
1469 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1470 with `org-directory' as the default path."
1471 :group 'org-refile
1472 :group 'org-remember
1473 :type 'directory)
1475 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1476 "Default target for storing notes.
1477 Used by the hooks for remember.el. This can be a string, or nil to mean
1478 the value of `remember-data-file'.
1479 You can set this on a per-template basis with the variable
1480 `org-remember-templates'."
1481 :group 'org-refile
1482 :group 'org-remember
1483 :type '(choice
1484 (const :tag "Default from remember-data-file" nil)
1485 file))
1487 (defcustom org-goto-interface 'outline
1488 "The default interface to be used for `org-goto'.
1489 Allowed values are:
1490 outline The interface shows an outline of the relevant file
1491 and the correct heading is found by moving through
1492 the outline or by searching with incremental search.
1493 outline-path-completion Headlines in the current buffer are offered via
1494 completion. This is the interface also used by
1495 the refile command."
1496 :group 'org-refile
1497 :type '(choice
1498 (const :tag "Outline" outline)
1499 (const :tag "Outline-path-completion" outline-path-completion)))
1501 (defcustom org-goto-max-level 5
1502 "Maximum level to be considered when running org-goto with refile interface."
1503 :group 'org-refile
1504 :type 'integer)
1506 (defcustom org-reverse-note-order nil
1507 "Non-nil means, store new notes at the beginning of a file or entry.
1508 When nil, new notes will be filed to the end of a file or entry.
1509 This can also be a list with cons cells of regular expressions that
1510 are matched against file names, and values."
1511 :group 'org-remember
1512 :group 'org-refile
1513 :type '(choice
1514 (const :tag "Reverse always" t)
1515 (const :tag "Reverse never" nil)
1516 (repeat :tag "By file name regexp"
1517 (cons regexp boolean))))
1519 (defcustom org-refile-targets nil
1520 "Targets for refiling entries with \\[org-refile].
1521 This is list of cons cells. Each cell contains:
1522 - a specification of the files to be considered, either a list of files,
1523 or a symbol whose function or variable value will be used to retrieve
1524 a file name or a list of file names. If you use `org-agenda-files' for
1525 that, all agenda files will be scanned for targets. Nil means, consider
1526 headings in the current buffer.
1527 - A specification of how to find candidate refile targets. This may be
1528 any of:
1529 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1530 This tag has to be present in all target headlines, inheritance will
1531 not be considered.
1532 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1533 todo keyword.
1534 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1535 headlines that are refiling targets.
1536 - a cons cell (:level . N). Any headline of level N is considered a target.
1537 Note that, when `org-odd-levels-only' is set, level corresponds to
1538 order in hierarchy, not to the number of stars.
1539 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1540 Note that, when `org-odd-levels-only' is set, level corresponds to
1541 order in hierarchy, not to the number of stars.
1543 You can set the variable `org-refile-target-verify-function' to a function
1544 to verify each headline found by the simple critery above.
1546 When this variable is nil, all top-level headlines in the current buffer
1547 are used, equivalent to the value `((nil . (:level . 1))'."
1548 :group 'org-refile
1549 :type '(repeat
1550 (cons
1551 (choice :value org-agenda-files
1552 (const :tag "All agenda files" org-agenda-files)
1553 (const :tag "Current buffer" nil)
1554 (function) (variable) (file))
1555 (choice :tag "Identify target headline by"
1556 (cons :tag "Specific tag" (const :value :tag) (string))
1557 (cons :tag "TODO keyword" (const :value :todo) (string))
1558 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1559 (cons :tag "Level number" (const :value :level) (integer))
1560 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1562 (defcustom org-refile-target-verify-function nil
1563 "Function to verify if the headline at point should be a refile target.
1564 The function will be called without arguments, with point at the
1565 beginning of the headline. It should return t and leave point
1566 where it is if the headline is a valid target for refiling.
1568 If the target should not be selected, the function must return nil.
1569 In addition to this, it may move point to a place from where the search
1570 should be continued. For example, the function may decide that the entire
1571 subtree of the current entry should be excluded and move point to the end
1572 of the subtree."
1573 :group 'org-refile
1574 :type 'function)
1576 (defcustom org-refile-use-outline-path nil
1577 "Non-nil means, provide refile targets as paths.
1578 So a level 3 headline will be available as level1/level2/level3.
1580 When the value is `file', also include the file name (without directory)
1581 into the path. In this case, you can also stop the completion after
1582 the file name, to get entries inserted as top level in the file.
1584 When `full-file-path', include the full file path."
1585 :group 'org-refile
1586 :type '(choice
1587 (const :tag "Not" nil)
1588 (const :tag "Yes" t)
1589 (const :tag "Start with file name" file)
1590 (const :tag "Start with full file path" full-file-path)))
1592 (defcustom org-outline-path-complete-in-steps t
1593 "Non-nil means, complete the outline path in hierarchical steps.
1594 When Org-mode uses the refile interface to select an outline path
1595 \(see variable `org-refile-use-outline-path'), the completion of
1596 the path can be done is a single go, or if can be done in steps down
1597 the headline hierarchy. Going in steps is probably the best if you
1598 do not use a special completion package like `ido' or `icicles'.
1599 However, when using these packages, going in one step can be very
1600 fast, while still showing the whole path to the entry."
1601 :group 'org-refile
1602 :type 'boolean)
1604 (defcustom org-refile-allow-creating-parent-nodes nil
1605 "Non-nil means, allow to create new nodes as refile targets.
1606 New nodes are then created by adding \"/new node name\" to the completion
1607 of an existing node. When the value of this variable is `confirm',
1608 new node creation must be confirmed by the user (recommended)
1609 When nil, the completion must match an existing entry.
1611 Note that, if the new heading is not seen by the criteria
1612 listed in `org-refile-targets', multiple instances of the same
1613 heading would be created by trying again to file under the new
1614 heading."
1615 :group 'org-refile
1616 :type '(choice
1617 (const :tag "Never" nil)
1618 (const :tag "Always" t)
1619 (const :tag "Prompt for confirmation" confirm)))
1621 (defgroup org-todo nil
1622 "Options concerning TODO items in Org-mode."
1623 :tag "Org TODO"
1624 :group 'org)
1626 (defgroup org-progress nil
1627 "Options concerning Progress logging in Org-mode."
1628 :tag "Org Progress"
1629 :group 'org-time)
1631 (defvar org-todo-interpretation-widgets
1633 (:tag "Sequence (cycling hits every state)" sequence)
1634 (:tag "Type (cycling directly to DONE)" type))
1635 "The available interpretation symbols for customizing
1636 `org-todo-keywords'.
1637 Interested libraries should add to this list.")
1639 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1640 "List of TODO entry keyword sequences and their interpretation.
1641 \\<org-mode-map>This is a list of sequences.
1643 Each sequence starts with a symbol, either `sequence' or `type',
1644 indicating if the keywords should be interpreted as a sequence of
1645 action steps, or as different types of TODO items. The first
1646 keywords are states requiring action - these states will select a headline
1647 for inclusion into the global TODO list Org-mode produces. If one of
1648 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1649 signify that no further action is necessary. If \"|\" is not found,
1650 the last keyword is treated as the only DONE state of the sequence.
1652 The command \\[org-todo] cycles an entry through these states, and one
1653 additional state where no keyword is present. For details about this
1654 cycling, see the manual.
1656 TODO keywords and interpretation can also be set on a per-file basis with
1657 the special #+SEQ_TODO and #+TYP_TODO lines.
1659 Each keyword can optionally specify a character for fast state selection
1660 \(in combination with the variable `org-use-fast-todo-selection')
1661 and specifiers for state change logging, using the same syntax
1662 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1663 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1664 indicates to record a time stamp each time this state is selected.
1666 Each keyword may also specify if a timestamp or a note should be
1667 recorded when entering or leaving the state, by adding additional
1668 characters in the parenthesis after the keyword. This looks like this:
1669 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1670 record only the time of the state change. With X and Y being either
1671 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1672 Y when leaving the state if and only if the *target* state does not
1673 define X. You may omit any of the fast-selection key or X or /Y,
1674 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1676 For backward compatibility, this variable may also be just a list
1677 of keywords - in this case the interpretation (sequence or type) will be
1678 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1679 :group 'org-todo
1680 :group 'org-keywords
1681 :type '(choice
1682 (repeat :tag "Old syntax, just keywords"
1683 (string :tag "Keyword"))
1684 (repeat :tag "New syntax"
1685 (cons
1686 (choice
1687 :tag "Interpretation"
1688 ;;Quick and dirty way to see
1689 ;;`org-todo-interpretations'. This takes the
1690 ;;place of item arguments
1691 :convert-widget
1692 (lambda (widget)
1693 (widget-put widget
1694 :args (mapcar
1695 #'(lambda (x)
1696 (widget-convert
1697 (cons 'const x)))
1698 org-todo-interpretation-widgets))
1699 widget))
1700 (repeat
1701 (string :tag "Keyword"))))))
1703 (defvar org-todo-keywords-1 nil
1704 "All TODO and DONE keywords active in a buffer.")
1705 (make-variable-buffer-local 'org-todo-keywords-1)
1706 (defvar org-todo-keywords-for-agenda nil)
1707 (defvar org-done-keywords-for-agenda nil)
1708 (defvar org-todo-keyword-alist-for-agenda nil)
1709 (defvar org-tag-alist-for-agenda nil)
1710 (defvar org-agenda-contributing-files nil)
1711 (defvar org-not-done-keywords nil)
1712 (make-variable-buffer-local 'org-not-done-keywords)
1713 (defvar org-done-keywords nil)
1714 (make-variable-buffer-local 'org-done-keywords)
1715 (defvar org-todo-heads nil)
1716 (make-variable-buffer-local 'org-todo-heads)
1717 (defvar org-todo-sets nil)
1718 (make-variable-buffer-local 'org-todo-sets)
1719 (defvar org-todo-log-states nil)
1720 (make-variable-buffer-local 'org-todo-log-states)
1721 (defvar org-todo-kwd-alist nil)
1722 (make-variable-buffer-local 'org-todo-kwd-alist)
1723 (defvar org-todo-key-alist nil)
1724 (make-variable-buffer-local 'org-todo-key-alist)
1725 (defvar org-todo-key-trigger nil)
1726 (make-variable-buffer-local 'org-todo-key-trigger)
1728 (defcustom org-todo-interpretation 'sequence
1729 "Controls how TODO keywords are interpreted.
1730 This variable is in principle obsolete and is only used for
1731 backward compatibility, if the interpretation of todo keywords is
1732 not given already in `org-todo-keywords'. See that variable for
1733 more information."
1734 :group 'org-todo
1735 :group 'org-keywords
1736 :type '(choice (const sequence)
1737 (const type)))
1739 (defcustom org-use-fast-todo-selection t
1740 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1741 This variable describes if and under what circumstances the cycling
1742 mechanism for TODO keywords will be replaced by a single-key, direct
1743 selection scheme.
1745 When nil, fast selection is never used.
1747 When the symbol `prefix', it will be used when `org-todo' is called with
1748 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1749 in an agenda buffer.
1751 When t, fast selection is used by default. In this case, the prefix
1752 argument forces cycling instead.
1754 In all cases, the special interface is only used if access keys have actually
1755 been assigned by the user, i.e. if keywords in the configuration are followed
1756 by a letter in parenthesis, like TODO(t)."
1757 :group 'org-todo
1758 :type '(choice
1759 (const :tag "Never" nil)
1760 (const :tag "By default" t)
1761 (const :tag "Only with C-u C-c C-t" prefix)))
1763 (defcustom org-provide-todo-statistics t
1764 "Non-nil means, update todo statistics after insert and toggle.
1765 ALL-HEADLINES means update todo statistics by including headlines
1766 with no TODO keyword as well, counting them as not done.
1767 A list of TODO keywords means the same, but skip keywords that are
1768 not in this list.
1770 When this is set, todo statistics is updated in the parent of the
1771 current entry each time a todo state is changed."
1772 :group 'org-todo
1773 :type '(choice
1774 (const :tag "Yes, only for TODO entries" t)
1775 (const :tag "Yes, including all entries" 'all-headlines)
1776 (repeat :tag "Yes, for TODOs in this list"
1777 (string :tag "TODO keyword"))
1778 (other :tag "No TODO statistics" nil)))
1780 (defcustom org-hierarchical-todo-statistics t
1781 "Non-nil means, TODO statistics covers just direct children.
1782 When nil, all entries in the subtree are considered.
1783 This has only an effect if `org-provide-todo-statistics' is set.
1784 To set this to nil for only a single subtree, use a COOKIE_DATA
1785 property and include the word \"recursive\" into the value."
1786 :group 'org-todo
1787 :type 'boolean)
1789 (defcustom org-after-todo-state-change-hook nil
1790 "Hook which is run after the state of a TODO item was changed.
1791 The new state (a string with a TODO keyword, or nil) is available in the
1792 Lisp variable `state'."
1793 :group 'org-todo
1794 :type 'hook)
1796 (defvar org-blocker-hook nil
1797 "Hook for functions that are allowed to block a state change.
1799 Each function gets as its single argument a property list, see
1800 `org-trigger-hook' for more information about this list.
1802 If any of the functions in this hook returns nil, the state change
1803 is blocked.")
1805 (defvar org-trigger-hook nil
1806 "Hook for functions that are triggered by a state change.
1808 Each function gets as its single argument a property list with at least
1809 the following elements:
1811 (:type type-of-change :position pos-at-entry-start
1812 :from old-state :to new-state)
1814 Depending on the type, more properties may be present.
1816 This mechanism is currently implemented for:
1818 TODO state changes
1819 ------------------
1820 :type todo-state-change
1821 :from previous state (keyword as a string), or nil, or a symbol
1822 'todo' or 'done', to indicate the general type of state.
1823 :to new state, like in :from")
1825 (defcustom org-enforce-todo-dependencies nil
1826 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1827 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1828 be blocked if any prior sibling is not yet done.
1829 Finally, if the parent is blocked because of ordered siblings of its own,
1830 the child will also be blocked.
1831 This variable needs to be set before org.el is loaded, and you need to
1832 restart Emacs after a change to make the change effective. The only way
1833 to change is while Emacs is running is through the customize interface."
1834 :set (lambda (var val)
1835 (set var val)
1836 (if val
1837 (add-hook 'org-blocker-hook
1838 'org-block-todo-from-children-or-siblings-or-parent)
1839 (remove-hook 'org-blocker-hook
1840 'org-block-todo-from-children-or-siblings-or-parent)))
1841 :group 'org-todo
1842 :type 'boolean)
1844 (defcustom org-enforce-todo-checkbox-dependencies nil
1845 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1846 When this is nil, checkboxes have no influence on switching TODO states.
1847 When non-nil, you first need to check off all check boxes before the TODO
1848 entry can be switched to DONE.
1849 This variable needs to be set before org.el is loaded, and you need to
1850 restart Emacs after a change to make the change effective. The only way
1851 to change is while Emacs is running is through the customize interface."
1852 :set (lambda (var val)
1853 (set var val)
1854 (if val
1855 (add-hook 'org-blocker-hook
1856 'org-block-todo-from-checkboxes)
1857 (remove-hook 'org-blocker-hook
1858 'org-block-todo-from-checkboxes)))
1859 :group 'org-todo
1860 :type 'boolean)
1862 (defcustom org-treat-insert-todo-heading-as-state-change nil
1863 "Non-nil means, inserting a TODO heading is treated as state change.
1864 So when the command \\[org-insert-todo-heading] is used, state change
1865 logging will apply if appropriate. When nil, the new TODO item will
1866 be inserted directly, and no logging will take place."
1867 :group 'org-todo
1868 :type 'boolean)
1870 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1871 "Non-nil means, switching TODO states with S-cursor counts as state change.
1872 This is the default behavior. However, setting this to nil allows a
1873 convenient way to select a TODO state and bypass any logging associated
1874 with that."
1875 :group 'org-todo
1876 :type 'boolean)
1878 (defcustom org-todo-state-tags-triggers nil
1879 "Tag changes that should be triggered by TODO state changes.
1880 This is a list. Each entry is
1882 (state-change (tag . flag) .......)
1884 State-change can be a string with a state, and empty string to indicate the
1885 state that has no TODO keyword, or it can be one of the symbols `todo'
1886 or `done', meaning any not-done or done state, respectively."
1887 :group 'org-todo
1888 :group 'org-tags
1889 :type '(repeat
1890 (cons (choice :tag "When changing to"
1891 (const :tag "Not-done state" todo)
1892 (const :tag "Done state" done)
1893 (string :tag "State"))
1894 (repeat
1895 (cons :tag "Tag action"
1896 (string :tag "Tag")
1897 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1899 (defcustom org-log-done nil
1900 "Information to record when a task moves to the DONE state.
1902 Possible values are:
1904 nil Don't add anything, just change the keyword
1905 time Add a time stamp to the task
1906 note Prompt a closing note and add it with template `org-log-note-headings'
1908 This option can also be set with on a per-file-basis with
1910 #+STARTUP: nologdone
1911 #+STARTUP: logdone
1912 #+STARTUP: lognotedone
1914 You can have local logging settings for a subtree by setting the LOGGING
1915 property to one or more of these keywords."
1916 :group 'org-todo
1917 :group 'org-progress
1918 :type '(choice
1919 (const :tag "No logging" nil)
1920 (const :tag "Record CLOSED timestamp" time)
1921 (const :tag "Record CLOSED timestamp with closing note." note)))
1923 ;; Normalize old uses of org-log-done.
1924 (cond
1925 ((eq org-log-done t) (setq org-log-done 'time))
1926 ((and (listp org-log-done) (memq 'done org-log-done))
1927 (setq org-log-done 'note)))
1929 (defcustom org-log-note-clock-out nil
1930 "Non-nil means, record a note when clocking out of an item.
1931 This can also be configured on a per-file basis by adding one of
1932 the following lines anywhere in the buffer:
1934 #+STARTUP: lognoteclock-out
1935 #+STARTUP: nolognoteclock-out"
1936 :group 'org-todo
1937 :group 'org-progress
1938 :type 'boolean)
1940 (defcustom org-log-done-with-time t
1941 "Non-nil means, the CLOSED time stamp will contain date and time.
1942 When nil, only the date will be recorded."
1943 :group 'org-progress
1944 :type 'boolean)
1946 (defcustom org-log-note-headings
1947 '((done . "CLOSING NOTE %t")
1948 (state . "State %-12s from %-12S %t")
1949 (note . "Note taken on %t")
1950 (clock-out . ""))
1951 "Headings for notes added to entries.
1952 The value is an alist, with the car being a symbol indicating the note
1953 context, and the cdr is the heading to be used. The heading may also be the
1954 empty string.
1955 %t in the heading will be replaced by a time stamp.
1956 %s will be replaced by the new TODO state, in double quotes.
1957 %S will be replaced by the old TODO state, in double quotes.
1958 %u will be replaced by the user name.
1959 %U will be replaced by the full user name."
1960 :group 'org-todo
1961 :group 'org-progress
1962 :type '(list :greedy t
1963 (cons (const :tag "Heading when closing an item" done) string)
1964 (cons (const :tag
1965 "Heading when changing todo state (todo sequence only)"
1966 state) string)
1967 (cons (const :tag "Heading when just taking a note" note) string)
1968 (cons (const :tag "Heading when clocking out" clock-out) string)))
1970 (unless (assq 'note org-log-note-headings)
1971 (push '(note . "%t") org-log-note-headings))
1973 (defcustom org-log-into-drawer nil
1974 "Non-nil means, insert state change notes and time stamps into a drawer.
1975 When nil, state changes notes will be inserted after the headline and
1976 any scheduling and clock lines, but not inside a drawer.
1978 The value of this variable should be the name of the drawer to use.
1979 LOGBOOK is proposed at the default drawer for this purpose, you can
1980 also set this to a string to define the drawer of your choice.
1982 A value of t is also allowed, representing \"LOGBOOK\".
1984 If this variable is set, `org-log-state-notes-insert-after-drawers'
1985 will be ignored.
1987 You can set the property LOG_INTO_DRAWER to overrule this setting for
1988 a subtree."
1989 :group 'org-todo
1990 :group 'org-progress
1991 :type '(choice
1992 (const :tag "Not into a drawer" nil)
1993 (const :tag "LOGBOOK" t)
1994 (string :tag "Other")))
1996 (if (fboundp 'defvaralias)
1997 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1999 (defun org-log-into-drawer ()
2000 "Return the value of `org-log-into-drawer', but let properties overrule.
2001 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2002 used instead of the default value."
2003 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2004 (cond
2005 ((or (not p) (equal p "nil")) org-log-into-drawer)
2006 ((equal p "t") "LOGBOOK")
2007 (t p))))
2009 (defcustom org-log-state-notes-insert-after-drawers nil
2010 "Non-nil means, insert state change notes after any drawers in entry.
2011 Only the drawers that *immediately* follow the headline and the
2012 deadline/scheduled line are skipped.
2013 When nil, insert notes right after the heading and perhaps the line
2014 with deadline/scheduling if present.
2016 This variable will have no effect if `org-log-into-drawer' is
2017 set."
2018 :group 'org-todo
2019 :group 'org-progress
2020 :type 'boolean)
2022 (defcustom org-log-states-order-reversed t
2023 "Non-nil means, the latest state change note will be directly after heading.
2024 When nil, the notes will be orderer according to time."
2025 :group 'org-todo
2026 :group 'org-progress
2027 :type 'boolean)
2029 (defcustom org-log-repeat 'time
2030 "Non-nil means, record moving through the DONE state when triggering repeat.
2031 An auto-repeating task is immediately switched back to TODO when
2032 marked DONE. If you are not logging state changes (by adding \"@\"
2033 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2034 record a closing note, there will be no record of the task moving
2035 through DONE. This variable forces taking a note anyway.
2037 nil Don't force a record
2038 time Record a time stamp
2039 note Record a note
2041 This option can also be set with on a per-file-basis with
2043 #+STARTUP: logrepeat
2044 #+STARTUP: lognoterepeat
2045 #+STARTUP: nologrepeat
2047 You can have local logging settings for a subtree by setting the LOGGING
2048 property to one or more of these keywords."
2049 :group 'org-todo
2050 :group 'org-progress
2051 :type '(choice
2052 (const :tag "Don't force a record" nil)
2053 (const :tag "Force recording the DONE state" time)
2054 (const :tag "Force recording a note with the DONE state" note)))
2057 (defgroup org-priorities nil
2058 "Priorities in Org-mode."
2059 :tag "Org Priorities"
2060 :group 'org-todo)
2062 (defcustom org-enable-priority-commands t
2063 "Non-nil means, priority commands are active.
2064 When nil, these commands will be disabled, so that you never accidentally
2065 set a priority."
2066 :group 'org-priorities
2067 :type 'boolean)
2069 (defcustom org-highest-priority ?A
2070 "The highest priority of TODO items. A character like ?A, ?B etc.
2071 Must have a smaller ASCII number than `org-lowest-priority'."
2072 :group 'org-priorities
2073 :type 'character)
2075 (defcustom org-lowest-priority ?C
2076 "The lowest priority of TODO items. A character like ?A, ?B etc.
2077 Must have a larger ASCII number than `org-highest-priority'."
2078 :group 'org-priorities
2079 :type 'character)
2081 (defcustom org-default-priority ?B
2082 "The default priority of TODO items.
2083 This is the priority an item get if no explicit priority is given."
2084 :group 'org-priorities
2085 :type 'character)
2087 (defcustom org-priority-start-cycle-with-default t
2088 "Non-nil means, start with default priority when starting to cycle.
2089 When this is nil, the first step in the cycle will be (depending on the
2090 command used) one higher or lower that the default priority."
2091 :group 'org-priorities
2092 :type 'boolean)
2094 (defgroup org-time nil
2095 "Options concerning time stamps and deadlines in Org-mode."
2096 :tag "Org Time"
2097 :group 'org)
2099 (defcustom org-insert-labeled-timestamps-at-point nil
2100 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2101 When nil, these labeled time stamps are forces into the second line of an
2102 entry, just after the headline. When scheduling from the global TODO list,
2103 the time stamp will always be forced into the second line."
2104 :group 'org-time
2105 :type 'boolean)
2107 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2108 "Formats for `format-time-string' which are used for time stamps.
2109 It is not recommended to change this constant.")
2111 (defcustom org-time-stamp-rounding-minutes '(0 5)
2112 "Number of minutes to round time stamps to.
2113 These are two values, the first applies when first creating a time stamp.
2114 The second applies when changing it with the commands `S-up' and `S-down'.
2115 When changing the time stamp, this means that it will change in steps
2116 of N minutes, as given by the second value.
2118 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2119 numbers should be factors of 60, so for example 5, 10, 15.
2121 When this is larger than 1, you can still force an exact time-stamp by using
2122 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2123 and by using a prefix arg to `S-up/down' to specify the exact number
2124 of minutes to shift."
2125 :group 'org-time
2126 :get '(lambda (var) ; Make sure all entries have 5 elements
2127 (if (integerp (default-value var))
2128 (list (default-value var) 5)
2129 (default-value var)))
2130 :type '(list
2131 (integer :tag "when inserting times")
2132 (integer :tag "when modifying times")))
2134 ;; Normalize old customizations of this variable.
2135 (when (integerp org-time-stamp-rounding-minutes)
2136 (setq org-time-stamp-rounding-minutes
2137 (list org-time-stamp-rounding-minutes
2138 org-time-stamp-rounding-minutes)))
2140 (defcustom org-display-custom-times nil
2141 "Non-nil means, overlay custom formats over all time stamps.
2142 The formats are defined through the variable `org-time-stamp-custom-formats'.
2143 To turn this on on a per-file basis, insert anywhere in the file:
2144 #+STARTUP: customtime"
2145 :group 'org-time
2146 :set 'set-default
2147 :type 'sexp)
2148 (make-variable-buffer-local 'org-display-custom-times)
2150 (defcustom org-time-stamp-custom-formats
2151 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2152 "Custom formats for time stamps. See `format-time-string' for the syntax.
2153 These are overlayed over the default ISO format if the variable
2154 `org-display-custom-times' is set. Time like %H:%M should be at the
2155 end of the second format. The custom formats are also honored by export
2156 commands, if custom time display is turned on at the time of export."
2157 :group 'org-time
2158 :type 'sexp)
2160 (defun org-time-stamp-format (&optional long inactive)
2161 "Get the right format for a time string."
2162 (let ((f (if long (cdr org-time-stamp-formats)
2163 (car org-time-stamp-formats))))
2164 (if inactive
2165 (concat "[" (substring f 1 -1) "]")
2166 f)))
2168 (defcustom org-time-clocksum-format "%d:%02d"
2169 "The format string used when creating CLOCKSUM lines, or when
2170 org-mode generates a time duration."
2171 :group 'org-time
2172 :type 'string)
2174 (defcustom org-deadline-warning-days 14
2175 "No. of days before expiration during which a deadline becomes active.
2176 This variable governs the display in sparse trees and in the agenda.
2177 When 0 or negative, it means use this number (the absolute value of it)
2178 even if a deadline has a different individual lead time specified.
2180 Custom commands can set this variable in the options section."
2181 :group 'org-time
2182 :group 'org-agenda-daily/weekly
2183 :type 'integer)
2185 (defcustom org-read-date-prefer-future t
2186 "Non-nil means, assume future for incomplete date input from user.
2187 This affects the following situations:
2188 1. The user gives a day, but no month.
2189 For example, if today is the 15th, and you enter \"3\", Org-mode will
2190 read this as the third of *next* month. However, if you enter \"17\",
2191 it will be considered as *this* month.
2192 2. The user gives a month but not a year.
2193 For example, if it is april and you enter \"feb 2\", this will be read
2194 as feb 2, *next* year. \"May 5\", however, will be this year.
2196 Currently this does not work for ISO week specifications.
2198 When this option is nil, the current month and year will always be used
2199 as defaults."
2200 :group 'org-time
2201 :type 'boolean)
2203 (defcustom org-read-date-display-live t
2204 "Non-nil means, display current interpretation of date prompt live.
2205 This display will be in an overlay, in the minibuffer."
2206 :group 'org-time
2207 :type 'boolean)
2209 (defcustom org-read-date-popup-calendar t
2210 "Non-nil means, pop up a calendar when prompting for a date.
2211 In the calendar, the date can be selected with mouse-1. However, the
2212 minibuffer will also be active, and you can simply enter the date as well.
2213 When nil, only the minibuffer will be available."
2214 :group 'org-time
2215 :type 'boolean)
2216 (if (fboundp 'defvaralias)
2217 (defvaralias 'org-popup-calendar-for-date-prompt
2218 'org-read-date-popup-calendar))
2220 (defcustom org-read-date-minibuffer-setup-hook nil
2221 "Hook to be used to set up keys for the date/time interface.
2222 Add key definitions to `minibuffer-local-map', which will be a temporary
2223 copy."
2224 :group 'org-time
2225 :type 'hook)
2227 (defcustom org-extend-today-until 0
2228 "The hour when your day really ends. Must be an integer.
2229 This has influence for the following applications:
2230 - When switching the agenda to \"today\". It it is still earlier than
2231 the time given here, the day recognized as TODAY is actually yesterday.
2232 - When a date is read from the user and it is still before the time given
2233 here, the current date and time will be assumed to be yesterday, 23:59.
2234 Also, timestamps inserted in remember templates follow this rule.
2236 IMPORTANT: This is a feature whose implementation is and likely will
2237 remain incomplete. Really, it is only here because past midnight seems to
2238 be the favorite working time of John Wiegley :-)"
2239 :group 'org-time
2240 :type 'integer)
2242 (defcustom org-edit-timestamp-down-means-later nil
2243 "Non-nil means, S-down will increase the time in a time stamp.
2244 When nil, S-up will increase."
2245 :group 'org-time
2246 :type 'boolean)
2248 (defcustom org-calendar-follow-timestamp-change t
2249 "Non-nil means, make the calendar window follow timestamp changes.
2250 When a timestamp is modified and the calendar window is visible, it will be
2251 moved to the new date."
2252 :group 'org-time
2253 :type 'boolean)
2255 (defgroup org-tags nil
2256 "Options concerning tags in Org-mode."
2257 :tag "Org Tags"
2258 :group 'org)
2260 (defcustom org-tag-alist nil
2261 "List of tags allowed in Org-mode files.
2262 When this list is nil, Org-mode will base TAG input on what is already in the
2263 buffer.
2264 The value of this variable is an alist, the car of each entry must be a
2265 keyword as a string, the cdr may be a character that is used to select
2266 that tag through the fast-tag-selection interface.
2267 See the manual for details."
2268 :group 'org-tags
2269 :type '(repeat
2270 (choice
2271 (cons (string :tag "Tag name")
2272 (character :tag "Access char"))
2273 (const :tag "Start radio group" (:startgroup))
2274 (const :tag "End radio group" (:endgroup))
2275 (const :tag "New line" (:newline)))))
2277 (defcustom org-tag-persistent-alist nil
2278 "List of tags that will always appear in all Org-mode files.
2279 This is in addition to any in buffer settings or customizations
2280 of `org-tag-alist'.
2281 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2282 The value of this variable is an alist, the car of each entry must be a
2283 keyword as a string, the cdr may be a character that is used to select
2284 that tag through the fast-tag-selection interface.
2285 See the manual for details.
2286 To disable these tags on a per-file basis, insert anywhere in the file:
2287 #+STARTUP: noptag"
2288 :group 'org-tags
2289 :type '(repeat
2290 (choice
2291 (cons (string :tag "Tag name")
2292 (character :tag "Access char"))
2293 (const :tag "Start radio group" (:startgroup))
2294 (const :tag "End radio group" (:endgroup))
2295 (const :tag "New line" (:newline)))))
2297 (defvar org-file-tags nil
2298 "List of tags that can be inherited by all entries in the file.
2299 The tags will be inherited if the variable `org-use-tag-inheritance'
2300 says they should be.
2301 This variable is populated from #+TAG lines.")
2303 (defcustom org-use-fast-tag-selection 'auto
2304 "Non-nil means, use fast tag selection scheme.
2305 This is a special interface to select and deselect tags with single keys.
2306 When nil, fast selection is never used.
2307 When the symbol `auto', fast selection is used if and only if selection
2308 characters for tags have been configured, either through the variable
2309 `org-tag-alist' or through a #+TAGS line in the buffer.
2310 When t, fast selection is always used and selection keys are assigned
2311 automatically if necessary."
2312 :group 'org-tags
2313 :type '(choice
2314 (const :tag "Always" t)
2315 (const :tag "Never" nil)
2316 (const :tag "When selection characters are configured" 'auto)))
2318 (defcustom org-fast-tag-selection-single-key nil
2319 "Non-nil means, fast tag selection exits after first change.
2320 When nil, you have to press RET to exit it.
2321 During fast tag selection, you can toggle this flag with `C-c'.
2322 This variable can also have the value `expert'. In this case, the window
2323 displaying the tags menu is not even shown, until you press C-c again."
2324 :group 'org-tags
2325 :type '(choice
2326 (const :tag "No" nil)
2327 (const :tag "Yes" t)
2328 (const :tag "Expert" expert)))
2330 (defvar org-fast-tag-selection-include-todo nil
2331 "Non-nil means, fast tags selection interface will also offer TODO states.
2332 This is an undocumented feature, you should not rely on it.")
2334 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2335 "The column to which tags should be indented in a headline.
2336 If this number is positive, it specifies the column. If it is negative,
2337 it means that the tags should be flushright to that column. For example,
2338 -80 works well for a normal 80 character screen."
2339 :group 'org-tags
2340 :type 'integer)
2342 (defcustom org-auto-align-tags t
2343 "Non-nil means, realign tags after pro/demotion of TODO state change.
2344 These operations change the length of a headline and therefore shift
2345 the tags around. With this options turned on, after each such operation
2346 the tags are again aligned to `org-tags-column'."
2347 :group 'org-tags
2348 :type 'boolean)
2350 (defcustom org-use-tag-inheritance t
2351 "Non-nil means, tags in levels apply also for sublevels.
2352 When nil, only the tags directly given in a specific line apply there.
2353 This may also be a list of tags that should be inherited, or a regexp that
2354 matches tags that should be inherited. Additional control is possible
2355 with the variable `org-tags-exclude-from-inheritance' which gives an
2356 explicit list of tags to be excluded from inheritance., even if the value of
2357 `org-use-tag-inheritance' would select it for inheritance.
2359 If this option is t, a match early-on in a tree can lead to a large
2360 number of matches in the subtree when constructing the agenda or creating
2361 a sparse tree. If you only want to see the first match in a tree during
2362 a search, check out the variable `org-tags-match-list-sublevels'."
2363 :group 'org-tags
2364 :type '(choice
2365 (const :tag "Not" nil)
2366 (const :tag "Always" t)
2367 (repeat :tag "Specific tags" (string :tag "Tag"))
2368 (regexp :tag "Tags matched by regexp")))
2370 (defcustom org-tags-exclude-from-inheritance nil
2371 "List of tags that should never be inherited.
2372 This is a way to exclude a few tags from inheritance. For way to do
2373 the opposite, to actively allow inheritance for selected tags,
2374 see the variable `org-use-tag-inheritance'."
2375 :group 'org-tags
2376 :type '(repeat (string :tag "Tag")))
2378 (defun org-tag-inherit-p (tag)
2379 "Check if TAG is one that should be inherited."
2380 (cond
2381 ((member tag org-tags-exclude-from-inheritance) nil)
2382 ((eq org-use-tag-inheritance t) t)
2383 ((not org-use-tag-inheritance) nil)
2384 ((stringp org-use-tag-inheritance)
2385 (string-match org-use-tag-inheritance tag))
2386 ((listp org-use-tag-inheritance)
2387 (member tag org-use-tag-inheritance))
2388 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2390 (defcustom org-tags-match-list-sublevels t
2391 "Non-nil means list also sublevels of headlines matching a search.
2392 This variable applies to tags/property searches, and also to stuck
2393 projects because this search is based on a tags match as well.
2395 When set to the symbol `indented', sublevels are indented with
2396 leading dots.
2398 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2399 the sublevels of a headline matching a tag search often also match
2400 the same search. Listing all of them can create very long lists.
2401 Setting this variable to nil causes subtrees of a match to be skipped.
2403 This variable is semi-obsolete and probably should always be true. It
2404 is better to limit inheritance to certain tags using the variables
2405 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2406 :group 'org-tags
2407 :type '(choice
2408 (const :tag "No, don't list them" nil)
2409 (const :tag "Yes, do list them" t)
2410 (const :tag "List them, indented with leading dots" indented)))
2412 (defcustom org-tags-sort-function nil
2413 "When set, tags are sorted using this function as a comparator"
2414 :group 'org-tags
2415 :type '(choice
2416 (const :tag "No sorting" nil)
2417 (const :tag "Alphabetical" string<)
2418 (const :tag "Reverse alphabetical" string>)
2419 (function :tag "Custom function" nil)))
2421 (defvar org-tags-history nil
2422 "History of minibuffer reads for tags.")
2423 (defvar org-last-tags-completion-table nil
2424 "The last used completion table for tags.")
2425 (defvar org-after-tags-change-hook nil
2426 "Hook that is run after the tags in a line have changed.")
2428 (defgroup org-properties nil
2429 "Options concerning properties in Org-mode."
2430 :tag "Org Properties"
2431 :group 'org)
2433 (defcustom org-property-format "%-10s %s"
2434 "How property key/value pairs should be formatted by `indent-line'.
2435 When `indent-line' hits a property definition, it will format the line
2436 according to this format, mainly to make sure that the values are
2437 lined-up with respect to each other."
2438 :group 'org-properties
2439 :type 'string)
2441 (defcustom org-use-property-inheritance nil
2442 "Non-nil means, properties apply also for sublevels.
2444 This setting is chiefly used during property searches. Turning it on can
2445 cause significant overhead when doing a search, which is why it is not
2446 on by default.
2448 When nil, only the properties directly given in the current entry count.
2449 When t, every property is inherited. The value may also be a list of
2450 properties that should have inheritance, or a regular expression matching
2451 properties that should be inherited.
2453 However, note that some special properties use inheritance under special
2454 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2455 and the properties ending in \"_ALL\" when they are used as descriptor
2456 for valid values of a property.
2458 Note for programmers:
2459 When querying an entry with `org-entry-get', you can control if inheritance
2460 should be used. By default, `org-entry-get' looks only at the local
2461 properties. You can request inheritance by setting the inherit argument
2462 to t (to force inheritance) or to `selective' (to respect the setting
2463 in this variable)."
2464 :group 'org-properties
2465 :type '(choice
2466 (const :tag "Not" nil)
2467 (const :tag "Always" t)
2468 (repeat :tag "Specific properties" (string :tag "Property"))
2469 (regexp :tag "Properties matched by regexp")))
2471 (defun org-property-inherit-p (property)
2472 "Check if PROPERTY is one that should be inherited."
2473 (cond
2474 ((eq org-use-property-inheritance t) t)
2475 ((not org-use-property-inheritance) nil)
2476 ((stringp org-use-property-inheritance)
2477 (string-match org-use-property-inheritance property))
2478 ((listp org-use-property-inheritance)
2479 (member property org-use-property-inheritance))
2480 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2482 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2483 "The default column format, if no other format has been defined.
2484 This variable can be set on the per-file basis by inserting a line
2486 #+COLUMNS: %25ITEM ....."
2487 :group 'org-properties
2488 :type 'string)
2490 (defcustom org-columns-ellipses ".."
2491 "The ellipses to be used when a field in column view is truncated.
2492 When this is the empty string, as many characters as possible are shown,
2493 but then there will be no visual indication that the field has been truncated.
2494 When this is a string of length N, the last N characters of a truncated
2495 field are replaced by this string. If the column is narrower than the
2496 ellipses string, only part of the ellipses string will be shown."
2497 :group 'org-properties
2498 :type 'string)
2500 (defcustom org-columns-modify-value-for-display-function nil
2501 "Function that modifies values for display in column view.
2502 For example, it can be used to cut out a certain part from a time stamp.
2503 The function must take 2 arguments:
2505 column-title The title of the column (*not* the property name)
2506 value The value that should be modified.
2508 The function should return the value that should be displayed,
2509 or nil if the normal value should be used."
2510 :group 'org-properties
2511 :type 'function)
2513 (defcustom org-effort-property "Effort"
2514 "The property that is being used to keep track of effort estimates.
2515 Effort estimates given in this property need to have the format H:MM."
2516 :group 'org-properties
2517 :group 'org-progress
2518 :type '(string :tag "Property"))
2520 (defconst org-global-properties-fixed
2521 '(("VISIBILITY_ALL" . "folded children content all")
2522 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2523 "List of property/value pairs that can be inherited by any entry.
2525 These are fixed values, for the preset properties. The user variable
2526 that can be used to add to this list is `org-global-properties'.
2528 The entries in this list are cons cells where the car is a property
2529 name and cdr is a string with the value. If the value represents
2530 multiple items like an \"_ALL\" property, separate the items by
2531 spaces.")
2533 (defcustom org-global-properties nil
2534 "List of property/value pairs that can be inherited by any entry.
2536 This list will be combined with the constant `org-global-properties-fixed'.
2538 The entries in this list are cons cells where the car is a property
2539 name and cdr is a string with the value.
2541 You can set buffer-local values for the same purpose in the variable
2542 `org-file-properties' this by adding lines like
2544 #+PROPERTY: NAME VALUE"
2545 :group 'org-properties
2546 :type '(repeat
2547 (cons (string :tag "Property")
2548 (string :tag "Value"))))
2550 (defvar org-file-properties nil
2551 "List of property/value pairs that can be inherited by any entry.
2552 Valid for the current buffer.
2553 This variable is populated from #+PROPERTY lines.")
2554 (make-variable-buffer-local 'org-file-properties)
2556 (defgroup org-agenda nil
2557 "Options concerning agenda views in Org-mode."
2558 :tag "Org Agenda"
2559 :group 'org)
2561 (defvar org-category nil
2562 "Variable used by org files to set a category for agenda display.
2563 Such files should use a file variable to set it, for example
2565 # -*- mode: org; org-category: \"ELisp\"
2567 or contain a special line
2569 #+CATEGORY: ELisp
2571 If the file does not specify a category, then file's base name
2572 is used instead.")
2573 (make-variable-buffer-local 'org-category)
2574 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2576 (defcustom org-agenda-files nil
2577 "The files to be used for agenda display.
2578 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2579 \\[org-remove-file]. You can also use customize to edit the list.
2581 If an entry is a directory, all files in that directory that are matched by
2582 `org-agenda-file-regexp' will be part of the file list.
2584 If the value of the variable is not a list but a single file name, then
2585 the list of agenda files is actually stored and maintained in that file, one
2586 agenda file per line."
2587 :group 'org-agenda
2588 :type '(choice
2589 (repeat :tag "List of files and directories" file)
2590 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2592 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2593 "Regular expression to match files for `org-agenda-files'.
2594 If any element in the list in that variable contains a directory instead
2595 of a normal file, all files in that directory that are matched by this
2596 regular expression will be included."
2597 :group 'org-agenda
2598 :type 'regexp)
2600 (defcustom org-agenda-text-search-extra-files nil
2601 "List of extra files to be searched by text search commands.
2602 These files will be search in addition to the agenda files by the
2603 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2604 Note that these files will only be searched for text search commands,
2605 not for the other agenda views like todo lists, tag searches or the weekly
2606 agenda. This variable is intended to list notes and possibly archive files
2607 that should also be searched by these two commands.
2608 In fact, if the first element in the list is the symbol `agenda-archives',
2609 than all archive files of all agenda files will be added to the search
2610 scope."
2611 :group 'org-agenda
2612 :type '(set :greedy t
2613 (const :tag "Agenda Archives" agenda-archives)
2614 (repeat :inline t (file))))
2616 (if (fboundp 'defvaralias)
2617 (defvaralias 'org-agenda-multi-occur-extra-files
2618 'org-agenda-text-search-extra-files))
2620 (defcustom org-agenda-skip-unavailable-files nil
2621 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2622 A nil value means to remove them, after a query, from the list."
2623 :group 'org-agenda
2624 :type 'boolean)
2626 (defcustom org-calendar-to-agenda-key [?c]
2627 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2628 The command `org-calendar-goto-agenda' will be bound to this key. The
2629 default is the character `c' because then `c' can be used to switch back and
2630 forth between agenda and calendar."
2631 :group 'org-agenda
2632 :type 'sexp)
2634 (defcustom org-calendar-agenda-action-key [?k]
2635 "The key to be installed in `calendar-mode-map' for agenda-action.
2636 The command `org-agenda-action' will be bound to this key. The
2637 default is the character `k' because we use the same key in the agenda."
2638 :group 'org-agenda
2639 :type 'sexp)
2641 (eval-after-load "calendar"
2642 '(progn
2643 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2644 'org-calendar-goto-agenda)
2645 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2646 'org-agenda-action)))
2648 (defgroup org-latex nil
2649 "Options for embedding LaTeX code into Org-mode."
2650 :tag "Org LaTeX"
2651 :group 'org)
2653 (defcustom org-format-latex-options
2654 '(:foreground default :background default :scale 1.0
2655 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2656 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2657 "Options for creating images from LaTeX fragments.
2658 This is a property list with the following properties:
2659 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2660 `default' means use the foreground of the default face.
2661 :background the background color, or \"Transparent\".
2662 `default' means use the background of the default face.
2663 :scale a scaling factor for the size of the images.
2664 :html-foreground, :html-background, :html-scale
2665 the same numbers for HTML export.
2666 :matchers a list indicating which matchers should be used to
2667 find LaTeX fragments. Valid members of this list are:
2668 \"begin\" find environments
2669 \"$1\" find single characters surrounded by $.$
2670 \"$\" find math expressions surrounded by $...$
2671 \"$$\" find math expressions surrounded by $$....$$
2672 \"\\(\" find math expressions surrounded by \\(...\\)
2673 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2674 :group 'org-latex
2675 :type 'plist)
2677 (defcustom org-format-latex-header "\\documentclass{article}
2678 \\usepackage{fullpage} % do not remove
2679 \\usepackage{amssymb}
2680 \\usepackage[usenames]{color}
2681 \\usepackage{amsmath}
2682 \\usepackage{latexsym}
2683 \\usepackage[mathscr]{eucal}
2684 \\pagestyle{empty} % do not remove"
2685 "The document header used for processing LaTeX fragments."
2686 :group 'org-latex
2687 :type 'string)
2690 (defgroup org-font-lock nil
2691 "Font-lock settings for highlighting in Org-mode."
2692 :tag "Org Font Lock"
2693 :group 'org)
2695 (defcustom org-level-color-stars-only nil
2696 "Non-nil means fontify only the stars in each headline.
2697 When nil, the entire headline is fontified.
2698 Changing it requires restart of `font-lock-mode' to become effective
2699 also in regions already fontified."
2700 :group 'org-font-lock
2701 :type 'boolean)
2703 (defcustom org-hide-leading-stars nil
2704 "Non-nil means, hide the first N-1 stars in a headline.
2705 This works by using the face `org-hide' for these stars. This
2706 face is white for a light background, and black for a dark
2707 background. You may have to customize the face `org-hide' to
2708 make this work.
2709 Changing it requires restart of `font-lock-mode' to become effective
2710 also in regions already fontified.
2711 You may also set this on a per-file basis by adding one of the following
2712 lines to the buffer:
2714 #+STARTUP: hidestars
2715 #+STARTUP: showstars"
2716 :group 'org-font-lock
2717 :type 'boolean)
2719 (defcustom org-fontify-done-headline nil
2720 "Non-nil means, change the face of a headline if it is marked DONE.
2721 Normally, only the TODO/DONE keyword indicates the state of a headline.
2722 When this is non-nil, the headline after the keyword is set to the
2723 `org-headline-done' as an additional indication."
2724 :group 'org-font-lock
2725 :type 'boolean)
2727 (defcustom org-fontify-emphasized-text t
2728 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2729 Changing this variable requires a restart of Emacs to take effect."
2730 :group 'org-font-lock
2731 :type 'boolean)
2733 (defcustom org-fontify-whole-heading-line nil
2734 "Non-nil means fontify the whole line for headings.
2735 This is useful when setting a background color for the
2736 org-leve-* faces."
2737 :group 'org-font-lock
2738 :type 'boolean)
2740 (defcustom org-highlight-latex-fragments-and-specials nil
2741 "Non-nil means, fontify what is treated specially by the exporters."
2742 :group 'org-font-lock
2743 :type 'boolean)
2745 (defcustom org-hide-emphasis-markers nil
2746 "Non-nil mean font-lock should hide the emphasis marker characters."
2747 :group 'org-font-lock
2748 :type 'boolean)
2750 (defvar org-emph-re nil
2751 "Regular expression for matching emphasis.")
2752 (defvar org-verbatim-re nil
2753 "Regular expression for matching verbatim text.")
2754 (defvar org-emphasis-regexp-components) ; defined just below
2755 (defvar org-emphasis-alist) ; defined just below
2756 (defun org-set-emph-re (var val)
2757 "Set variable and compute the emphasis regular expression."
2758 (set var val)
2759 (when (and (boundp 'org-emphasis-alist)
2760 (boundp 'org-emphasis-regexp-components)
2761 org-emphasis-alist org-emphasis-regexp-components)
2762 (let* ((e org-emphasis-regexp-components)
2763 (pre (car e))
2764 (post (nth 1 e))
2765 (border (nth 2 e))
2766 (body (nth 3 e))
2767 (nl (nth 4 e))
2768 (body1 (concat body "*?"))
2769 (markers (mapconcat 'car org-emphasis-alist ""))
2770 (vmarkers (mapconcat
2771 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2772 org-emphasis-alist "")))
2773 ;; make sure special characters appear at the right position in the class
2774 (if (string-match "\\^" markers)
2775 (setq markers (concat (replace-match "" t t markers) "^")))
2776 (if (string-match "-" markers)
2777 (setq markers (concat (replace-match "" t t markers) "-")))
2778 (if (string-match "\\^" vmarkers)
2779 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2780 (if (string-match "-" vmarkers)
2781 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2782 (if (> nl 0)
2783 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2784 (int-to-string nl) "\\}")))
2785 ;; Make the regexp
2786 (setq org-emph-re
2787 (concat "\\([" pre "]\\|^\\)"
2788 "\\("
2789 "\\([" markers "]\\)"
2790 "\\("
2791 "[^" border "]\\|"
2792 "[^" border "]"
2793 body1
2794 "[^" border "]"
2795 "\\)"
2796 "\\3\\)"
2797 "\\([" post "]\\|$\\)"))
2798 (setq org-verbatim-re
2799 (concat "\\([" pre "]\\|^\\)"
2800 "\\("
2801 "\\([" vmarkers "]\\)"
2802 "\\("
2803 "[^" border "]\\|"
2804 "[^" border "]"
2805 body1
2806 "[^" border "]"
2807 "\\)"
2808 "\\3\\)"
2809 "\\([" post "]\\|$\\)")))))
2811 (defcustom org-emphasis-regexp-components
2812 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2813 "Components used to build the regular expression for emphasis.
2814 This is a list with 6 entries. Terminology: In an emphasis string
2815 like \" *strong word* \", we call the initial space PREMATCH, the final
2816 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2817 and \"trong wor\" is the body. The different components in this variable
2818 specify what is allowed/forbidden in each part:
2820 pre Chars allowed as prematch. Beginning of line will be allowed too.
2821 post Chars allowed as postmatch. End of line will be allowed too.
2822 border The chars *forbidden* as border characters.
2823 body-regexp A regexp like \".\" to match a body character. Don't use
2824 non-shy groups here, and don't allow newline here.
2825 newline The maximum number of newlines allowed in an emphasis exp.
2827 Use customize to modify this, or restart Emacs after changing it."
2828 :group 'org-font-lock
2829 :set 'org-set-emph-re
2830 :type '(list
2831 (sexp :tag "Allowed chars in pre ")
2832 (sexp :tag "Allowed chars in post ")
2833 (sexp :tag "Forbidden chars in border ")
2834 (sexp :tag "Regexp for body ")
2835 (integer :tag "number of newlines allowed")
2836 (option (boolean :tag "Please ignore this button"))))
2838 (defcustom org-emphasis-alist
2839 `(("*" bold "<b>" "</b>")
2840 ("/" italic "<i>" "</i>")
2841 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2842 ("=" org-code "<code>" "</code>" verbatim)
2843 ("~" org-verbatim "<code>" "</code>" verbatim)
2844 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2845 "<del>" "</del>")
2847 "Special syntax for emphasized text.
2848 Text starting and ending with a special character will be emphasized, for
2849 example *bold*, _underlined_ and /italic/. This variable sets the marker
2850 characters, the face to be used by font-lock for highlighting in Org-mode
2851 Emacs buffers, and the HTML tags to be used for this.
2852 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2853 Use customize to modify this, or restart Emacs after changing it."
2854 :group 'org-font-lock
2855 :set 'org-set-emph-re
2856 :type '(repeat
2857 (list
2858 (string :tag "Marker character")
2859 (choice
2860 (face :tag "Font-lock-face")
2861 (plist :tag "Face property list"))
2862 (string :tag "HTML start tag")
2863 (string :tag "HTML end tag")
2864 (option (const verbatim)))))
2866 (defvar org-protecting-blocks
2867 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2868 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2869 This is needed for font-lock setup.")
2871 ;;; Miscellaneous options
2873 (defgroup org-completion nil
2874 "Completion in Org-mode."
2875 :tag "Org Completion"
2876 :group 'org)
2878 (defcustom org-completion-use-ido nil
2879 "Non-nil means, use ido completion wherever possible.
2880 Note that `ido-mode' must be active for this variable to be relevant.
2881 If you decide to turn this variable on, you might well want to turn off
2882 `org-outline-path-complete-in-steps'.
2883 See also `org-completion-use-iswitchb'."
2884 :group 'org-completion
2885 :type 'boolean)
2887 (defcustom org-completion-use-iswitchb nil
2888 "Non-nil means, use iswitchb completion wherever possible.
2889 Note that `iswitchb-mode' must be active for this variable to be relevant.
2890 If you decide to turn this variable on, you might well want to turn off
2891 `org-outline-path-complete-in-steps'.
2892 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
2893 :group 'org-completion
2894 :type 'boolean)
2896 (defcustom org-completion-fallback-command 'hippie-expand
2897 "The expansion command called by \\[org-complete] in normal context.
2898 Normal means, no org-mode-specific context."
2899 :group 'org-completion
2900 :type 'function)
2902 ;;; Functions and variables from ther packages
2903 ;; Declared here to avoid compiler warnings
2905 ;; XEmacs only
2906 (defvar outline-mode-menu-heading)
2907 (defvar outline-mode-menu-show)
2908 (defvar outline-mode-menu-hide)
2909 (defvar zmacs-regions) ; XEmacs regions
2911 ;; Emacs only
2912 (defvar mark-active)
2914 ;; Various packages
2915 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2916 (declare-function calendar-forward-day "cal-move" (arg))
2917 (declare-function calendar-goto-date "cal-move" (date))
2918 (declare-function calendar-goto-today "cal-move" ())
2919 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2920 (defvar calc-embedded-close-formula)
2921 (defvar calc-embedded-open-formula)
2922 (declare-function cdlatex-tab "ext:cdlatex" ())
2923 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2924 (defvar font-lock-unfontify-region-function)
2925 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2926 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2927 (defvar iswitchb-temp-buflist)
2928 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2929 (defvar org-agenda-tags-todo-honor-ignore-options)
2930 (declare-function org-agenda-skip "org-agenda" ())
2931 (declare-function org-format-agenda-item "org-agenda"
2932 (extra txt &optional category tags dotime noprefix remove-re))
2933 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2934 (declare-function org-agenda-change-all-lines "org-agenda"
2935 (newhead hdmarker &optional fixface just-this))
2936 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2937 (declare-function org-agenda-maybe-redo "org-agenda" ())
2938 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2939 (beg end))
2940 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2941 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2942 "org-agenda" (&optional end))
2943 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
2944 (declare-function org-indent-mode "org-indent" (arg))
2945 (declare-function parse-time-string "parse-time" (string))
2946 (declare-function remember "remember" (&optional initial))
2947 (declare-function remember-buffer-desc "remember" ())
2948 (declare-function remember-finalize "remember" ())
2949 (defvar remember-save-after-remembering)
2950 (defvar remember-data-file)
2951 (defvar remember-register)
2952 (defvar remember-buffer)
2953 (defvar remember-handler-functions)
2954 (defvar remember-annotation-functions)
2955 (defvar texmathp-why)
2956 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2957 (declare-function table--at-cell-p "table" (position &optional object at-column))
2959 (defvar w3m-current-url)
2960 (defvar w3m-current-title)
2962 (defvar org-latex-regexps)
2964 ;;; Autoload and prepare some org modules
2966 ;; Some table stuff that needs to be defined here, because it is used
2967 ;; by the functions setting up org-mode or checking for table context.
2969 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2970 "Detects an org-type or table-type table.")
2971 (defconst org-table-line-regexp "^[ \t]*|"
2972 "Detects an org-type table line.")
2973 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2974 "Detects an org-type table line.")
2975 (defconst org-table-hline-regexp "^[ \t]*|-"
2976 "Detects an org-type table hline.")
2977 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2978 "Detects a table-type table hline.")
2979 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2980 "Searching from within a table (any type) this finds the first line
2981 outside the table.")
2983 ;; Autoload the functions in org-table.el that are needed by functions here.
2985 (eval-and-compile
2986 (org-autoload "org-table"
2987 '(org-table-align org-table-begin org-table-blank-field
2988 org-table-convert org-table-convert-region org-table-copy-down
2989 org-table-copy-region org-table-create
2990 org-table-create-or-convert-from-region
2991 org-table-create-with-table.el org-table-current-dline
2992 org-table-cut-region org-table-delete-column org-table-edit-field
2993 org-table-edit-formulas org-table-end org-table-eval-formula
2994 org-table-export org-table-field-info
2995 org-table-get-stored-formulas org-table-goto-column
2996 org-table-hline-and-move org-table-import org-table-insert-column
2997 org-table-insert-hline org-table-insert-row org-table-iterate
2998 org-table-justify-field-maybe org-table-kill-row
2999 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3000 org-table-move-column org-table-move-column-left
3001 org-table-move-column-right org-table-move-row
3002 org-table-move-row-down org-table-move-row-up
3003 org-table-next-field org-table-next-row org-table-paste-rectangle
3004 org-table-previous-field org-table-recalculate
3005 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3006 org-table-toggle-coordinate-overlays
3007 org-table-toggle-formula-debugger org-table-wrap-region
3008 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3010 (defun org-at-table-p (&optional table-type)
3011 "Return t if the cursor is inside an org-type table.
3012 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3013 (if org-enable-table-editor
3014 (save-excursion
3015 (beginning-of-line 1)
3016 (looking-at (if table-type org-table-any-line-regexp
3017 org-table-line-regexp)))
3018 nil))
3019 (defsubst org-table-p () (org-at-table-p))
3021 (defun org-at-table.el-p ()
3022 "Return t if and only if we are at a table.el table."
3023 (and (org-at-table-p 'any)
3024 (save-excursion
3025 (goto-char (org-table-begin 'any))
3026 (looking-at org-table1-hline-regexp))))
3027 (defun org-table-recognize-table.el ()
3028 "If there is a table.el table nearby, recognize it and move into it."
3029 (if org-table-tab-recognizes-table.el
3030 (if (org-at-table.el-p)
3031 (progn
3032 (beginning-of-line 1)
3033 (if (looking-at org-table-dataline-regexp)
3035 (if (looking-at org-table1-hline-regexp)
3036 (progn
3037 (beginning-of-line 2)
3038 (if (looking-at org-table-any-border-regexp)
3039 (beginning-of-line -1)))))
3040 (if (re-search-forward "|" (org-table-end t) t)
3041 (progn
3042 (require 'table)
3043 (if (table--at-cell-p (point))
3045 (message "recognizing table.el table...")
3046 (table-recognize-table)
3047 (message "recognizing table.el table...done")))
3048 (error "This should not happen..."))
3050 nil)
3051 nil))
3053 (defun org-at-table-hline-p ()
3054 "Return t if the cursor is inside a hline in a table."
3055 (if org-enable-table-editor
3056 (save-excursion
3057 (beginning-of-line 1)
3058 (looking-at org-table-hline-regexp))
3059 nil))
3061 (defvar org-table-clean-did-remove-column nil)
3063 (defun org-table-map-tables (function)
3064 "Apply FUNCTION to the start of all tables in the buffer."
3065 (save-excursion
3066 (save-restriction
3067 (widen)
3068 (goto-char (point-min))
3069 (while (re-search-forward org-table-any-line-regexp nil t)
3070 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3071 (beginning-of-line 1)
3072 (when (looking-at org-table-line-regexp)
3073 (save-excursion (funcall function))
3074 (or (looking-at org-table-line-regexp)
3075 (forward-char 1)))
3076 (re-search-forward org-table-any-border-regexp nil 1))))
3077 (message "Mapping tables: done"))
3079 ;; Declare and autoload functions from org-exp.el & Co
3081 (declare-function org-default-export-plist "org-exp")
3082 (declare-function org-infile-export-plist "org-exp")
3083 (declare-function org-get-current-options "org-exp")
3084 (eval-and-compile
3085 (org-autoload "org-exp"
3086 '(org-export org-export-visible
3087 org-insert-export-options-template
3088 org-table-clean-before-export))
3089 (org-autoload "org-ascii"
3090 '(org-export-as-ascii org-export-ascii-preprocess
3091 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3092 org-export-region-as-ascii))
3093 (org-autoload "org-html"
3094 '(org-export-as-html-and-open
3095 org-export-as-html-batch org-export-as-html-to-buffer
3096 org-replace-region-by-html org-export-region-as-html
3097 org-export-as-html))
3098 (org-autoload "org-icalendar"
3099 '(org-export-icalendar-this-file
3100 org-export-icalendar-all-agenda-files
3101 org-export-icalendar-combine-agenda-files))
3102 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3104 ;; Declare and autoload functions from org-agenda.el
3106 (eval-and-compile
3107 (org-autoload "org-agenda"
3108 '(org-agenda org-agenda-list org-search-view
3109 org-todo-list org-tags-view org-agenda-list-stuck-projects
3110 org-diary org-agenda-to-appt
3111 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3113 ;; Autoload org-remember
3115 (eval-and-compile
3116 (org-autoload "org-remember"
3117 '(org-remember-insinuate org-remember-annotation
3118 org-remember-apply-template org-remember org-remember-handler)))
3120 ;; Autoload org-clock.el
3123 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3124 (beg end))
3125 (declare-function org-clock-update-mode-line "org-clock" ())
3126 (defvar org-clock-start-time)
3127 (defvar org-clock-marker (make-marker)
3128 "Marker recording the last clock-in.")
3129 (defvar org-clock-hd-marker (make-marker)
3130 "Marker recording the last clock-in, but the headline position.")
3131 (defun org-clock-is-active ()
3132 "Return non-nil if clock is currently running.
3133 The return value is actually the clock marker."
3134 (marker-buffer org-clock-marker))
3136 (eval-and-compile
3137 (org-autoload
3138 "org-clock"
3139 '(org-clock-in org-clock-out org-clock-cancel
3140 org-clock-goto org-clock-sum org-clock-display
3141 org-clock-remove-overlays org-clock-report
3142 org-clocktable-shift org-dblock-write:clocktable
3143 org-get-clocktable)))
3145 (defun org-clock-update-time-maybe ()
3146 "If this is a CLOCK line, update it and return t.
3147 Otherwise, return nil."
3148 (interactive)
3149 (save-excursion
3150 (beginning-of-line 1)
3151 (skip-chars-forward " \t")
3152 (when (looking-at org-clock-string)
3153 (let ((re (concat "[ \t]*" org-clock-string
3154 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3155 "\\([ \t]*=>.*\\)?\\)?"))
3156 ts te h m s neg)
3157 (cond
3158 ((not (looking-at re))
3159 nil)
3160 ((not (match-end 2))
3161 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3162 (> org-clock-marker (point))
3163 (<= org-clock-marker (point-at-eol)))
3164 ;; The clock is running here
3165 (setq org-clock-start-time
3166 (apply 'encode-time
3167 (org-parse-time-string (match-string 1))))
3168 (org-clock-update-mode-line)))
3170 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3171 (end-of-line 1)
3172 (setq ts (match-string 1)
3173 te (match-string 3))
3174 (setq s (- (org-float-time
3175 (apply 'encode-time (org-parse-time-string te)))
3176 (org-float-time
3177 (apply 'encode-time (org-parse-time-string ts))))
3178 neg (< s 0)
3179 s (abs s)
3180 h (floor (/ s 3600))
3181 s (- s (* 3600 h))
3182 m (floor (/ s 60))
3183 s (- s (* 60 s)))
3184 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3185 t))))))
3187 (defun org-check-running-clock ()
3188 "Check if the current buffer contains the running clock.
3189 If yes, offer to stop it and to save the buffer with the changes."
3190 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3191 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3192 (buffer-name))))
3193 (org-clock-out)
3194 (when (y-or-n-p "Save changed buffer?")
3195 (save-buffer))))
3197 (defun org-clocktable-try-shift (dir n)
3198 "Check if this line starts a clock table, if yes, shift the time block."
3199 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3200 (org-clocktable-shift dir n)))
3202 ;; Autoload org-timer.el
3204 (eval-and-compile
3205 (org-autoload
3206 "org-timer"
3207 '(org-timer-start org-timer org-timer-item
3208 org-timer-change-times-in-region
3209 org-timer-set-timer
3210 org-timer-reset-timers
3211 org-timer-show-remaining-time)))
3213 ;; Autoload org-feed.el
3215 (eval-and-compile
3216 (org-autoload
3217 "org-feed"
3218 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3221 ;; Autoload org-indent.el
3223 (eval-and-compile
3224 (org-autoload
3225 "org-indent"
3226 '(org-indent-mode)))
3228 ;; Autoload org-mobile.el
3230 (eval-and-compile
3231 (org-autoload
3232 "org-mobile"
3233 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3235 ;; Autoload archiving code
3236 ;; The stuff that is needed for cycling and tags has to be defined here.
3238 (defgroup org-archive nil
3239 "Options concerning archiving in Org-mode."
3240 :tag "Org Archive"
3241 :group 'org-structure)
3243 (defcustom org-archive-location "%s_archive::"
3244 "The location where subtrees should be archived.
3246 The value of this variable is a string, consisting of two parts,
3247 separated by a double-colon. The first part is a filename and
3248 the second part is a headline.
3250 When the filename is omitted, archiving happens in the same file.
3251 %s in the filename will be replaced by the current file
3252 name (without the directory part). Archiving to a different file
3253 is useful to keep archived entries from contributing to the
3254 Org-mode Agenda.
3256 The archived entries will be filed as subtrees of the specified
3257 headline. When the headline is omitted, the subtrees are simply
3258 filed away at the end of the file, as top-level entries. Also in
3259 the heading you can use %s to represent the file name, this can be
3260 useful when using the same archive for a number of different files.
3262 Here are a few examples:
3263 \"%s_archive::\"
3264 If the current file is Projects.org, archive in file
3265 Projects.org_archive, as top-level trees. This is the default.
3267 \"::* Archived Tasks\"
3268 Archive in the current file, under the top-level headline
3269 \"* Archived Tasks\".
3271 \"~/org/archive.org::\"
3272 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3274 \"~/org/archive.org::From %s\"
3275 Archive in file ~/org/archive.org (absolute path), und headlines
3276 \"From FILENAME\" where file name is the current file name.
3278 \"basement::** Finished Tasks\"
3279 Archive in file ./basement (relative path), as level 3 trees
3280 below the level 2 heading \"** Finished Tasks\".
3282 You may set this option on a per-file basis by adding to the buffer a
3283 line like
3285 #+ARCHIVE: basement::** Finished Tasks
3287 You may also define it locally for a subtree by setting an ARCHIVE property
3288 in the entry. If such a property is found in an entry, or anywhere up
3289 the hierarchy, it will be used."
3290 :group 'org-archive
3291 :type 'string)
3293 (defcustom org-archive-tag "ARCHIVE"
3294 "The tag that marks a subtree as archived.
3295 An archived subtree does not open during visibility cycling, and does
3296 not contribute to the agenda listings.
3297 After changing this, font-lock must be restarted in the relevant buffers to
3298 get the proper fontification."
3299 :group 'org-archive
3300 :group 'org-keywords
3301 :type 'string)
3303 (defcustom org-agenda-skip-archived-trees t
3304 "Non-nil means, the agenda will skip any items located in archived trees.
3305 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3306 variable is no longer recommended, you should leave it at the value t.
3307 Instead, use the key `v' to cycle the archives-mode in the agenda."
3308 :group 'org-archive
3309 :group 'org-agenda-skip
3310 :type 'boolean)
3312 (defcustom org-columns-skip-arrchived-trees t
3313 "Non-nil means, irgnore archived trees when creating column view."
3314 :group 'org-archive
3315 :group 'org-properties
3316 :type 'boolean)
3318 (defcustom org-cycle-open-archived-trees nil
3319 "Non-nil means, `org-cycle' will open archived trees.
3320 An archived tree is a tree marked with the tag ARCHIVE.
3321 When nil, archived trees will stay folded. You can still open them with
3322 normal outline commands like `show-all', but not with the cycling commands."
3323 :group 'org-archive
3324 :group 'org-cycle
3325 :type 'boolean)
3327 (defcustom org-sparse-tree-open-archived-trees nil
3328 "Non-nil means sparse tree construction shows matches in archived trees.
3329 When nil, matches in these trees are highlighted, but the trees are kept in
3330 collapsed state."
3331 :group 'org-archive
3332 :group 'org-sparse-trees
3333 :type 'boolean)
3335 (defun org-cycle-hide-archived-subtrees (state)
3336 "Re-hide all archived subtrees after a visibility state change."
3337 (when (and (not org-cycle-open-archived-trees)
3338 (not (memq state '(overview folded))))
3339 (save-excursion
3340 (let* ((globalp (memq state '(contents all)))
3341 (beg (if globalp (point-min) (point)))
3342 (end (if globalp (point-max) (org-end-of-subtree t))))
3343 (org-hide-archived-subtrees beg end)
3344 (goto-char beg)
3345 (if (looking-at (concat ".*:" org-archive-tag ":"))
3346 (message "%s" (substitute-command-keys
3347 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3349 (defun org-force-cycle-archived ()
3350 "Cycle subtree even if it is archived."
3351 (interactive)
3352 (setq this-command 'org-cycle)
3353 (let ((org-cycle-open-archived-trees t))
3354 (call-interactively 'org-cycle)))
3356 (defun org-hide-archived-subtrees (beg end)
3357 "Re-hide all archived subtrees after a visibility state change."
3358 (save-excursion
3359 (let* ((re (concat ":" org-archive-tag ":")))
3360 (goto-char beg)
3361 (while (re-search-forward re end t)
3362 (and (org-on-heading-p) (hide-subtree))
3363 (org-end-of-subtree t)))))
3365 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3367 (eval-and-compile
3368 (org-autoload "org-archive"
3369 '(org-add-archive-files org-archive-subtree
3370 org-archive-to-archive-sibling org-toggle-archive-tag)))
3372 ;; Autoload Column View Code
3374 (declare-function org-columns-number-to-string "org-colview")
3375 (declare-function org-columns-get-format-and-top-level "org-colview")
3376 (declare-function org-columns-compute "org-colview")
3378 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3379 '(org-columns-number-to-string org-columns-get-format-and-top-level
3380 org-columns-compute org-agenda-columns org-columns-remove-overlays
3381 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3383 ;; Autoload ID code
3385 (declare-function org-id-store-link "org-id")
3386 (declare-function org-id-locations-load "org-id")
3387 (declare-function org-id-locations-save "org-id")
3388 (defvar org-id-track-globally)
3389 (org-autoload "org-id"
3390 '(org-id-get-create org-id-new org-id-copy org-id-get
3391 org-id-get-with-outline-path-completion
3392 org-id-get-with-outline-drilling
3393 org-id-goto org-id-find org-id-store-link))
3395 ;; Autoload Plotting Code
3397 (org-autoload "org-plot"
3398 '(org-plot/gnuplot))
3400 ;;; Variables for pre-computed regular expressions, all buffer local
3402 (defvar org-drawer-regexp nil
3403 "Matches first line of a hidden block.")
3404 (make-variable-buffer-local 'org-drawer-regexp)
3405 (defvar org-todo-regexp nil
3406 "Matches any of the TODO state keywords.")
3407 (make-variable-buffer-local 'org-todo-regexp)
3408 (defvar org-not-done-regexp nil
3409 "Matches any of the TODO state keywords except the last one.")
3410 (make-variable-buffer-local 'org-not-done-regexp)
3411 (defvar org-not-done-heading-regexp nil
3412 "Matches a TODO headline that is not done.")
3413 (make-variable-buffer-local 'org-not-done-regexp)
3414 (defvar org-todo-line-regexp nil
3415 "Matches a headline and puts TODO state into group 2 if present.")
3416 (make-variable-buffer-local 'org-todo-line-regexp)
3417 (defvar org-complex-heading-regexp nil
3418 "Matches a headline and puts everything into groups:
3419 group 1: the stars
3420 group 2: The todo keyword, maybe
3421 group 3: Priority cookie
3422 group 4: True headline
3423 group 5: Tags")
3424 (make-variable-buffer-local 'org-complex-heading-regexp)
3425 (defvar org-todo-line-tags-regexp nil
3426 "Matches a headline and puts TODO state into group 2 if present.
3427 Also put tags into group 4 if tags are present.")
3428 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3429 (defvar org-nl-done-regexp nil
3430 "Matches newline followed by a headline with the DONE keyword.")
3431 (make-variable-buffer-local 'org-nl-done-regexp)
3432 (defvar org-looking-at-done-regexp nil
3433 "Matches the DONE keyword a point.")
3434 (make-variable-buffer-local 'org-looking-at-done-regexp)
3435 (defvar org-ds-keyword-length 12
3436 "Maximum length of the Deadline and SCHEDULED keywords.")
3437 (make-variable-buffer-local 'org-ds-keyword-length)
3438 (defvar org-deadline-regexp nil
3439 "Matches the DEADLINE keyword.")
3440 (make-variable-buffer-local 'org-deadline-regexp)
3441 (defvar org-deadline-time-regexp nil
3442 "Matches the DEADLINE keyword together with a time stamp.")
3443 (make-variable-buffer-local 'org-deadline-time-regexp)
3444 (defvar org-deadline-line-regexp nil
3445 "Matches the DEADLINE keyword and the rest of the line.")
3446 (make-variable-buffer-local 'org-deadline-line-regexp)
3447 (defvar org-scheduled-regexp nil
3448 "Matches the SCHEDULED keyword.")
3449 (make-variable-buffer-local 'org-scheduled-regexp)
3450 (defvar org-scheduled-time-regexp nil
3451 "Matches the SCHEDULED keyword together with a time stamp.")
3452 (make-variable-buffer-local 'org-scheduled-time-regexp)
3453 (defvar org-closed-time-regexp nil
3454 "Matches the CLOSED keyword together with a time stamp.")
3455 (make-variable-buffer-local 'org-closed-time-regexp)
3457 (defvar org-keyword-time-regexp nil
3458 "Matches any of the 4 keywords, together with the time stamp.")
3459 (make-variable-buffer-local 'org-keyword-time-regexp)
3460 (defvar org-keyword-time-not-clock-regexp nil
3461 "Matches any of the 3 keywords, together with the time stamp.")
3462 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3463 (defvar org-maybe-keyword-time-regexp nil
3464 "Matches a timestamp, possibly preceeded by a keyword.")
3465 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3466 (defvar org-planning-or-clock-line-re nil
3467 "Matches a line with planning or clock info.")
3468 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3470 (defconst org-plain-time-of-day-regexp
3471 (concat
3472 "\\(\\<[012]?[0-9]"
3473 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3474 "\\(--?"
3475 "\\(\\<[012]?[0-9]"
3476 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3477 "\\)?")
3478 "Regular expression to match a plain time or time range.
3479 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3480 groups carry important information:
3481 0 the full match
3482 1 the first time, range or not
3483 8 the second time, if it is a range.")
3485 (defconst org-plain-time-extension-regexp
3486 (concat
3487 "\\(\\<[012]?[0-9]"
3488 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3489 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3490 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3491 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3492 groups carry important information:
3493 0 the full match
3494 7 hours of duration
3495 9 minutes of duration")
3497 (defconst org-stamp-time-of-day-regexp
3498 (concat
3499 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3500 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3501 "\\(--?"
3502 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3503 "Regular expression to match a timestamp time or time range.
3504 After a match, the following groups carry important information:
3505 0 the full match
3506 1 date plus weekday, for backreferencing to make sure both times on same day
3507 2 the first time, range or not
3508 4 the second time, if it is a range.")
3510 (defconst org-startup-options
3511 '(("fold" org-startup-folded t)
3512 ("overview" org-startup-folded t)
3513 ("nofold" org-startup-folded nil)
3514 ("showall" org-startup-folded nil)
3515 ("showeverything" org-startup-folded showeverything)
3516 ("content" org-startup-folded content)
3517 ("indent" org-startup-indented t)
3518 ("noindent" org-startup-indented nil)
3519 ("hidestars" org-hide-leading-stars t)
3520 ("showstars" org-hide-leading-stars nil)
3521 ("odd" org-odd-levels-only t)
3522 ("oddeven" org-odd-levels-only nil)
3523 ("align" org-startup-align-all-tables t)
3524 ("noalign" org-startup-align-all-tables nil)
3525 ("customtime" org-display-custom-times t)
3526 ("logdone" org-log-done time)
3527 ("lognotedone" org-log-done note)
3528 ("nologdone" org-log-done nil)
3529 ("lognoteclock-out" org-log-note-clock-out t)
3530 ("nolognoteclock-out" org-log-note-clock-out nil)
3531 ("logrepeat" org-log-repeat state)
3532 ("lognoterepeat" org-log-repeat note)
3533 ("nologrepeat" org-log-repeat nil)
3534 ("fninline" org-footnote-define-inline t)
3535 ("nofninline" org-footnote-define-inline nil)
3536 ("fnlocal" org-footnote-section nil)
3537 ("fnauto" org-footnote-auto-label t)
3538 ("fnprompt" org-footnote-auto-label nil)
3539 ("fnconfirm" org-footnote-auto-label confirm)
3540 ("fnplain" org-footnote-auto-label plain)
3541 ("fnadjust" org-footnote-auto-adjust t)
3542 ("nofnadjust" org-footnote-auto-adjust nil)
3543 ("constcgs" constants-unit-system cgs)
3544 ("constSI" constants-unit-system SI)
3545 ("noptag" org-tag-persistent-alist nil)
3546 ("hideblocks" org-hide-block-startup t)
3547 ("nohideblocks" org-hide-block-startup nil))
3548 "Variable associated with STARTUP options for org-mode.
3549 Each element is a list of three items: The startup options as written
3550 in the #+STARTUP line, the corresponding variable, and the value to
3551 set this variable to if the option is found. An optional forth element PUSH
3552 means to push this value onto the list in the variable.")
3554 (defun org-set-regexps-and-options ()
3555 "Precompute regular expressions for current buffer."
3556 (when (org-mode-p)
3557 (org-set-local 'org-todo-kwd-alist nil)
3558 (org-set-local 'org-todo-key-alist nil)
3559 (org-set-local 'org-todo-key-trigger nil)
3560 (org-set-local 'org-todo-keywords-1 nil)
3561 (org-set-local 'org-done-keywords nil)
3562 (org-set-local 'org-todo-heads nil)
3563 (org-set-local 'org-todo-sets nil)
3564 (org-set-local 'org-todo-log-states nil)
3565 (org-set-local 'org-file-properties nil)
3566 (org-set-local 'org-file-tags nil)
3567 (let ((re (org-make-options-regexp
3568 '("CATEGORY" "TODO" "COLUMNS"
3569 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3570 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3571 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3572 (splitre "[ \t]+")
3573 kwds kws0 kwsa key log value cat arch tags const links hw dws
3574 tail sep kws1 prio props ftags drawers
3575 ext-setup-or-nil setup-contents (start 0))
3576 (save-excursion
3577 (save-restriction
3578 (widen)
3579 (goto-char (point-min))
3580 (while (or (and ext-setup-or-nil
3581 (string-match re ext-setup-or-nil start)
3582 (setq start (match-end 0)))
3583 (and (setq ext-setup-or-nil nil start 0)
3584 (re-search-forward re nil t)))
3585 (setq key (upcase (match-string 1 ext-setup-or-nil))
3586 value (org-match-string-no-properties 2 ext-setup-or-nil))
3587 (cond
3588 ((equal key "CATEGORY")
3589 (if (string-match "[ \t]+$" value)
3590 (setq value (replace-match "" t t value)))
3591 (setq cat value))
3592 ((member key '("SEQ_TODO" "TODO"))
3593 (push (cons 'sequence (org-split-string value splitre)) kwds))
3594 ((equal key "TYP_TODO")
3595 (push (cons 'type (org-split-string value splitre)) kwds))
3596 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3597 ;; general TODO-like setup
3598 (push (cons (intern (downcase (match-string 1 key)))
3599 (org-split-string value splitre)) kwds))
3600 ((equal key "TAGS")
3601 (setq tags (append tags (if tags '("\\n") nil)
3602 (org-split-string value splitre))))
3603 ((equal key "COLUMNS")
3604 (org-set-local 'org-columns-default-format value))
3605 ((equal key "LINK")
3606 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3607 (push (cons (match-string 1 value)
3608 (org-trim (match-string 2 value)))
3609 links)))
3610 ((equal key "PRIORITIES")
3611 (setq prio (org-split-string value " +")))
3612 ((equal key "PROPERTY")
3613 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3614 (push (cons (match-string 1 value) (match-string 2 value))
3615 props)))
3616 ((equal key "FILETAGS")
3617 (when (string-match "\\S-" value)
3618 (setq ftags
3619 (append
3620 ftags
3621 (apply 'append
3622 (mapcar (lambda (x) (org-split-string x ":"))
3623 (org-split-string value)))))))
3624 ((equal key "DRAWERS")
3625 (setq drawers (org-split-string value splitre)))
3626 ((equal key "CONSTANTS")
3627 (setq const (append const (org-split-string value splitre))))
3628 ((equal key "STARTUP")
3629 (let ((opts (org-split-string value splitre))
3630 l var val)
3631 (while (setq l (pop opts))
3632 (when (setq l (assoc l org-startup-options))
3633 (setq var (nth 1 l) val (nth 2 l))
3634 (if (not (nth 3 l))
3635 (set (make-local-variable var) val)
3636 (if (not (listp (symbol-value var)))
3637 (set (make-local-variable var) nil))
3638 (set (make-local-variable var) (symbol-value var))
3639 (add-to-list var val))))))
3640 ((equal key "ARCHIVE")
3641 (string-match " *$" value)
3642 (setq arch (replace-match "" t t value))
3643 (remove-text-properties 0 (length arch)
3644 '(face t fontified t) arch))
3645 ((equal key "SETUPFILE")
3646 (setq setup-contents (org-file-contents
3647 (expand-file-name
3648 (org-remove-double-quotes value))
3649 'noerror))
3650 (if (not ext-setup-or-nil)
3651 (setq ext-setup-or-nil setup-contents start 0)
3652 (setq ext-setup-or-nil
3653 (concat (substring ext-setup-or-nil 0 start)
3654 "\n" setup-contents "\n"
3655 (substring ext-setup-or-nil start)))))
3656 ))))
3657 (when cat
3658 (org-set-local 'org-category (intern cat))
3659 (push (cons "CATEGORY" cat) props))
3660 (when prio
3661 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3662 (setq prio (mapcar 'string-to-char prio))
3663 (org-set-local 'org-highest-priority (nth 0 prio))
3664 (org-set-local 'org-lowest-priority (nth 1 prio))
3665 (org-set-local 'org-default-priority (nth 2 prio)))
3666 (and props (org-set-local 'org-file-properties (nreverse props)))
3667 (and ftags (org-set-local 'org-file-tags
3668 (mapcar 'org-add-prop-inherited ftags)))
3669 (and drawers (org-set-local 'org-drawers drawers))
3670 (and arch (org-set-local 'org-archive-location arch))
3671 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3672 ;; Process the TODO keywords
3673 (unless kwds
3674 ;; Use the global values as if they had been given locally.
3675 (setq kwds (default-value 'org-todo-keywords))
3676 (if (stringp (car kwds))
3677 (setq kwds (list (cons org-todo-interpretation
3678 (default-value 'org-todo-keywords)))))
3679 (setq kwds (reverse kwds)))
3680 (setq kwds (nreverse kwds))
3681 (let (inter kws kw)
3682 (while (setq kws (pop kwds))
3683 (let ((kws (or
3684 (run-hook-with-args-until-success
3685 'org-todo-setup-filter-hook kws)
3686 kws)))
3687 (setq inter (pop kws) sep (member "|" kws)
3688 kws0 (delete "|" (copy-sequence kws))
3689 kwsa nil
3690 kws1 (mapcar
3691 (lambda (x)
3692 ;; 1 2
3693 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3694 (progn
3695 (setq kw (match-string 1 x)
3696 key (and (match-end 2) (match-string 2 x))
3697 log (org-extract-log-state-settings x))
3698 (push (cons kw (and key (string-to-char key))) kwsa)
3699 (and log (push log org-todo-log-states))
3701 (error "Invalid TODO keyword %s" x)))
3702 kws0)
3703 kwsa (if kwsa (append '((:startgroup))
3704 (nreverse kwsa)
3705 '((:endgroup))))
3706 hw (car kws1)
3707 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3708 tail (list inter hw (car dws) (org-last dws))))
3709 (add-to-list 'org-todo-heads hw 'append)
3710 (push kws1 org-todo-sets)
3711 (setq org-done-keywords (append org-done-keywords dws nil))
3712 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3713 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3714 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3715 (setq org-todo-sets (nreverse org-todo-sets)
3716 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3717 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3718 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3719 ;; Process the constants
3720 (when const
3721 (let (e cst)
3722 (while (setq e (pop const))
3723 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3724 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3725 (setq org-table-formula-constants-local cst)))
3727 ;; Process the tags.
3728 (when tags
3729 (let (e tgs)
3730 (while (setq e (pop tags))
3731 (cond
3732 ((equal e "{") (push '(:startgroup) tgs))
3733 ((equal e "}") (push '(:endgroup) tgs))
3734 ((equal e "\\n") (push '(:newline) tgs))
3735 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3736 (push (cons (match-string 1 e)
3737 (string-to-char (match-string 2 e)))
3738 tgs))
3739 (t (push (list e) tgs))))
3740 (org-set-local 'org-tag-alist nil)
3741 (while (setq e (pop tgs))
3742 (or (and (stringp (car e))
3743 (assoc (car e) org-tag-alist))
3744 (push e org-tag-alist)))))
3746 ;; Compute the regular expressions and other local variables
3747 (if (not org-done-keywords)
3748 (setq org-done-keywords (and org-todo-keywords-1
3749 (list (org-last org-todo-keywords-1)))))
3750 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3751 (length org-scheduled-string)
3752 (length org-clock-string)
3753 (length org-closed-string)))
3754 org-drawer-regexp
3755 (concat "^[ \t]*:\\("
3756 (mapconcat 'regexp-quote org-drawers "\\|")
3757 "\\):[ \t]*$")
3758 org-not-done-keywords
3759 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3760 org-todo-regexp
3761 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3762 "\\|") "\\)\\>")
3763 org-not-done-regexp
3764 (concat "\\<\\("
3765 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3766 "\\)\\>")
3767 org-not-done-heading-regexp
3768 (concat "^\\(\\*+\\)[ \t]+\\("
3769 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3770 "\\)\\>")
3771 org-todo-line-regexp
3772 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3773 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3774 "\\)\\>\\)?[ \t]*\\(.*\\)")
3775 org-complex-heading-regexp
3776 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3777 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3778 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3779 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3780 org-nl-done-regexp
3781 (concat "\n\\*+[ \t]+"
3782 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3783 "\\)" "\\>")
3784 org-todo-line-tags-regexp
3785 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3786 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3787 (org-re
3788 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3789 org-looking-at-done-regexp
3790 (concat "^" "\\(?:"
3791 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3792 "\\>")
3793 org-deadline-regexp (concat "\\<" org-deadline-string)
3794 org-deadline-time-regexp
3795 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3796 org-deadline-line-regexp
3797 (concat "\\<\\(" org-deadline-string "\\).*")
3798 org-scheduled-regexp
3799 (concat "\\<" org-scheduled-string)
3800 org-scheduled-time-regexp
3801 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3802 org-closed-time-regexp
3803 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3804 org-keyword-time-regexp
3805 (concat "\\<\\(" org-scheduled-string
3806 "\\|" org-deadline-string
3807 "\\|" org-closed-string
3808 "\\|" org-clock-string "\\)"
3809 " *[[<]\\([^]>]+\\)[]>]")
3810 org-keyword-time-not-clock-regexp
3811 (concat "\\<\\(" org-scheduled-string
3812 "\\|" org-deadline-string
3813 "\\|" org-closed-string
3814 "\\)"
3815 " *[[<]\\([^]>]+\\)[]>]")
3816 org-maybe-keyword-time-regexp
3817 (concat "\\(\\<\\(" org-scheduled-string
3818 "\\|" org-deadline-string
3819 "\\|" org-closed-string
3820 "\\|" org-clock-string "\\)\\)?"
3821 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3822 org-planning-or-clock-line-re
3823 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3824 "\\|" org-deadline-string
3825 "\\|" org-closed-string "\\|" org-clock-string
3826 "\\)\\>\\)")
3828 (org-compute-latex-and-specials-regexp)
3829 (org-set-font-lock-defaults))))
3831 (defun org-file-contents (file &optional noerror)
3832 "Return the contents of FILE, as a string."
3833 (if (or (not file)
3834 (not (file-readable-p file)))
3835 (if noerror
3836 (progn
3837 (message "Cannot read file %s" file)
3838 (ding) (sit-for 2)
3840 (error "Cannot read file %s" file))
3841 (with-temp-buffer
3842 (insert-file-contents file)
3843 (buffer-string))))
3845 (defun org-extract-log-state-settings (x)
3846 "Extract the log state setting from a TODO keyword string.
3847 This will extract info from a string like \"WAIT(w@/!)\"."
3848 (let (kw key log1 log2)
3849 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3850 (setq kw (match-string 1 x)
3851 key (and (match-end 2) (match-string 2 x))
3852 log1 (and (match-end 3) (match-string 3 x))
3853 log2 (and (match-end 4) (match-string 4 x)))
3854 (and (or log1 log2)
3855 (list kw
3856 (and log1 (if (equal log1 "!") 'time 'note))
3857 (and log2 (if (equal log2 "!") 'time 'note)))))))
3859 (defun org-remove-keyword-keys (list)
3860 "Remove a pair of parenthesis at the end of each string in LIST."
3861 (mapcar (lambda (x)
3862 (if (string-match "(.*)$" x)
3863 (substring x 0 (match-beginning 0))
3865 list))
3867 ;; FIXME: this could be done much better, using second characters etc.
3868 (defun org-assign-fast-keys (alist)
3869 "Assign fast keys to a keyword-key alist.
3870 Respect keys that are already there."
3871 (let (new e k c c1 c2 (char ?a))
3872 (while (setq e (pop alist))
3873 (cond
3874 ((equal e '(:startgroup)) (push e new))
3875 ((equal e '(:endgroup)) (push e new))
3876 ((equal e '(:newline)) (push e new))
3878 (setq k (car e) c2 nil)
3879 (if (cdr e)
3880 (setq c (cdr e))
3881 ;; automatically assign a character.
3882 (setq c1 (string-to-char
3883 (downcase (substring
3884 k (if (= (string-to-char k) ?@) 1 0)))))
3885 (if (or (rassoc c1 new) (rassoc c1 alist))
3886 (while (or (rassoc char new) (rassoc char alist))
3887 (setq char (1+ char)))
3888 (setq c2 c1))
3889 (setq c (or c2 char)))
3890 (push (cons k c) new))))
3891 (nreverse new)))
3893 ;;; Some variables used in various places
3895 (defvar org-window-configuration nil
3896 "Used in various places to store a window configuration.")
3897 (defvar org-selected-window nil
3898 "Used in various places to store a window configuration.")
3899 (defvar org-finish-function nil
3900 "Function to be called when `C-c C-c' is used.
3901 This is for getting out of special buffers like remember.")
3904 ;; FIXME: Occasionally check by commenting these, to make sure
3905 ;; no other functions uses these, forgetting to let-bind them.
3906 (defvar entry)
3907 (defvar last-state)
3908 (defvar date)
3910 ;; Defined somewhere in this file, but used before definition.
3911 (defvar org-html-entities)
3912 (defvar org-struct-menu)
3913 (defvar org-org-menu)
3914 (defvar org-tbl-menu)
3915 (defvar org-agenda-keymap)
3917 ;;;; Define the Org-mode
3919 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3920 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22."))
3923 ;; We use a before-change function to check if a table might need
3924 ;; an update.
3925 (defvar org-table-may-need-update t
3926 "Indicates that a table might need an update.
3927 This variable is set by `org-before-change-function'.
3928 `org-table-align' sets it back to nil.")
3929 (defun org-before-change-function (beg end)
3930 "Every change indicates that a table might need an update."
3931 (setq org-table-may-need-update t))
3932 (defvar org-mode-map)
3933 (defvar org-mode-hook nil
3934 "Mode hook for Org-mode, run after the mode was turned on.")
3935 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3936 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3937 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3938 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3939 (defvar org-table-buffer-is-an nil)
3940 (defconst org-outline-regexp "\\*+ ")
3942 ;;;###autoload
3943 (define-derived-mode org-mode outline-mode "Org"
3944 "Outline-based notes management and organizer, alias
3945 \"Carsten's outline-mode for keeping track of everything.\"
3947 Org-mode develops organizational tasks around a NOTES file which
3948 contains information about projects as plain text. Org-mode is
3949 implemented on top of outline-mode, which is ideal to keep the content
3950 of large files well structured. It supports ToDo items, deadlines and
3951 time stamps, which magically appear in the diary listing of the Emacs
3952 calendar. Tables are easily created with a built-in table editor.
3953 Plain text URL-like links connect to websites, emails (VM), Usenet
3954 messages (Gnus), BBDB entries, and any files related to the project.
3955 For printing and sharing of notes, an Org-mode file (or a part of it)
3956 can be exported as a structured ASCII or HTML file.
3958 The following commands are available:
3960 \\{org-mode-map}"
3962 ;; Get rid of Outline menus, they are not needed
3963 ;; Need to do this here because define-derived-mode sets up
3964 ;; the keymap so late. Still, it is a waste to call this each time
3965 ;; we switch another buffer into org-mode.
3966 (if (featurep 'xemacs)
3967 (when (boundp 'outline-mode-menu-heading)
3968 ;; Assume this is Greg's port, it used easymenu
3969 (easy-menu-remove outline-mode-menu-heading)
3970 (easy-menu-remove outline-mode-menu-show)
3971 (easy-menu-remove outline-mode-menu-hide))
3972 (define-key org-mode-map [menu-bar headings] 'undefined)
3973 (define-key org-mode-map [menu-bar hide] 'undefined)
3974 (define-key org-mode-map [menu-bar show] 'undefined))
3976 (org-load-modules-maybe)
3977 (easy-menu-add org-org-menu)
3978 (easy-menu-add org-tbl-menu)
3979 (org-install-agenda-files-menu)
3980 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3981 (org-add-to-invisibility-spec '(org-cwidth))
3982 (org-add-to-invisibility-spec '(org-hide-block . t))
3983 (when (featurep 'xemacs)
3984 (org-set-local 'line-move-ignore-invisible t))
3985 (org-set-local 'outline-regexp org-outline-regexp)
3986 (org-set-local 'outline-level 'org-outline-level)
3987 (when (and org-ellipsis
3988 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3989 (fboundp 'make-glyph-code))
3990 (unless org-display-table
3991 (setq org-display-table (make-display-table)))
3992 (set-display-table-slot
3993 org-display-table 4
3994 (vconcat (mapcar
3995 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3996 org-ellipsis)))
3997 (if (stringp org-ellipsis) org-ellipsis "..."))))
3998 (setq buffer-display-table org-display-table))
3999 (org-set-regexps-and-options)
4000 (when (and org-tag-faces (not org-tags-special-faces-re))
4001 ;; tag faces set outside customize.... force initialization.
4002 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4003 ;; Calc embedded
4004 (org-set-local 'calc-embedded-open-mode "# ")
4005 (modify-syntax-entry ?# "<")
4006 (modify-syntax-entry ?@ "w")
4007 (if org-startup-truncated (setq truncate-lines t))
4008 (org-set-local 'font-lock-unfontify-region-function
4009 'org-unfontify-region)
4010 ;; Activate before-change-function
4011 (org-set-local 'org-table-may-need-update t)
4012 (org-add-hook 'before-change-functions 'org-before-change-function nil
4013 'local)
4014 ;; Check for running clock before killing a buffer
4015 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4016 ;; Paragraphs and auto-filling
4017 (org-set-autofill-regexps)
4018 (setq indent-line-function 'org-indent-line-function)
4019 (org-update-radio-target-regexp)
4020 ;; Make sure dependence stuff works reliably, even for users who set it
4021 ;; too late :-(
4022 (if org-enforce-todo-dependencies
4023 (add-hook 'org-blocker-hook
4024 'org-block-todo-from-children-or-siblings-or-parent)
4025 (remove-hook 'org-blocker-hook
4026 'org-block-todo-from-children-or-siblings-or-parent))
4027 (if org-enforce-todo-checkbox-dependencies
4028 (add-hook 'org-blocker-hook
4029 'org-block-todo-from-checkboxes)
4030 (remove-hook 'org-blocker-hook
4031 'org-block-todo-from-checkboxes))
4033 ;; Comment characters
4034 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4035 (org-set-local 'comment-padding " ")
4037 ;; Align options lines
4038 (org-set-local
4039 'align-mode-rules-list
4040 '((org-in-buffer-settings
4041 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4042 (modes . '(org-mode)))))
4044 ;; Imenu
4045 (org-set-local 'imenu-create-index-function
4046 'org-imenu-get-tree)
4048 ;; Make isearch reveal context
4049 (if (or (featurep 'xemacs)
4050 (not (boundp 'outline-isearch-open-invisible-function)))
4051 ;; Emacs 21 and XEmacs make use of the hook
4052 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4053 ;; Emacs 22 deals with this through a special variable
4054 (org-set-local 'outline-isearch-open-invisible-function
4055 (lambda (&rest ignore) (org-show-context 'isearch))))
4057 ;; If empty file that did not turn on org-mode automatically, make it to.
4058 (if (and org-insert-mode-line-in-empty-file
4059 (interactive-p)
4060 (= (point-min) (point-max)))
4061 (insert "# -*- mode: org -*-\n\n"))
4063 (unless org-inhibit-startup
4064 (when org-startup-align-all-tables
4065 (let ((bmp (buffer-modified-p)))
4066 (org-table-map-tables 'org-table-align)
4067 (set-buffer-modified-p bmp)))
4068 (when org-startup-indented
4069 (require 'org-indent)
4070 (org-indent-mode 1))
4071 (org-set-startup-visibility)))
4073 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4075 (defun org-current-time ()
4076 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4077 (if (> (car org-time-stamp-rounding-minutes) 1)
4078 (let ((r (car org-time-stamp-rounding-minutes))
4079 (time (decode-time)))
4080 (apply 'encode-time
4081 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4082 (nthcdr 2 time))))
4083 (current-time)))
4085 ;;;; Font-Lock stuff, including the activators
4087 (defvar org-mouse-map (make-sparse-keymap))
4088 (org-defkey org-mouse-map
4089 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4090 (org-defkey org-mouse-map
4091 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4092 (when org-mouse-1-follows-link
4093 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4094 (when org-tab-follows-link
4095 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4096 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4098 (require 'font-lock)
4100 (defconst org-non-link-chars "]\t\n\r<>")
4101 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4102 "shell" "elisp"))
4103 (defvar org-link-types-re nil
4104 "Matches a link that has a url-like prefix like \"http:\"")
4105 (defvar org-link-re-with-space nil
4106 "Matches a link with spaces, optional angular brackets around it.")
4107 (defvar org-link-re-with-space2 nil
4108 "Matches a link with spaces, optional angular brackets around it.")
4109 (defvar org-link-re-with-space3 nil
4110 "Matches a link with spaces, only for internal part in bracket links.")
4111 (defvar org-angle-link-re nil
4112 "Matches link with angular brackets, spaces are allowed.")
4113 (defvar org-plain-link-re nil
4114 "Matches plain link, without spaces.")
4115 (defvar org-bracket-link-regexp nil
4116 "Matches a link in double brackets.")
4117 (defvar org-bracket-link-analytic-regexp nil
4118 "Regular expression used to analyze links.
4119 Here is what the match groups contain after a match:
4120 1: http:
4121 2: http
4122 3: path
4123 4: [desc]
4124 5: desc")
4125 (defvar org-bracket-link-analytic-regexp++ nil
4126 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4127 (defvar org-any-link-re nil
4128 "Regular expression matching any link.")
4130 (defun org-make-link-regexps ()
4131 "Update the link regular expressions.
4132 This should be called after the variable `org-link-types' has changed."
4133 (setq org-link-types-re
4134 (concat
4135 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4136 org-link-re-with-space
4137 (concat
4138 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4139 "\\([^" org-non-link-chars " ]"
4140 "[^" org-non-link-chars "]*"
4141 "[^" org-non-link-chars " ]\\)>?")
4142 org-link-re-with-space2
4143 (concat
4144 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4145 "\\([^" org-non-link-chars " ]"
4146 "[^\t\n\r]*"
4147 "[^" org-non-link-chars " ]\\)>?")
4148 org-link-re-with-space3
4149 (concat
4150 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4151 "\\([^" org-non-link-chars " ]"
4152 "[^\t\n\r]*\\)")
4153 org-angle-link-re
4154 (concat
4155 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4156 "\\([^" org-non-link-chars " ]"
4157 "[^" org-non-link-chars "]*"
4158 "\\)>")
4159 org-plain-link-re
4160 (concat
4161 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4162 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4163 org-bracket-link-regexp
4164 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4165 org-bracket-link-analytic-regexp
4166 (concat
4167 "\\[\\["
4168 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4169 "\\([^]]+\\)"
4170 "\\]"
4171 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4172 "\\]")
4173 org-bracket-link-analytic-regexp++
4174 (concat
4175 "\\[\\["
4176 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4177 "\\([^]]+\\)"
4178 "\\]"
4179 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4180 "\\]")
4181 org-any-link-re
4182 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4183 org-angle-link-re "\\)\\|\\("
4184 org-plain-link-re "\\)")))
4186 (org-make-link-regexps)
4188 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4189 "Regular expression for fast time stamp matching.")
4190 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4191 "Regular expression for fast time stamp matching.")
4192 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4193 "Regular expression matching time strings for analysis.
4194 This one does not require the space after the date, so it can be used
4195 on a string that terminates immediately after the date.")
4196 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4197 "Regular expression matching time strings for analysis.")
4198 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4199 "Regular expression matching time stamps, with groups.")
4200 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4201 "Regular expression matching time stamps (also [..]), with groups.")
4202 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4203 "Regular expression matching a time stamp range.")
4204 (defconst org-tr-regexp-both
4205 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4206 "Regular expression matching a time stamp range.")
4207 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4208 org-ts-regexp "\\)?")
4209 "Regular expression matching a time stamp or time stamp range.")
4210 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4211 org-ts-regexp-both "\\)?")
4212 "Regular expression matching a time stamp or time stamp range.
4213 The time stamps may be either active or inactive.")
4215 (defvar org-emph-face nil)
4217 (defun org-do-emphasis-faces (limit)
4218 "Run through the buffer and add overlays to links."
4219 (let (rtn a)
4220 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4221 (if (not (= (char-after (match-beginning 3))
4222 (char-after (match-beginning 4))))
4223 (progn
4224 (setq rtn t)
4225 (setq a (assoc (match-string 3) org-emphasis-alist))
4226 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4227 'face
4228 (nth 1 a))
4229 (and (nth 4 a)
4230 (org-remove-flyspell-overlays-in
4231 (match-beginning 0) (match-end 0)))
4232 (add-text-properties (match-beginning 2) (match-end 2)
4233 '(font-lock-multiline t))
4234 (when org-hide-emphasis-markers
4235 (add-text-properties (match-end 4) (match-beginning 5)
4236 '(invisible org-link))
4237 (add-text-properties (match-beginning 3) (match-end 3)
4238 '(invisible org-link)))))
4239 (backward-char 1))
4240 rtn))
4242 (defun org-emphasize (&optional char)
4243 "Insert or change an emphasis, i.e. a font like bold or italic.
4244 If there is an active region, change that region to a new emphasis.
4245 If there is no region, just insert the marker characters and position
4246 the cursor between them.
4247 CHAR should be either the marker character, or the first character of the
4248 HTML tag associated with that emphasis. If CHAR is a space, the means
4249 to remove the emphasis of the selected region.
4250 If char is not given (for example in an interactive call) it
4251 will be prompted for."
4252 (interactive)
4253 (let ((eal org-emphasis-alist) e det
4254 (erc org-emphasis-regexp-components)
4255 (prompt "")
4256 (string "") beg end move tag c s)
4257 (if (org-region-active-p)
4258 (setq beg (region-beginning) end (region-end)
4259 string (buffer-substring beg end))
4260 (setq move t))
4262 (while (setq e (pop eal))
4263 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4264 c (aref tag 0))
4265 (push (cons c (string-to-char (car e))) det)
4266 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4267 (substring tag 1)))))
4268 (setq det (nreverse det))
4269 (unless char
4270 (message "%s" (concat "Emphasis marker or tag:" prompt))
4271 (setq char (read-char-exclusive)))
4272 (setq char (or (cdr (assoc char det)) char))
4273 (if (equal char ?\ )
4274 (setq s "" move nil)
4275 (unless (assoc (char-to-string char) org-emphasis-alist)
4276 (error "No such emphasis marker: \"%c\"" char))
4277 (setq s (char-to-string char)))
4278 (while (and (> (length string) 1)
4279 (equal (substring string 0 1) (substring string -1))
4280 (assoc (substring string 0 1) org-emphasis-alist))
4281 (setq string (substring string 1 -1)))
4282 (setq string (concat s string s))
4283 (if beg (delete-region beg end))
4284 (unless (or (bolp)
4285 (string-match (concat "[" (nth 0 erc) "\n]")
4286 (char-to-string (char-before (point)))))
4287 (insert " "))
4288 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4289 (char-to-string (char-after (point))))
4290 (insert " ") (backward-char 1))
4291 (insert string)
4292 (and move (backward-char 1))))
4294 (defconst org-nonsticky-props
4295 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4297 (defsubst org-rear-nonsticky-at (pos)
4298 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4300 (defun org-activate-plain-links (limit)
4301 "Run through the buffer and add overlays to links."
4302 (catch 'exit
4303 (let (f)
4304 (if (re-search-forward org-plain-link-re limit t)
4305 (progn
4306 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4307 (setq f (get-text-property (match-beginning 0) 'face))
4308 (if (or (eq f 'org-tag)
4309 (and (listp f) (memq 'org-tag f)))
4311 (add-text-properties (match-beginning 0) (match-end 0)
4312 (list 'mouse-face 'highlight
4313 'keymap org-mouse-map))
4314 (org-rear-nonsticky-at (match-end 0)))
4315 t)))))
4317 (defun org-activate-code (limit)
4318 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4319 (progn
4320 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4321 (remove-text-properties (match-beginning 0) (match-end 0)
4322 '(display t invisible t intangible t))
4323 t)))
4325 (defun org-fontify-meta-lines-and-blocks (limit)
4326 "Fontify #+ lines and blocks, in the correct ways."
4327 (let ((case-fold-search t))
4328 (if (re-search-forward
4329 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4330 limit t)
4331 (let ((beg (match-beginning 0))
4332 (beg1 (line-beginning-position 2))
4333 (dc1 (downcase (match-string 2)))
4334 (dc3 (downcase (match-string 3)))
4335 end end1 quoting)
4336 (cond
4337 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4338 ;; a single line of backend-specific content
4339 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4340 (remove-text-properties (match-beginning 0) (match-end 0)
4341 '(display t invisible t intangible t))
4342 (add-text-properties (match-beginning 1) (match-end 3)
4343 '(font-lock-fontified t face org-meta-line))
4344 (add-text-properties (match-beginning 6) (match-end 6)
4345 '(font-lock-fontified t face org-block))
4347 ((and (match-end 4) (equal dc3 "begin"))
4348 ;; Truely a block
4349 (setq quoting (member (downcase (match-string 5))
4350 org-protecting-blocks))
4351 (when (re-search-forward
4352 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4353 nil t) ;; on purpose, we look further than LIMIT
4354 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4355 (when quoting
4356 (remove-text-properties beg end
4357 '(display t invisible t intangible t)))
4358 (add-text-properties
4359 beg end
4360 '(font-lock-fontified t font-lock-multiline t))
4361 (add-text-properties beg beg1 '(face org-meta-line))
4362 (add-text-properties end1 end '(face org-meta-line))
4363 (when quoting
4364 (add-text-properties beg1 end1 '(face org-block)))
4366 ((not (member (char-after beg) '(?\ ?\t)))
4367 ;; just any other in-buffer setting, but not indented
4368 (add-text-properties
4369 beg (match-end 0)
4370 '(font-lock-fontified t face org-meta-line))
4372 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4373 "orgtbl:" "tblfm:" "tblname:"))
4374 (and (match-end 4) (equal dc3 "attr")))
4375 (add-text-properties
4376 beg (match-end 0)
4377 '(font-lock-fontified t face org-meta-line))
4379 (t nil))))))
4381 (defun org-activate-angle-links (limit)
4382 "Run through the buffer and add overlays to links."
4383 (if (re-search-forward org-angle-link-re limit t)
4384 (progn
4385 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4386 (add-text-properties (match-beginning 0) (match-end 0)
4387 (list 'mouse-face 'highlight
4388 'keymap org-mouse-map))
4389 (org-rear-nonsticky-at (match-end 0))
4390 t)))
4392 (defun org-activate-footnote-links (limit)
4393 "Run through the buffer and add overlays to links."
4394 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4395 limit t)
4396 (progn
4397 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4398 (add-text-properties (match-beginning 2) (match-end 2)
4399 (list 'mouse-face 'highlight
4400 'keymap org-mouse-map
4401 'help-echo
4402 (if (= (point-at-bol) (match-beginning 2))
4403 "Footnote definition"
4404 "Footnote reference")
4406 (org-rear-nonsticky-at (match-end 2))
4407 t)))
4409 (defun org-activate-bracket-links (limit)
4410 "Run through the buffer and add overlays to bracketed links."
4411 (if (re-search-forward org-bracket-link-regexp limit t)
4412 (let* ((help (concat "LINK: "
4413 (org-match-string-no-properties 1)))
4414 ;; FIXME: above we should remove the escapes.
4415 ;; but that requires another match, protecting match data,
4416 ;; a lot of overhead for font-lock.
4417 (ip (org-maybe-intangible
4418 (list 'invisible 'org-link
4419 'keymap org-mouse-map 'mouse-face 'highlight
4420 'font-lock-multiline t 'help-echo help)))
4421 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4422 'font-lock-multiline t 'help-echo help)))
4423 ;; We need to remove the invisible property here. Table narrowing
4424 ;; may have made some of this invisible.
4425 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4426 (remove-text-properties (match-beginning 0) (match-end 0)
4427 '(invisible nil))
4428 (if (match-end 3)
4429 (progn
4430 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4431 (org-rear-nonsticky-at (match-beginning 3))
4432 (add-text-properties (match-beginning 3) (match-end 3) vp)
4433 (org-rear-nonsticky-at (match-end 3))
4434 (add-text-properties (match-end 3) (match-end 0) ip)
4435 (org-rear-nonsticky-at (match-end 0)))
4436 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4437 (org-rear-nonsticky-at (match-beginning 1))
4438 (add-text-properties (match-beginning 1) (match-end 1) vp)
4439 (org-rear-nonsticky-at (match-end 1))
4440 (add-text-properties (match-end 1) (match-end 0) ip)
4441 (org-rear-nonsticky-at (match-end 0)))
4442 t)))
4444 (defun org-activate-dates (limit)
4445 "Run through the buffer and add overlays to dates."
4446 (if (re-search-forward org-tsr-regexp-both limit t)
4447 (progn
4448 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4449 (add-text-properties (match-beginning 0) (match-end 0)
4450 (list 'mouse-face 'highlight
4451 'keymap org-mouse-map))
4452 (org-rear-nonsticky-at (match-end 0))
4453 (when org-display-custom-times
4454 (if (match-end 3)
4455 (org-display-custom-time (match-beginning 3) (match-end 3)))
4456 (org-display-custom-time (match-beginning 1) (match-end 1)))
4457 t)))
4459 (defvar org-target-link-regexp nil
4460 "Regular expression matching radio targets in plain text.")
4461 (make-variable-buffer-local 'org-target-link-regexp)
4462 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4463 "Regular expression matching a link target.")
4464 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4465 "Regular expression matching a radio target.")
4466 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4467 "Regular expression matching any target.")
4469 (defun org-activate-target-links (limit)
4470 "Run through the buffer and add overlays to target matches."
4471 (when org-target-link-regexp
4472 (let ((case-fold-search t))
4473 (if (re-search-forward org-target-link-regexp limit t)
4474 (progn
4475 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4476 (add-text-properties (match-beginning 0) (match-end 0)
4477 (list 'mouse-face 'highlight
4478 'keymap org-mouse-map
4479 'help-echo "Radio target link"
4480 'org-linked-text t))
4481 (org-rear-nonsticky-at (match-end 0))
4482 t)))))
4484 (defun org-update-radio-target-regexp ()
4485 "Find all radio targets in this file and update the regular expression."
4486 (interactive)
4487 (when (memq 'radio org-activate-links)
4488 (setq org-target-link-regexp
4489 (org-make-target-link-regexp (org-all-targets 'radio)))
4490 (org-restart-font-lock)))
4492 (defun org-hide-wide-columns (limit)
4493 (let (s e)
4494 (setq s (text-property-any (point) (or limit (point-max))
4495 'org-cwidth t))
4496 (when s
4497 (setq e (next-single-property-change s 'org-cwidth))
4498 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4499 (goto-char e)
4500 t)))
4502 (defvar org-latex-and-specials-regexp nil
4503 "Regular expression for highlighting export special stuff.")
4504 (defvar org-match-substring-regexp)
4505 (defvar org-match-substring-with-braces-regexp)
4507 ;; This should be with the exporter code, but we also use if for font-locking
4508 (defconst org-export-html-special-string-regexps
4509 '(("\\\\-" . "&shy;")
4510 ("---\\([^-]\\)" . "&mdash;\\1")
4511 ("--\\([^-]\\)" . "&ndash;\\1")
4512 ("\\.\\.\\." . "&hellip;"))
4513 "Regular expressions for special string conversion.")
4516 (defun org-compute-latex-and-specials-regexp ()
4517 "Compute regular expression for stuff treated specially by exporters."
4518 (if (not org-highlight-latex-fragments-and-specials)
4519 (org-set-local 'org-latex-and-specials-regexp nil)
4520 (require 'org-exp)
4521 (let*
4522 ((matchers (plist-get org-format-latex-options :matchers))
4523 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4524 org-latex-regexps)))
4525 (options (org-combine-plists (org-default-export-plist)
4526 (org-infile-export-plist)))
4527 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4528 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4529 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4530 (org-export-html-expand (plist-get options :expand-quoted-html))
4531 (org-export-with-special-strings (plist-get options :special-strings))
4532 (re-sub
4533 (cond
4534 ((equal org-export-with-sub-superscripts '{})
4535 (list org-match-substring-with-braces-regexp))
4536 (org-export-with-sub-superscripts
4537 (list org-match-substring-regexp))
4538 (t nil)))
4539 (re-latex
4540 (if org-export-with-LaTeX-fragments
4541 (mapcar (lambda (x) (nth 1 x)) latexs)))
4542 (re-macros
4543 (if org-export-with-TeX-macros
4544 (list (concat "\\\\"
4545 (regexp-opt
4546 (append (mapcar 'car org-html-entities)
4547 (if (boundp 'org-latex-entities)
4548 (mapcar (lambda (x)
4549 (or (car-safe x) x))
4550 org-latex-entities)
4551 nil))
4552 'words))) ; FIXME
4554 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4555 (re-special (if org-export-with-special-strings
4556 (mapcar (lambda (x) (car x))
4557 org-export-html-special-string-regexps)))
4558 (re-rest
4559 (delq nil
4560 (list
4561 (if org-export-html-expand "@<[^>\n]+>")
4562 ))))
4563 (org-set-local
4564 'org-latex-and-specials-regexp
4565 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4566 re-rest) "\\|")))))
4568 (defun org-do-latex-and-special-faces (limit)
4569 "Run through the buffer and add overlays to links."
4570 (when org-latex-and-specials-regexp
4571 (let (rtn d)
4572 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4573 limit t))
4574 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4575 'face))
4576 '(org-code org-verbatim underline)))
4577 (progn
4578 (setq rtn t
4579 d (cond ((member (char-after (1+ (match-beginning 0)))
4580 '(?_ ?^)) 1)
4581 (t 0)))
4582 (font-lock-prepend-text-property
4583 (+ d (match-beginning 0)) (match-end 0)
4584 'face 'org-latex-and-export-specials)
4585 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4586 '(font-lock-multiline t)))))
4587 rtn)))
4589 (defun org-restart-font-lock ()
4590 "Restart font-lock-mode, to force refontification."
4591 (when (and (boundp 'font-lock-mode) font-lock-mode)
4592 (font-lock-mode -1)
4593 (font-lock-mode 1)))
4595 (defun org-all-targets (&optional radio)
4596 "Return a list of all targets in this file.
4597 With optional argument RADIO, only find radio targets."
4598 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4599 rtn)
4600 (save-excursion
4601 (goto-char (point-min))
4602 (while (re-search-forward re nil t)
4603 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4604 rtn)))
4606 (defun org-make-target-link-regexp (targets)
4607 "Make regular expression matching all strings in TARGETS.
4608 The regular expression finds the targets also if there is a line break
4609 between words."
4610 (and targets
4611 (concat
4612 "\\<\\("
4613 (mapconcat
4614 (lambda (x)
4615 (while (string-match " +" x)
4616 (setq x (replace-match "\\s-+" t t x)))
4618 targets
4619 "\\|")
4620 "\\)\\>")))
4622 (defun org-activate-tags (limit)
4623 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4624 (progn
4625 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4626 (add-text-properties (match-beginning 1) (match-end 1)
4627 (list 'mouse-face 'highlight
4628 'keymap org-mouse-map))
4629 (org-rear-nonsticky-at (match-end 1))
4630 t)))
4632 (defun org-outline-level ()
4633 (save-excursion
4634 (looking-at outline-regexp)
4635 (if (match-beginning 1)
4636 (+ (org-get-string-indentation (match-string 1)) 1000)
4637 (1- (- (match-end 0) (match-beginning 0))))))
4639 (defvar org-font-lock-keywords nil)
4641 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4642 "Regular expression matching a property line.")
4644 (defvar org-font-lock-hook nil
4645 "Functions to be called for special font lock stuff.")
4647 (defun org-font-lock-hook (limit)
4648 (run-hook-with-args 'org-font-lock-hook limit))
4650 (defun org-set-font-lock-defaults ()
4651 (let* ((em org-fontify-emphasized-text)
4652 (lk org-activate-links)
4653 (org-font-lock-extra-keywords
4654 (list
4655 ;; Call the hook
4656 '(org-font-lock-hook)
4657 ;; Headlines
4658 `(,(if org-fontify-whole-heading-line
4659 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4660 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4661 (1 (org-get-level-face 1))
4662 (2 (org-get-level-face 2))
4663 (3 (org-get-level-face 3)))
4664 ;; Table lines
4665 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4666 (1 'org-table t))
4667 ;; Table internals
4668 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4669 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4670 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4671 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4672 ;; Drawers
4673 (list org-drawer-regexp '(0 'org-special-keyword t))
4674 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4675 ;; Properties
4676 (list org-property-re
4677 '(1 'org-special-keyword t)
4678 '(3 'org-property-value t))
4679 ;; Links
4680 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4681 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4682 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4683 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4684 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4685 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4686 (if (memq 'footnote lk) '(org-activate-footnote-links
4687 (2 'org-footnote t)))
4688 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4689 '(org-hide-wide-columns (0 nil append))
4690 ;; TODO lines
4691 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4692 '(1 (org-get-todo-face 1) t))
4693 ;; DONE
4694 (if org-fontify-done-headline
4695 (list (concat "^[*]+ +\\<\\("
4696 (mapconcat 'regexp-quote org-done-keywords "\\|")
4697 "\\)\\(.*\\)")
4698 '(2 'org-headline-done t))
4699 nil)
4700 ;; Priorities
4701 '(org-font-lock-add-priority-faces)
4702 ;; Tags
4703 '(org-font-lock-add-tag-faces)
4704 ;; Special keywords
4705 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4706 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4707 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4708 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4709 ;; Emphasis
4710 (if em
4711 (if (featurep 'xemacs)
4712 '(org-do-emphasis-faces (0 nil append))
4713 '(org-do-emphasis-faces)))
4714 ;; Checkboxes
4715 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4716 2 'org-checkbox prepend)
4717 (if org-provide-checkbox-statistics
4718 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4719 (0 (org-get-checkbox-statistics-face) t)))
4720 ;; Description list items
4721 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4722 2 'bold prepend)
4723 ;; ARCHIVEd headings
4724 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4725 '(1 'org-archived prepend))
4726 ;; Specials
4727 '(org-do-latex-and-special-faces)
4728 ;; Code
4729 '(org-activate-code (1 'org-code t))
4730 ;; COMMENT
4731 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4732 "\\|" org-quote-string "\\)\\>")
4733 '(1 'org-special-keyword t))
4734 '("^#.*" (0 'font-lock-comment-face t))
4735 ;; Blocks and meta lines
4736 '(org-fontify-meta-lines-and-blocks)
4738 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4739 ;; Now set the full font-lock-keywords
4740 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4741 (org-set-local 'font-lock-defaults
4742 '(org-font-lock-keywords t nil nil backward-paragraph))
4743 (kill-local-variable 'font-lock-keywords) nil))
4745 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4746 "Fontify string S like in Org-mode"
4747 (with-temp-buffer
4748 (insert s)
4749 (let ((org-odd-levels-only odd-levels))
4750 (org-mode)
4751 (font-lock-fontify-buffer)
4752 (buffer-string))))
4754 (defvar org-m nil)
4755 (defvar org-l nil)
4756 (defvar org-f nil)
4757 (defun org-get-level-face (n)
4758 "Get the right face for match N in font-lock matching of headlines."
4759 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4760 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4761 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4762 (cond
4763 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4764 ((eq n 2) org-f)
4765 (t (if org-level-color-stars-only nil org-f))))
4767 (defun org-get-todo-face (kwd)
4768 "Get the right face for a TODO keyword KWD.
4769 If KWD is a number, get the corresponding match group."
4770 (if (numberp kwd) (setq kwd (match-string kwd)))
4771 (or (cdr (assoc kwd org-todo-keyword-faces))
4772 (and (member kwd org-done-keywords) 'org-done)
4773 'org-todo))
4775 (defun org-font-lock-add-tag-faces (limit)
4776 "Add the special tag faces."
4777 (when (and org-tag-faces org-tags-special-faces-re)
4778 (while (re-search-forward org-tags-special-faces-re limit t)
4779 (add-text-properties (match-beginning 1) (match-end 1)
4780 (list 'face (org-get-tag-face 1)
4781 'font-lock-fontified t))
4782 (backward-char 1))))
4784 (defun org-font-lock-add-priority-faces (limit)
4785 "Add the special priority faces."
4786 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4787 (add-text-properties
4788 (match-beginning 0) (match-end 0)
4789 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4790 org-priority-faces))
4791 'org-special-keyword)
4792 'font-lock-fontified t))))
4794 (defun org-get-tag-face (kwd)
4795 "Get the right face for a TODO keyword KWD.
4796 If KWD is a number, get the corresponding match group."
4797 (if (numberp kwd) (setq kwd (match-string kwd)))
4798 (or (cdr (assoc kwd org-tag-faces))
4799 'org-tag))
4801 (defun org-unfontify-region (beg end &optional maybe_loudly)
4802 "Remove fontification and activation overlays from links."
4803 (font-lock-default-unfontify-region beg end)
4804 (let* ((buffer-undo-list t)
4805 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4806 (inhibit-modification-hooks t)
4807 deactivate-mark buffer-file-name buffer-file-truename)
4808 (remove-text-properties beg end
4809 '(mouse-face t keymap t org-linked-text t
4810 invisible t intangible t
4811 line-prefix t wrap-prefix t
4812 org-no-flyspell t))))
4814 ;;;; Visibility cycling, including org-goto and indirect buffer
4816 ;;; Cycling
4818 (defvar org-cycle-global-status nil)
4819 (make-variable-buffer-local 'org-cycle-global-status)
4820 (defvar org-cycle-subtree-status nil)
4821 (make-variable-buffer-local 'org-cycle-subtree-status)
4823 ;;;###autoload
4825 (defvar org-inlinetask-min-level)
4827 (defun org-cycle (&optional arg)
4828 "TAB-action and visibility cycling for Org-mode.
4830 This is the command invoked in Org-mode by the TAB key. Its main purpose
4831 is outine visibility cycling, but it also invokes other actions
4832 in special contexts.
4834 - When this function is called with a prefix argument, rotate the entire
4835 buffer through 3 states (global cycling)
4836 1. OVERVIEW: Show only top-level headlines.
4837 2. CONTENTS: Show all headlines of all levels, but no body text.
4838 3. SHOW ALL: Show everything.
4839 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4840 determined by the variable `org-startup-folded', and by any VISIBILITY
4841 properties in the buffer.
4842 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4843 including any drawers.
4845 - When inside a table, re-align the table and move to the next field.
4847 - When point is at the beginning of a headline, rotate the subtree started
4848 by this line through 3 different states (local cycling)
4849 1. FOLDED: Only the main headline is shown.
4850 2. CHILDREN: The main headline and the direct children are shown.
4851 From this state, you can move to one of the children
4852 and zoom in further.
4853 3. SUBTREE: Show the entire subtree, including body text.
4854 If there is no subtree, switch directly from CHILDREN to FOLDED.
4856 - When there is a numeric prefix, go up to a heading with level ARG, do
4857 a `show-subtree' and return to the previous cursor position. If ARG
4858 is negative, go up that many levels.
4860 - When point is not at the beginning of a headline, execute the global
4861 binding for TAB, which is re-indenting the line. See the option
4862 `org-cycle-emulate-tab' for details.
4864 - Special case: if point is at the beginning of the buffer and there is
4865 no headline in line 1, this function will act as if called with prefix arg.
4866 But only if also the variable `org-cycle-global-at-bob' is t."
4867 (interactive "P")
4868 (org-load-modules-maybe)
4869 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4870 (let* ((limit-level
4871 (or org-cycle-max-level
4872 (and (boundp 'org-inlinetask-min-level)
4873 org-inlinetask-min-level
4874 (1- org-inlinetask-min-level))))
4875 (nstars (and limit-level
4876 (if org-odd-levels-only
4877 (and limit-level (1- (* limit-level 2)))
4878 limit-level)))
4879 (outline-regexp
4880 (cond
4881 ((not (org-mode-p)) outline-regexp)
4882 ((or (eq org-cycle-include-plain-lists 'integrate)
4883 (and org-cycle-include-plain-lists (org-at-item-p)))
4884 (concat "\\(?:\\*"
4885 (if nstars (format "\\{1,%d\\}" nstars) "+")
4886 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4887 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4888 (bob-special (and org-cycle-global-at-bob (bobp)
4889 (not (looking-at outline-regexp))))
4890 (org-cycle-hook
4891 (if bob-special
4892 (delq 'org-optimize-window-after-visibility-change
4893 (copy-sequence org-cycle-hook))
4894 org-cycle-hook))
4895 (pos (point)))
4897 (if (or bob-special (equal arg '(4)))
4898 ;; special case: use global cycling
4899 (setq arg t))
4901 (cond
4903 ((equal arg '(16))
4904 (org-set-startup-visibility)
4905 (message "Startup visibility, plus VISIBILITY properties"))
4907 ((equal arg '(64))
4908 (show-all)
4909 (message "Entire buffer visible, including drawers"))
4911 ((org-at-table-p 'any)
4912 ;; Enter the table or move to the next field in the table
4913 (or (org-table-recognize-table.el)
4914 (progn
4915 (if arg (org-table-edit-field t)
4916 (org-table-justify-field-maybe)
4917 (call-interactively 'org-table-next-field)))))
4919 ((run-hook-with-args-until-success
4920 'org-tab-after-check-for-table-hook))
4922 ((eq arg t) ;; Global cycling
4923 (org-cycle-internal-global))
4925 ((and org-drawers org-drawer-regexp
4926 (save-excursion
4927 (beginning-of-line 1)
4928 (looking-at org-drawer-regexp)))
4929 ;; Toggle block visibility
4930 (org-flag-drawer
4931 (not (get-char-property (match-end 0) 'invisible))))
4933 ((integerp arg)
4934 ;; Show-subtree, ARG levels up from here.
4935 (save-excursion
4936 (org-back-to-heading)
4937 (outline-up-heading (if (< arg 0) (- arg)
4938 (- (funcall outline-level) arg)))
4939 (org-show-subtree)))
4941 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4942 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4944 (org-cycle-internal-local))
4946 ;; TAB emulation and template completion
4947 (buffer-read-only (org-back-to-heading))
4949 ((run-hook-with-args-until-success
4950 'org-tab-after-check-for-cycling-hook))
4952 ((org-try-structure-completion))
4954 ((org-try-cdlatex-tab))
4956 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4957 (or (not (bolp))
4958 (not (looking-at outline-regexp))))
4959 (call-interactively (global-key-binding "\t")))
4961 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4962 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4963 (or (and (eq org-cycle-emulate-tab 'white)
4964 (= (match-end 0) (point-at-eol)))
4965 (and (eq org-cycle-emulate-tab 'whitestart)
4966 (>= (match-end 0) pos))))
4968 (eq org-cycle-emulate-tab t))
4969 (call-interactively (global-key-binding "\t")))
4971 (t (save-excursion
4972 (org-back-to-heading)
4973 (org-cycle)))))))
4975 (defun org-cycle-internal-global ()
4976 "Do the global cycling action."
4977 (cond
4978 ((and (eq last-command this-command)
4979 (eq org-cycle-global-status 'overview))
4980 ;; We just created the overview - now do table of contents
4981 ;; This can be slow in very large buffers, so indicate action
4982 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4983 (message "CONTENTS...")
4984 (org-content)
4985 (message "CONTENTS...done")
4986 (setq org-cycle-global-status 'contents)
4987 (run-hook-with-args 'org-cycle-hook 'contents))
4989 ((and (eq last-command this-command)
4990 (eq org-cycle-global-status 'contents))
4991 ;; We just showed the table of contents - now show everything
4992 (run-hook-with-args 'org-pre-cycle-hook 'all)
4993 (show-all)
4994 (message "SHOW ALL")
4995 (setq org-cycle-global-status 'all)
4996 (run-hook-with-args 'org-cycle-hook 'all))
4999 ;; Default action: go to overview
5000 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5001 (org-overview)
5002 (message "OVERVIEW")
5003 (setq org-cycle-global-status 'overview)
5004 (run-hook-with-args 'org-cycle-hook 'overview))))
5006 (defun org-cycle-internal-local ()
5007 "Do the local cycling action."
5008 (org-back-to-heading)
5009 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5010 ;; First, some boundaries
5011 (save-excursion
5012 (org-back-to-heading)
5013 (setq level (funcall outline-level))
5014 (save-excursion
5015 (beginning-of-line 2)
5016 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5017 ; XEmacs does not have `next-single-char-property-change'
5018 ; I'm not sure about Emacs 21.
5019 (while (and (not (eobp)) ;; this is like `next-line'
5020 (get-char-property (1- (point)) 'invisible))
5021 (beginning-of-line 2))
5022 (while (and (not (eobp)) ;; this is like `next-line'
5023 (get-char-property (1- (point)) 'invisible))
5024 (goto-char (next-single-char-property-change (point) 'invisible))
5025 ;;;??? (or (bolp) (beginning-of-line 2))))
5026 (and (eolp) (beginning-of-line 2))))
5027 (setq eol (point)))
5028 (outline-end-of-heading) (setq eoh (point))
5029 (save-excursion
5030 (outline-next-heading)
5031 (setq has-children (and (org-at-heading-p t)
5032 (> (funcall outline-level) level))))
5033 (org-end-of-subtree t)
5034 (unless (eobp)
5035 (skip-chars-forward " \t\n")
5036 (beginning-of-line 1) ; in case this is an item
5038 (setq eos (if (eobp) (point) (1- (point)))))
5039 ;; Find out what to do next and set `this-command'
5040 (cond
5041 ((= eos eoh)
5042 ;; Nothing is hidden behind this heading
5043 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5044 (message "EMPTY ENTRY")
5045 (setq org-cycle-subtree-status nil)
5046 (save-excursion
5047 (goto-char eos)
5048 (outline-next-heading)
5049 (if (org-invisible-p) (org-flag-heading nil))))
5050 ((and (or (>= eol eos)
5051 (not (string-match "\\S-" (buffer-substring eol eos))))
5052 (or has-children
5053 (not (setq children-skipped
5054 org-cycle-skip-children-state-if-no-children))))
5055 ;; Entire subtree is hidden in one line: children view
5056 (run-hook-with-args 'org-pre-cycle-hook 'children)
5057 (org-show-entry)
5058 (show-children)
5059 (message "CHILDREN")
5060 (save-excursion
5061 (goto-char eos)
5062 (outline-next-heading)
5063 (if (org-invisible-p) (org-flag-heading nil)))
5064 (setq org-cycle-subtree-status 'children)
5065 (run-hook-with-args 'org-cycle-hook 'children))
5066 ((or children-skipped
5067 (and (eq last-command this-command)
5068 (eq org-cycle-subtree-status 'children)))
5069 ;; We just showed the children, or no children are there,
5070 ;; now show everything.
5071 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5072 (org-show-subtree)
5073 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5074 (setq org-cycle-subtree-status 'subtree)
5075 (run-hook-with-args 'org-cycle-hook 'subtree))
5077 ;; Default action: hide the subtree.
5078 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5079 (hide-subtree)
5080 (message "FOLDED")
5081 (setq org-cycle-subtree-status 'folded)
5082 (run-hook-with-args 'org-cycle-hook 'folded)))))
5084 ;;;###autoload
5085 (defun org-global-cycle (&optional arg)
5086 "Cycle the global visibility. For details see `org-cycle'.
5087 With C-u prefix arg, switch to startup visibility.
5088 With a numeric prefix, show all headlines up to that level."
5089 (interactive "P")
5090 (let ((org-cycle-include-plain-lists
5091 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5092 (cond
5093 ((integerp arg)
5094 (show-all)
5095 (hide-sublevels arg)
5096 (setq org-cycle-global-status 'contents))
5097 ((equal arg '(4))
5098 (org-set-startup-visibility)
5099 (message "Startup visibility, plus VISIBILITY properties."))
5101 (org-cycle '(4))))))
5103 (defun org-set-startup-visibility ()
5104 "Set the visibility required by startup options and properties."
5105 (cond
5106 ((eq org-startup-folded t)
5107 (org-cycle '(4)))
5108 ((eq org-startup-folded 'content)
5109 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5110 (org-cycle '(4)) (org-cycle '(4)))))
5111 (unless (eq org-startup-folded 'showeverything)
5112 (if org-hide-block-startup (org-hide-block-all))
5113 (org-set-visibility-according-to-property 'no-cleanup)
5114 (org-cycle-hide-archived-subtrees 'all)
5115 (org-cycle-hide-drawers 'all)
5116 (org-cycle-show-empty-lines 'all)))
5118 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5119 "Switch subtree visibilities according to :VISIBILITY: property."
5120 (interactive)
5121 (let (org-show-entry-below state)
5122 (save-excursion
5123 (goto-char (point-min))
5124 (while (re-search-forward
5125 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5126 nil t)
5127 (setq state (match-string 1))
5128 (save-excursion
5129 (org-back-to-heading t)
5130 (hide-subtree)
5131 (org-reveal)
5132 (cond
5133 ((equal state '("fold" "folded"))
5134 (hide-subtree))
5135 ((equal state "children")
5136 (org-show-hidden-entry)
5137 (show-children))
5138 ((equal state "content")
5139 (save-excursion
5140 (save-restriction
5141 (org-narrow-to-subtree)
5142 (org-content))))
5143 ((member state '("all" "showall"))
5144 (show-subtree)))))
5145 (unless no-cleanup
5146 (org-cycle-hide-archived-subtrees 'all)
5147 (org-cycle-hide-drawers 'all)
5148 (org-cycle-show-empty-lines 'all)))))
5150 (defun org-overview ()
5151 "Switch to overview mode, showing only top-level headlines.
5152 Really, this shows all headlines with level equal or greater than the level
5153 of the first headline in the buffer. This is important, because if the
5154 first headline is not level one, then (hide-sublevels 1) gives confusing
5155 results."
5156 (interactive)
5157 (let ((level (save-excursion
5158 (goto-char (point-min))
5159 (if (re-search-forward (concat "^" outline-regexp) nil t)
5160 (progn
5161 (goto-char (match-beginning 0))
5162 (funcall outline-level))))))
5163 (and level (hide-sublevels level))))
5165 (defun org-content (&optional arg)
5166 "Show all headlines in the buffer, like a table of contents.
5167 With numerical argument N, show content up to level N."
5168 (interactive "P")
5169 (save-excursion
5170 ;; Visit all headings and show their offspring
5171 (and (integerp arg) (org-overview))
5172 (goto-char (point-max))
5173 (catch 'exit
5174 (while (and (progn (condition-case nil
5175 (outline-previous-visible-heading 1)
5176 (error (goto-char (point-min))))
5178 (looking-at outline-regexp))
5179 (if (integerp arg)
5180 (show-children (1- arg))
5181 (show-branches))
5182 (if (bobp) (throw 'exit nil))))))
5185 (defun org-optimize-window-after-visibility-change (state)
5186 "Adjust the window after a change in outline visibility.
5187 This function is the default value of the hook `org-cycle-hook'."
5188 (when (get-buffer-window (current-buffer))
5189 (cond
5190 ((eq state 'content) nil)
5191 ((eq state 'all) nil)
5192 ((eq state 'folded) nil)
5193 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5194 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5196 ;; FIXME: no longer in use
5197 (defun org-compact-display-after-subtree-move ()
5198 "Show a compacter version of the tree of the entry's parent."
5199 (save-excursion
5200 (if (org-up-heading-safe)
5201 (progn
5202 (hide-subtree)
5203 (show-entry)
5204 (show-children)
5205 (org-cycle-show-empty-lines 'children)
5206 (org-cycle-hide-drawers 'children))
5207 (org-overview))))
5209 (defun org-remove-empty-overlays-at (pos)
5210 "Remove outline overlays that do not contain non-white stuff."
5211 (mapc
5212 (lambda (o)
5213 (and (eq 'outline (org-overlay-get o 'invisible))
5214 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5215 (org-overlay-end o))))
5216 (org-delete-overlay o)))
5217 (org-overlays-at pos)))
5219 (defun org-clean-visibility-after-subtree-move ()
5220 "Fix visibility issues after moving a subtree."
5221 ;; First, find a reasonable region to look at:
5222 ;; Start two siblings above, end three below
5223 (let* ((beg (save-excursion
5224 (and (org-get-last-sibling)
5225 (org-get-last-sibling))
5226 (point)))
5227 (end (save-excursion
5228 (and (org-get-next-sibling)
5229 (org-get-next-sibling)
5230 (org-get-next-sibling))
5231 (if (org-at-heading-p)
5232 (point-at-eol)
5233 (point))))
5234 (level (looking-at "\\*+"))
5235 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5236 (save-excursion
5237 (save-restriction
5238 (narrow-to-region beg end)
5239 (when re
5240 ;; Properly fold already folded siblings
5241 (goto-char (point-min))
5242 (while (re-search-forward re nil t)
5243 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5244 (hide-entry))))
5245 (org-cycle-show-empty-lines 'overview)
5246 (org-cycle-hide-drawers 'overview)))))
5248 (defun org-cycle-show-empty-lines (state)
5249 "Show empty lines above all visible headlines.
5250 The region to be covered depends on STATE when called through
5251 `org-cycle-hook'. Lisp program can use t for STATE to get the
5252 entire buffer covered. Note that an empty line is only shown if there
5253 are at least `org-cycle-separator-lines' empty lines before the headline."
5254 (when (not (= org-cycle-separator-lines 0))
5255 (save-excursion
5256 (let* ((n (abs org-cycle-separator-lines))
5257 (re (cond
5258 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5259 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5260 (t (let ((ns (number-to-string (- n 2))))
5261 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5262 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5263 beg end b e)
5264 (cond
5265 ((memq state '(overview contents t))
5266 (setq beg (point-min) end (point-max)))
5267 ((memq state '(children folded))
5268 (setq beg (point) end (progn (org-end-of-subtree t t)
5269 (beginning-of-line 2)
5270 (point)))))
5271 (when beg
5272 (goto-char beg)
5273 (while (re-search-forward re end t)
5274 (unless (get-char-property (match-end 1) 'invisible)
5275 (setq e (match-end 1))
5276 (if (< org-cycle-separator-lines 0)
5277 (setq b (save-excursion
5278 (goto-char (match-beginning 0))
5279 (org-back-over-empty-lines)
5280 (if (save-excursion
5281 (goto-char (max (point-min) (1- (point))))
5282 (org-on-heading-p))
5283 (1- (point))
5284 (point))))
5285 (setq b (match-beginning 1)))
5286 (outline-flag-region b e nil)))))))
5287 ;; Never hide empty lines at the end of the file.
5288 (save-excursion
5289 (goto-char (point-max))
5290 (outline-previous-heading)
5291 (outline-end-of-heading)
5292 (if (and (looking-at "[ \t\n]+")
5293 (= (match-end 0) (point-max)))
5294 (outline-flag-region (point) (match-end 0) nil))))
5296 (defun org-show-empty-lines-in-parent ()
5297 "Move to the parent and re-show empty lines before visible headlines."
5298 (save-excursion
5299 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5300 (org-cycle-show-empty-lines context))))
5302 (defun org-cycle-hide-drawers (state)
5303 "Re-hide all drawers after a visibility state change."
5304 (when (and (org-mode-p)
5305 (not (memq state '(overview folded contents))))
5306 (save-excursion
5307 (let* ((globalp (memq state '(contents all)))
5308 (beg (if globalp (point-min) (point)))
5309 (end (if globalp (point-max)
5310 (if (eq state 'children)
5311 (save-excursion (outline-next-heading) (point))
5312 (org-end-of-subtree t)))))
5313 (goto-char beg)
5314 (while (re-search-forward org-drawer-regexp end t)
5315 (org-flag-drawer t))))))
5317 (defun org-flag-drawer (flag)
5318 (save-excursion
5319 (beginning-of-line 1)
5320 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5321 (let ((b (match-end 0))
5322 (outline-regexp org-outline-regexp))
5323 (if (re-search-forward
5324 "^[ \t]*:END:"
5325 (save-excursion (outline-next-heading) (point)) t)
5326 (outline-flag-region b (point-at-eol) flag)
5327 (error ":END: line missing at position %s" b))))))
5329 (defun org-subtree-end-visible-p ()
5330 "Is the end of the current subtree visible?"
5331 (pos-visible-in-window-p
5332 (save-excursion (org-end-of-subtree t) (point))))
5334 (defun org-first-headline-recenter (&optional N)
5335 "Move cursor to the first headline and recenter the headline.
5336 Optional argument N means, put the headline into the Nth line of the window."
5337 (goto-char (point-min))
5338 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5339 (beginning-of-line)
5340 (recenter (prefix-numeric-value N))))
5342 ;;; Folding of blocks
5344 (defconst org-block-regexp
5346 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5347 "Regular expression for hiding blocks.")
5349 (defvar org-hide-block-overlays nil
5350 "Overays hiding blocks.")
5351 (make-variable-buffer-local 'org-hide-block-overlays)
5353 (defun org-block-map (function &optional start end)
5354 "Call func at the head of all source blocks in the current
5355 buffer. Optional arguments START and END can be used to limit
5356 the range."
5357 (let ((start (or start (point-min)))
5358 (end (or end (point-max))))
5359 (save-excursion
5360 (goto-char start)
5361 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5362 (save-excursion
5363 (save-match-data
5364 (goto-char (match-beginning 0))
5365 (funcall function)))))))
5367 (defun org-hide-block-toggle-all ()
5368 "Toggle the visibility of all blocks in the current buffer."
5369 (org-block-map #'org-hide-block-toggle))
5371 (defun org-hide-block-all ()
5372 "Fold all blocks in the current buffer."
5373 (interactive)
5374 (org-show-block-all)
5375 (org-block-map #'org-hide-block-toggle-maybe))
5377 (defun org-show-block-all ()
5378 "Unfold all blocks in the current buffer."
5379 (mapc 'org-delete-overlay org-hide-block-overlays)
5380 (setq org-hide-block-overlays nil))
5382 (defun org-hide-block-toggle-maybe ()
5383 "Toggle visibility of block at point."
5384 (interactive)
5385 (let ((case-fold-search t))
5386 (if (save-excursion
5387 (beginning-of-line 1)
5388 (looking-at org-block-regexp))
5389 (progn (org-hide-block-toggle)
5390 t) ;; to signal that we took action
5391 nil))) ;; to signal that we did not
5393 (defun org-hide-block-toggle (&optional force)
5394 "Toggle the visibility of the current block."
5395 (interactive)
5396 (save-excursion
5397 (beginning-of-line)
5398 (if (re-search-forward org-block-regexp nil t)
5399 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5400 (end (match-end 0)) ;; end of entire body
5402 (if (memq t (mapcar (lambda (overlay)
5403 (eq (org-overlay-get overlay 'invisible)
5404 'org-hide-block))
5405 (org-overlays-at start)))
5406 (if (or (not force) (eq force 'off))
5407 (mapc (lambda (ov)
5408 (when (member ov org-hide-block-overlays)
5409 (setq org-hide-block-overlays
5410 (delq ov org-hide-block-overlays)))
5411 (when (eq (org-overlay-get ov 'invisible)
5412 'org-hide-block)
5413 (org-delete-overlay ov)))
5414 (org-overlays-at start)))
5415 (setq ov (org-make-overlay start end))
5416 (org-overlay-put ov 'invisible 'org-hide-block)
5417 ;; make the block accessible to isearch
5418 (org-overlay-put
5419 ov 'isearch-open-invisible
5420 (lambda (ov)
5421 (when (member ov org-hide-block-overlays)
5422 (setq org-hide-block-overlays
5423 (delq ov org-hide-block-overlays)))
5424 (when (eq (org-overlay-get ov 'invisible)
5425 'org-hide-block)
5426 (org-delete-overlay ov))))
5427 (push ov org-hide-block-overlays)))
5428 (error "Not looking at a source block"))))
5430 ;; org-tab-after-check-for-cycling-hook
5431 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5432 ;; Remove overlays when changing major mode
5433 (add-hook 'org-mode-hook
5434 (lambda () (org-add-hook 'change-major-mode-hook
5435 'org-show-block-all 'append 'local)))
5437 ;;; Org-goto
5439 (defvar org-goto-window-configuration nil)
5440 (defvar org-goto-marker nil)
5441 (defvar org-goto-map
5442 (let ((map (make-sparse-keymap)))
5443 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5444 (while (setq cmd (pop cmds))
5445 (substitute-key-definition cmd cmd map global-map)))
5446 (suppress-keymap map)
5447 (org-defkey map "\C-m" 'org-goto-ret)
5448 (org-defkey map [(return)] 'org-goto-ret)
5449 (org-defkey map [(left)] 'org-goto-left)
5450 (org-defkey map [(right)] 'org-goto-right)
5451 (org-defkey map [(control ?g)] 'org-goto-quit)
5452 (org-defkey map "\C-i" 'org-cycle)
5453 (org-defkey map [(tab)] 'org-cycle)
5454 (org-defkey map [(down)] 'outline-next-visible-heading)
5455 (org-defkey map [(up)] 'outline-previous-visible-heading)
5456 (if org-goto-auto-isearch
5457 (if (fboundp 'define-key-after)
5458 (define-key-after map [t] 'org-goto-local-auto-isearch)
5459 nil)
5460 (org-defkey map "q" 'org-goto-quit)
5461 (org-defkey map "n" 'outline-next-visible-heading)
5462 (org-defkey map "p" 'outline-previous-visible-heading)
5463 (org-defkey map "f" 'outline-forward-same-level)
5464 (org-defkey map "b" 'outline-backward-same-level)
5465 (org-defkey map "u" 'outline-up-heading))
5466 (org-defkey map "/" 'org-occur)
5467 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5468 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5469 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5470 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5471 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5472 map))
5474 (defconst org-goto-help
5475 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5476 RET=jump to location [Q]uit and return to previous location
5477 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5479 (defvar org-goto-start-pos) ; dynamically scoped parameter
5481 ;; FIXME: Docstring doe not mention both interfaces
5482 (defun org-goto (&optional alternative-interface)
5483 "Look up a different location in the current file, keeping current visibility.
5485 When you want look-up or go to a different location in a document, the
5486 fastest way is often to fold the entire buffer and then dive into the tree.
5487 This method has the disadvantage, that the previous location will be folded,
5488 which may not be what you want.
5490 This command works around this by showing a copy of the current buffer
5491 in an indirect buffer, in overview mode. You can dive into the tree in
5492 that copy, use org-occur and incremental search to find a location.
5493 When pressing RET or `Q', the command returns to the original buffer in
5494 which the visibility is still unchanged. After RET is will also jump to
5495 the location selected in the indirect buffer and expose the
5496 the headline hierarchy above."
5497 (interactive "P")
5498 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5499 (org-refile-use-outline-path t)
5500 (org-refile-target-verify-function nil)
5501 (interface
5502 (if (not alternative-interface)
5503 org-goto-interface
5504 (if (eq org-goto-interface 'outline)
5505 'outline-path-completion
5506 'outline)))
5507 (org-goto-start-pos (point))
5508 (selected-point
5509 (if (eq interface 'outline)
5510 (car (org-get-location (current-buffer) org-goto-help))
5511 (nth 3 (org-refile-get-location "Goto: ")))))
5512 (if selected-point
5513 (progn
5514 (org-mark-ring-push org-goto-start-pos)
5515 (goto-char selected-point)
5516 (if (or (org-invisible-p) (org-invisible-p2))
5517 (org-show-context 'org-goto)))
5518 (message "Quit"))))
5520 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5521 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5522 (defvar org-goto-local-auto-isearch-map) ; defined below
5524 (defun org-get-location (buf help)
5525 "Let the user select a location in the Org-mode buffer BUF.
5526 This function uses a recursive edit. It returns the selected position
5527 or nil."
5528 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5529 (isearch-hide-immediately nil)
5530 (isearch-search-fun-function
5531 (lambda () 'org-goto-local-search-headings))
5532 (org-goto-selected-point org-goto-exit-command))
5533 (save-excursion
5534 (save-window-excursion
5535 (delete-other-windows)
5536 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5537 (switch-to-buffer
5538 (condition-case nil
5539 (make-indirect-buffer (current-buffer) "*org-goto*")
5540 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5541 (with-output-to-temp-buffer "*Help*"
5542 (princ help))
5543 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5544 (setq buffer-read-only nil)
5545 (let ((org-startup-truncated t)
5546 (org-startup-folded nil)
5547 (org-startup-align-all-tables nil))
5548 (org-mode)
5549 (org-overview))
5550 (setq buffer-read-only t)
5551 (if (and (boundp 'org-goto-start-pos)
5552 (integer-or-marker-p org-goto-start-pos))
5553 (let ((org-show-hierarchy-above t)
5554 (org-show-siblings t)
5555 (org-show-following-heading t))
5556 (goto-char org-goto-start-pos)
5557 (and (org-invisible-p) (org-show-context)))
5558 (goto-char (point-min)))
5559 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5560 (message "Select location and press RET")
5561 (use-local-map org-goto-map)
5562 (recursive-edit)
5564 (kill-buffer "*org-goto*")
5565 (cons org-goto-selected-point org-goto-exit-command)))
5567 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5568 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5569 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5570 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5572 (defun org-goto-local-search-headings (string bound noerror)
5573 "Search and make sure that any matches are in headlines."
5574 (catch 'return
5575 (while (if isearch-forward
5576 (search-forward string bound noerror)
5577 (search-backward string bound noerror))
5578 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5579 (and (member :headline context)
5580 (not (member :tags context))))
5581 (throw 'return (point))))))
5583 (defun org-goto-local-auto-isearch ()
5584 "Start isearch."
5585 (interactive)
5586 (goto-char (point-min))
5587 (let ((keys (this-command-keys)))
5588 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5589 (isearch-mode t)
5590 (isearch-process-search-char (string-to-char keys)))))
5592 (defun org-goto-ret (&optional arg)
5593 "Finish `org-goto' by going to the new location."
5594 (interactive "P")
5595 (setq org-goto-selected-point (point)
5596 org-goto-exit-command 'return)
5597 (throw 'exit nil))
5599 (defun org-goto-left ()
5600 "Finish `org-goto' by going to the new location."
5601 (interactive)
5602 (if (org-on-heading-p)
5603 (progn
5604 (beginning-of-line 1)
5605 (setq org-goto-selected-point (point)
5606 org-goto-exit-command 'left)
5607 (throw 'exit nil))
5608 (error "Not on a heading")))
5610 (defun org-goto-right ()
5611 "Finish `org-goto' by going to the new location."
5612 (interactive)
5613 (if (org-on-heading-p)
5614 (progn
5615 (setq org-goto-selected-point (point)
5616 org-goto-exit-command 'right)
5617 (throw 'exit nil))
5618 (error "Not on a heading")))
5620 (defun org-goto-quit ()
5621 "Finish `org-goto' without cursor motion."
5622 (interactive)
5623 (setq org-goto-selected-point nil)
5624 (setq org-goto-exit-command 'quit)
5625 (throw 'exit nil))
5627 ;;; Indirect buffer display of subtrees
5629 (defvar org-indirect-dedicated-frame nil
5630 "This is the frame being used for indirect tree display.")
5631 (defvar org-last-indirect-buffer nil)
5633 (defun org-tree-to-indirect-buffer (&optional arg)
5634 "Create indirect buffer and narrow it to current subtree.
5635 With numerical prefix ARG, go up to this level and then take that tree.
5636 If ARG is negative, go up that many levels.
5637 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5638 indirect buffer previously made with this command, to avoid proliferation of
5639 indirect buffers. However, when you call the command with a `C-u' prefix, or
5640 when `org-indirect-buffer-display' is `new-frame', the last buffer
5641 is kept so that you can work with several indirect buffers at the same time.
5642 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5643 requests that a new frame be made for the new buffer, so that the dedicated
5644 frame is not changed."
5645 (interactive "P")
5646 (let ((cbuf (current-buffer))
5647 (cwin (selected-window))
5648 (pos (point))
5649 beg end level heading ibuf)
5650 (save-excursion
5651 (org-back-to-heading t)
5652 (when (numberp arg)
5653 (setq level (org-outline-level))
5654 (if (< arg 0) (setq arg (+ level arg)))
5655 (while (> (setq level (org-outline-level)) arg)
5656 (outline-up-heading 1 t)))
5657 (setq beg (point)
5658 heading (org-get-heading))
5659 (org-end-of-subtree t t) (setq end (point)))
5660 (if (and (buffer-live-p org-last-indirect-buffer)
5661 (not (eq org-indirect-buffer-display 'new-frame))
5662 (not arg))
5663 (kill-buffer org-last-indirect-buffer))
5664 (setq ibuf (org-get-indirect-buffer cbuf)
5665 org-last-indirect-buffer ibuf)
5666 (cond
5667 ((or (eq org-indirect-buffer-display 'new-frame)
5668 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5669 (select-frame (make-frame))
5670 (delete-other-windows)
5671 (switch-to-buffer ibuf)
5672 (org-set-frame-title heading))
5673 ((eq org-indirect-buffer-display 'dedicated-frame)
5674 (raise-frame
5675 (select-frame (or (and org-indirect-dedicated-frame
5676 (frame-live-p org-indirect-dedicated-frame)
5677 org-indirect-dedicated-frame)
5678 (setq org-indirect-dedicated-frame (make-frame)))))
5679 (delete-other-windows)
5680 (switch-to-buffer ibuf)
5681 (org-set-frame-title (concat "Indirect: " heading)))
5682 ((eq org-indirect-buffer-display 'current-window)
5683 (switch-to-buffer ibuf))
5684 ((eq org-indirect-buffer-display 'other-window)
5685 (pop-to-buffer ibuf))
5686 (t (error "Invalid value.")))
5687 (if (featurep 'xemacs)
5688 (save-excursion (org-mode) (turn-on-font-lock)))
5689 (narrow-to-region beg end)
5690 (show-all)
5691 (goto-char pos)
5692 (and (window-live-p cwin) (select-window cwin))))
5694 (defun org-get-indirect-buffer (&optional buffer)
5695 (setq buffer (or buffer (current-buffer)))
5696 (let ((n 1) (base (buffer-name buffer)) bname)
5697 (while (buffer-live-p
5698 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5699 (setq n (1+ n)))
5700 (condition-case nil
5701 (make-indirect-buffer buffer bname 'clone)
5702 (error (make-indirect-buffer buffer bname)))))
5704 (defun org-set-frame-title (title)
5705 "Set the title of the current frame to the string TITLE."
5706 ;; FIXME: how to name a single frame in XEmacs???
5707 (unless (featurep 'xemacs)
5708 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5710 ;;;; Structure editing
5712 ;;; Inserting headlines
5714 (defun org-previous-line-empty-p ()
5715 (save-excursion
5716 (and (not (bobp))
5717 (or (beginning-of-line 0) t)
5718 (save-match-data
5719 (looking-at "[ \t]*$")))))
5721 (defun org-insert-heading (&optional force-heading)
5722 "Insert a new heading or item with same depth at point.
5723 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5724 If point is at the beginning of a headline, insert a sibling before the
5725 current headline. If point is not at the beginning, do not split the line,
5726 but create the new headline after the current line."
5727 (interactive "P")
5728 (if (= (buffer-size) 0)
5729 (insert "\n* ")
5730 (when (or force-heading (not (org-insert-item)))
5731 (let* ((empty-line-p nil)
5732 (head (save-excursion
5733 (condition-case nil
5734 (progn
5735 (org-back-to-heading)
5736 (setq empty-line-p (org-previous-line-empty-p))
5737 (match-string 0))
5738 (error "*"))))
5739 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5740 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5741 pos hide-previous previous-pos)
5742 (cond
5743 ((and (org-on-heading-p) (bolp)
5744 (or (bobp)
5745 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5746 ;; insert before the current line
5747 (open-line (if blank 2 1)))
5748 ((and (bolp)
5749 (not org-insert-heading-respect-content)
5750 (or (bobp)
5751 (save-excursion
5752 (backward-char 1) (not (org-invisible-p)))))
5753 ;; insert right here
5754 nil)
5756 ;; somewhere in the line
5757 (save-excursion
5758 (setq previous-pos (point-at-bol))
5759 (end-of-line)
5760 (setq hide-previous (org-invisible-p)))
5761 (and org-insert-heading-respect-content (org-show-subtree))
5762 (let ((split
5763 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5764 (save-excursion
5765 (let ((p (point)))
5766 (goto-char (point-at-bol))
5767 (and (looking-at org-complex-heading-regexp)
5768 (> p (match-beginning 4)))))))
5769 tags pos)
5770 (cond
5771 (org-insert-heading-respect-content
5772 (org-end-of-subtree nil t)
5773 (or (bolp) (newline))
5774 (or (org-previous-line-empty-p)
5775 (and blank (newline)))
5776 (open-line 1))
5777 ((org-on-heading-p)
5778 (when hide-previous
5779 (show-children)
5780 (org-show-entry))
5781 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5782 (setq tags (and (match-end 2) (match-string 2)))
5783 (and (match-end 1)
5784 (delete-region (match-beginning 1) (match-end 1)))
5785 (setq pos (point-at-bol))
5786 (or split (end-of-line 1))
5787 (delete-horizontal-space)
5788 (newline (if blank 2 1))
5789 (when tags
5790 (save-excursion
5791 (goto-char pos)
5792 (end-of-line 1)
5793 (insert " " tags)
5794 (org-set-tags nil 'align))))
5796 (or split (end-of-line 1))
5797 (newline (if blank 2 1)))))))
5798 (insert head) (just-one-space)
5799 (setq pos (point))
5800 (end-of-line 1)
5801 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5802 (when (and org-insert-heading-respect-content hide-previous)
5803 (save-excursion
5804 (goto-char previous-pos)
5805 (hide-subtree)))
5806 (run-hooks 'org-insert-heading-hook)))))
5808 (defun org-get-heading (&optional no-tags)
5809 "Return the heading of the current entry, without the stars."
5810 (save-excursion
5811 (org-back-to-heading t)
5812 (if (looking-at
5813 (if no-tags
5814 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5815 "\\*+[ \t]+\\([^\r\n]*\\)"))
5816 (match-string 1) "")))
5818 (defun org-heading-components ()
5819 "Return the components of the current heading.
5820 This is a list with the following elements:
5821 - the level as an integer
5822 - the reduced level, different if `org-odd-levels-only' is set.
5823 - the TODO keyword, or nil
5824 - the priority character, like ?A, or nil if no priority is given
5825 - the headline text itself, or the tags string if no headline text
5826 - the tags string, or nil."
5827 (save-excursion
5828 (org-back-to-heading t)
5829 (if (looking-at org-complex-heading-regexp)
5830 (list (length (match-string 1))
5831 (org-reduced-level (length (match-string 1)))
5832 (org-match-string-no-properties 2)
5833 (and (match-end 3) (aref (match-string 3) 2))
5834 (org-match-string-no-properties 4)
5835 (org-match-string-no-properties 5)))))
5837 (defun org-get-entry ()
5838 "Get the entry text, after heading, entire subtree."
5839 (save-excursion
5840 (org-back-to-heading t)
5841 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5843 (defun org-insert-heading-after-current ()
5844 "Insert a new heading with same level as current, after current subtree."
5845 (interactive)
5846 (org-back-to-heading)
5847 (org-insert-heading)
5848 (org-move-subtree-down)
5849 (end-of-line 1))
5851 (defun org-insert-heading-respect-content ()
5852 (interactive)
5853 (let ((org-insert-heading-respect-content t))
5854 (org-insert-heading t)))
5856 (defun org-insert-todo-heading-respect-content (&optional force-state)
5857 (interactive "P")
5858 (let ((org-insert-heading-respect-content t))
5859 (org-insert-todo-heading force-state t)))
5861 (defun org-insert-todo-heading (arg &optional force-heading)
5862 "Insert a new heading with the same level and TODO state as current heading.
5863 If the heading has no TODO state, or if the state is DONE, use the first
5864 state (TODO by default). Also with prefix arg, force first state."
5865 (interactive "P")
5866 (when (or force-heading (not (org-insert-item 'checkbox)))
5867 (org-insert-heading force-heading)
5868 (save-excursion
5869 (org-back-to-heading)
5870 (outline-previous-heading)
5871 (looking-at org-todo-line-regexp))
5872 (let*
5873 ((new-mark-x
5874 (if (or arg
5875 (not (match-beginning 2))
5876 (member (match-string 2) org-done-keywords))
5877 (car org-todo-keywords-1)
5878 (match-string 2)))
5879 (new-mark
5881 (run-hook-with-args-until-success
5882 'org-todo-get-default-hook new-mark-x nil)
5883 new-mark-x)))
5884 (beginning-of-line 1)
5885 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5886 (if org-treat-insert-todo-heading-as-state-change
5887 (org-todo new-mark)
5888 (insert new-mark " "))))
5889 (when org-provide-todo-statistics
5890 (org-update-parent-todo-statistics))))
5892 (defun org-insert-subheading (arg)
5893 "Insert a new subheading and demote it.
5894 Works for outline headings and for plain lists alike."
5895 (interactive "P")
5896 (org-insert-heading arg)
5897 (cond
5898 ((org-on-heading-p) (org-do-demote))
5899 ((org-at-item-p) (org-indent-item 1))))
5901 (defun org-insert-todo-subheading (arg)
5902 "Insert a new subheading with TODO keyword or checkbox and demote it.
5903 Works for outline headings and for plain lists alike."
5904 (interactive "P")
5905 (org-insert-todo-heading arg)
5906 (cond
5907 ((org-on-heading-p) (org-do-demote))
5908 ((org-at-item-p) (org-indent-item 1))))
5910 ;;; Promotion and Demotion
5912 (defvar org-after-demote-entry-hook nil
5913 "Hook run after an entry has been demoted.
5914 The cursor will be at the beginning of the entry.
5915 When a subtree is being demoted, the hook will be called for each node.")
5917 (defvar org-after-promote-entry-hook nil
5918 "Hook run after an entry has been promoted.
5919 The cursor will be at the beginning of the entry.
5920 When a subtree is being promoted, the hook will be called for each node.")
5922 (defun org-promote-subtree ()
5923 "Promote the entire subtree.
5924 See also `org-promote'."
5925 (interactive)
5926 (save-excursion
5927 (org-map-tree 'org-promote))
5928 (org-fix-position-after-promote))
5930 (defun org-demote-subtree ()
5931 "Demote the entire subtree. See `org-demote'.
5932 See also `org-promote'."
5933 (interactive)
5934 (save-excursion
5935 (org-map-tree 'org-demote))
5936 (org-fix-position-after-promote))
5939 (defun org-do-promote ()
5940 "Promote the current heading higher up the tree.
5941 If the region is active in `transient-mark-mode', promote all headings
5942 in the region."
5943 (interactive)
5944 (save-excursion
5945 (if (org-region-active-p)
5946 (org-map-region 'org-promote (region-beginning) (region-end))
5947 (org-promote)))
5948 (org-fix-position-after-promote))
5950 (defun org-do-demote ()
5951 "Demote the current heading lower down the tree.
5952 If the region is active in `transient-mark-mode', demote all headings
5953 in the region."
5954 (interactive)
5955 (save-excursion
5956 (if (org-region-active-p)
5957 (org-map-region 'org-demote (region-beginning) (region-end))
5958 (org-demote)))
5959 (org-fix-position-after-promote))
5961 (defun org-fix-position-after-promote ()
5962 "Make sure that after pro/demotion cursor position is right."
5963 (let ((pos (point)))
5964 (when (save-excursion
5965 (beginning-of-line 1)
5966 (looking-at org-todo-line-regexp)
5967 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5968 (cond ((eobp) (insert " "))
5969 ((eolp) (insert " "))
5970 ((equal (char-after) ?\ ) (forward-char 1))))))
5972 (defun org-reduced-level (l)
5973 "Compute the effective level of a heading.
5974 This takes into account the setting of `org-odd-levels-only'."
5975 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5977 (defun org-get-valid-level (level &optional change)
5978 "Rectify a level change under the influence of `org-odd-levels-only'
5979 LEVEL is a current level, CHANGE is by how much the level should be
5980 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5981 even level numbers will become the next higher odd number."
5982 (if org-odd-levels-only
5983 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5984 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5985 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5986 (max 1 (+ level (or change 0)))))
5988 (if (boundp 'define-obsolete-function-alias)
5989 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5990 (define-obsolete-function-alias 'org-get-legal-level
5991 'org-get-valid-level)
5992 (define-obsolete-function-alias 'org-get-legal-level
5993 'org-get-valid-level "23.1")))
5995 (defun org-promote ()
5996 "Promote the current heading higher up the tree.
5997 If the region is active in `transient-mark-mode', promote all headings
5998 in the region."
5999 (org-back-to-heading t)
6000 (let* ((level (save-match-data (funcall outline-level)))
6001 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6002 (diff (abs (- level (length up-head) -1))))
6003 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6004 (replace-match up-head nil t)
6005 ;; Fixup tag positioning
6006 (and org-auto-align-tags (org-set-tags nil t))
6007 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6008 (run-hooks 'org-after-promote-entry-hook)))
6010 (defun org-demote ()
6011 "Demote the current heading lower down the tree.
6012 If the region is active in `transient-mark-mode', demote all headings
6013 in the region."
6014 (org-back-to-heading t)
6015 (let* ((level (save-match-data (funcall outline-level)))
6016 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6017 (diff (abs (- level (length down-head) -1))))
6018 (replace-match down-head nil t)
6019 ;; Fixup tag positioning
6020 (and org-auto-align-tags (org-set-tags nil t))
6021 (if org-adapt-indentation (org-fixup-indentation diff))
6022 (run-hooks 'org-after-demote-entry-hook)))
6024 (defun org-map-tree (fun)
6025 "Call FUN for every heading underneath the current one."
6026 (org-back-to-heading)
6027 (let ((level (funcall outline-level)))
6028 (save-excursion
6029 (funcall fun)
6030 (while (and (progn
6031 (outline-next-heading)
6032 (> (funcall outline-level) level))
6033 (not (eobp)))
6034 (funcall fun)))))
6036 (defun org-map-region (fun beg end)
6037 "Call FUN for every heading between BEG and END."
6038 (let ((org-ignore-region t))
6039 (save-excursion
6040 (setq end (copy-marker end))
6041 (goto-char beg)
6042 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6043 (< (point) end))
6044 (funcall fun))
6045 (while (and (progn
6046 (outline-next-heading)
6047 (< (point) end))
6048 (not (eobp)))
6049 (funcall fun)))))
6051 (defun org-fixup-indentation (diff)
6052 "Change the indentation in the current entry by DIFF
6053 However, if any line in the current entry has no indentation, or if it
6054 would end up with no indentation after the change, nothing at all is done."
6055 (save-excursion
6056 (let ((end (save-excursion (outline-next-heading)
6057 (point-marker)))
6058 (prohibit (if (> diff 0)
6059 "^\\S-"
6060 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6061 col)
6062 (unless (save-excursion (end-of-line 1)
6063 (re-search-forward prohibit end t))
6064 (while (and (< (point) end)
6065 (re-search-forward "^[ \t]+" end t))
6066 (goto-char (match-end 0))
6067 (setq col (current-column))
6068 (if (< diff 0) (replace-match ""))
6069 (org-indent-to-column (+ diff col))))
6070 (move-marker end nil))))
6072 (defun org-convert-to-odd-levels ()
6073 "Convert an org-mode file with all levels allowed to one with odd levels.
6074 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6075 level 5 etc."
6076 (interactive)
6077 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6078 (let ((outline-regexp org-outline-regexp)
6079 (outline-level 'org-outline-level)
6080 (org-odd-levels-only nil) n)
6081 (save-excursion
6082 (goto-char (point-min))
6083 (while (re-search-forward "^\\*\\*+ " nil t)
6084 (setq n (- (length (match-string 0)) 2))
6085 (while (>= (setq n (1- n)) 0)
6086 (org-demote))
6087 (end-of-line 1))))))
6089 (defun org-convert-to-oddeven-levels ()
6090 "Convert an org-mode file with only odd levels to one with odd and even levels.
6091 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6092 section with an even level, conversion would destroy the structure of the file. An error
6093 is signaled in this case."
6094 (interactive)
6095 (goto-char (point-min))
6096 ;; First check if there are no even levels
6097 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6098 (org-show-context t)
6099 (error "Not all levels are odd in this file. Conversion not possible."))
6100 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6101 (let ((outline-regexp org-outline-regexp)
6102 (outline-level 'org-outline-level)
6103 (org-odd-levels-only nil) n)
6104 (save-excursion
6105 (goto-char (point-min))
6106 (while (re-search-forward "^\\*\\*+ " nil t)
6107 (setq n (/ (1- (length (match-string 0))) 2))
6108 (while (>= (setq n (1- n)) 0)
6109 (org-promote))
6110 (end-of-line 1))))))
6112 (defun org-tr-level (n)
6113 "Make N odd if required."
6114 (if org-odd-levels-only (1+ (/ n 2)) n))
6116 ;;; Vertical tree motion, cutting and pasting of subtrees
6118 (defun org-move-subtree-up (&optional arg)
6119 "Move the current subtree up past ARG headlines of the same level."
6120 (interactive "p")
6121 (org-move-subtree-down (- (prefix-numeric-value arg))))
6123 (defun org-move-subtree-down (&optional arg)
6124 "Move the current subtree down past ARG headlines of the same level."
6125 (interactive "p")
6126 (setq arg (prefix-numeric-value arg))
6127 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6128 'org-get-last-sibling))
6129 (ins-point (make-marker))
6130 (cnt (abs arg))
6131 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6132 ;; Select the tree
6133 (org-back-to-heading)
6134 (setq beg0 (point))
6135 (save-excursion
6136 (setq ne-beg (org-back-over-empty-lines))
6137 (setq beg (point)))
6138 (save-match-data
6139 (save-excursion (outline-end-of-heading)
6140 (setq folded (org-invisible-p)))
6141 (outline-end-of-subtree))
6142 (outline-next-heading)
6143 (setq ne-end (org-back-over-empty-lines))
6144 (setq end (point))
6145 (goto-char beg0)
6146 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6147 ;; include less whitespace
6148 (save-excursion
6149 (goto-char beg)
6150 (forward-line (- ne-beg ne-end))
6151 (setq beg (point))))
6152 ;; Find insertion point, with error handling
6153 (while (> cnt 0)
6154 (or (and (funcall movfunc) (looking-at outline-regexp))
6155 (progn (goto-char beg0)
6156 (error "Cannot move past superior level or buffer limit")))
6157 (setq cnt (1- cnt)))
6158 (if (> arg 0)
6159 ;; Moving forward - still need to move over subtree
6160 (progn (org-end-of-subtree t t)
6161 (save-excursion
6162 (org-back-over-empty-lines)
6163 (or (bolp) (newline)))))
6164 (setq ne-ins (org-back-over-empty-lines))
6165 (move-marker ins-point (point))
6166 (setq txt (buffer-substring beg end))
6167 (org-save-markers-in-region beg end)
6168 (delete-region beg end)
6169 (org-remove-empty-overlays-at beg)
6170 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6171 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6172 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6173 (let ((bbb (point)))
6174 (insert-before-markers txt)
6175 (org-reinstall-markers-in-region bbb)
6176 (move-marker ins-point bbb))
6177 (or (bolp) (insert "\n"))
6178 (setq ins-end (point))
6179 (goto-char ins-point)
6180 (org-skip-whitespace)
6181 (when (and (< arg 0)
6182 (org-first-sibling-p)
6183 (> ne-ins ne-beg))
6184 ;; Move whitespace back to beginning
6185 (save-excursion
6186 (goto-char ins-end)
6187 (let ((kill-whole-line t))
6188 (kill-line (- ne-ins ne-beg)) (point)))
6189 (insert (make-string (- ne-ins ne-beg) ?\n)))
6190 (move-marker ins-point nil)
6191 (if folded
6192 (hide-subtree)
6193 (org-show-entry)
6194 (show-children)
6195 (org-cycle-hide-drawers 'children))
6196 (org-clean-visibility-after-subtree-move)))
6198 (defvar org-subtree-clip ""
6199 "Clipboard for cut and paste of subtrees.
6200 This is actually only a copy of the kill, because we use the normal kill
6201 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6203 (defvar org-subtree-clip-folded nil
6204 "Was the last copied subtree folded?
6205 This is used to fold the tree back after pasting.")
6207 (defun org-cut-subtree (&optional n)
6208 "Cut the current subtree into the clipboard.
6209 With prefix arg N, cut this many sequential subtrees.
6210 This is a short-hand for marking the subtree and then cutting it."
6211 (interactive "p")
6212 (org-copy-subtree n 'cut))
6214 (defun org-copy-subtree (&optional n cut force-store-markers)
6215 "Cut the current subtree into the clipboard.
6216 With prefix arg N, cut this many sequential subtrees.
6217 This is a short-hand for marking the subtree and then copying it.
6218 If CUT is non-nil, actually cut the subtree.
6219 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6220 of some markers in the region, even if CUT is non-nil. This is
6221 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6222 (interactive "p")
6223 (let (beg end folded (beg0 (point)))
6224 (if (interactive-p)
6225 (org-back-to-heading nil) ; take what looks like a subtree
6226 (org-back-to-heading t)) ; take what is really there
6227 (org-back-over-empty-lines)
6228 (setq beg (point))
6229 (skip-chars-forward " \t\r\n")
6230 (save-match-data
6231 (save-excursion (outline-end-of-heading)
6232 (setq folded (org-invisible-p)))
6233 (condition-case nil
6234 (org-forward-same-level (1- n) t)
6235 (error nil))
6236 (org-end-of-subtree t t))
6237 (org-back-over-empty-lines)
6238 (setq end (point))
6239 (goto-char beg0)
6240 (when (> end beg)
6241 (setq org-subtree-clip-folded folded)
6242 (when (or cut force-store-markers)
6243 (org-save-markers-in-region beg end))
6244 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6245 (setq org-subtree-clip (current-kill 0))
6246 (message "%s: Subtree(s) with %d characters"
6247 (if cut "Cut" "Copied")
6248 (length org-subtree-clip)))))
6250 (defun org-paste-subtree (&optional level tree for-yank)
6251 "Paste the clipboard as a subtree, with modification of headline level.
6252 The entire subtree is promoted or demoted in order to match a new headline
6253 level.
6255 If the cursor is at the beginning of a headline, the same level as
6256 that headline is used to paste the tree
6258 If not, the new level is derived from the *visible* headings
6259 before and after the insertion point, and taken to be the inferior headline
6260 level of the two. So if the previous visible heading is level 3 and the
6261 next is level 4 (or vice versa), level 4 will be used for insertion.
6262 This makes sure that the subtree remains an independent subtree and does
6263 not swallow low level entries.
6265 You can also force a different level, either by using a numeric prefix
6266 argument, or by inserting the heading marker by hand. For example, if the
6267 cursor is after \"*****\", then the tree will be shifted to level 5.
6269 If optional TREE is given, use this text instead of the kill ring.
6271 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6272 move back over whitespace before inserting, and move point to the end of
6273 the inserted text when done."
6274 (interactive "P")
6275 (setq tree (or tree (and kill-ring (current-kill 0))))
6276 (unless (org-kill-is-subtree-p tree)
6277 (error "%s"
6278 (substitute-command-keys
6279 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6280 (let* ((visp (not (org-invisible-p)))
6281 (txt tree)
6282 (^re (concat "^\\(" outline-regexp "\\)"))
6283 (re (concat "\\(" outline-regexp "\\)"))
6284 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6286 (old-level (if (string-match ^re txt)
6287 (- (match-end 0) (match-beginning 0) 1)
6288 -1))
6289 (force-level (cond (level (prefix-numeric-value level))
6290 ((and (looking-at "[ \t]*$")
6291 (string-match
6292 ^re_ (buffer-substring
6293 (point-at-bol) (point))))
6294 (- (match-end 1) (match-beginning 1)))
6295 ((and (bolp)
6296 (looking-at org-outline-regexp))
6297 (- (match-end 0) (point) 1))
6298 (t nil)))
6299 (previous-level (save-excursion
6300 (condition-case nil
6301 (progn
6302 (outline-previous-visible-heading 1)
6303 (if (looking-at re)
6304 (- (match-end 0) (match-beginning 0) 1)
6306 (error 1))))
6307 (next-level (save-excursion
6308 (condition-case nil
6309 (progn
6310 (or (looking-at outline-regexp)
6311 (outline-next-visible-heading 1))
6312 (if (looking-at re)
6313 (- (match-end 0) (match-beginning 0) 1)
6315 (error 1))))
6316 (new-level (or force-level (max previous-level next-level)))
6317 (shift (if (or (= old-level -1)
6318 (= new-level -1)
6319 (= old-level new-level))
6321 (- new-level old-level)))
6322 (delta (if (> shift 0) -1 1))
6323 (func (if (> shift 0) 'org-demote 'org-promote))
6324 (org-odd-levels-only nil)
6325 beg end newend)
6326 ;; Remove the forced level indicator
6327 (if force-level
6328 (delete-region (point-at-bol) (point)))
6329 ;; Paste
6330 (beginning-of-line 1)
6331 (unless for-yank (org-back-over-empty-lines))
6332 (setq beg (point))
6333 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6334 (insert-before-markers txt)
6335 (unless (string-match "\n\\'" txt) (insert "\n"))
6336 (setq newend (point))
6337 (org-reinstall-markers-in-region beg)
6338 (setq end (point))
6339 (goto-char beg)
6340 (skip-chars-forward " \t\n\r")
6341 (setq beg (point))
6342 (if (and (org-invisible-p) visp)
6343 (save-excursion (outline-show-heading)))
6344 ;; Shift if necessary
6345 (unless (= shift 0)
6346 (save-restriction
6347 (narrow-to-region beg end)
6348 (while (not (= shift 0))
6349 (org-map-region func (point-min) (point-max))
6350 (setq shift (+ delta shift)))
6351 (goto-char (point-min))
6352 (setq newend (point-max))))
6353 (when (or (interactive-p) for-yank)
6354 (message "Clipboard pasted as level %d subtree" new-level))
6355 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6356 kill-ring
6357 (eq org-subtree-clip (current-kill 0))
6358 org-subtree-clip-folded)
6359 ;; The tree was folded before it was killed/copied
6360 (hide-subtree))
6361 (and for-yank (goto-char newend))))
6363 (defun org-kill-is-subtree-p (&optional txt)
6364 "Check if the current kill is an outline subtree, or a set of trees.
6365 Returns nil if kill does not start with a headline, or if the first
6366 headline level is not the largest headline level in the tree.
6367 So this will actually accept several entries of equal levels as well,
6368 which is OK for `org-paste-subtree'.
6369 If optional TXT is given, check this string instead of the current kill."
6370 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6371 (start-level (and kill
6372 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6373 org-outline-regexp "\\)")
6374 kill)
6375 (- (match-end 2) (match-beginning 2) 1)))
6376 (re (concat "^" org-outline-regexp))
6377 (start (1+ (or (match-beginning 2) -1))))
6378 (if (not start-level)
6379 (progn
6380 nil) ;; does not even start with a heading
6381 (catch 'exit
6382 (while (setq start (string-match re kill (1+ start)))
6383 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6384 (throw 'exit nil)))
6385 t))))
6387 (defvar org-markers-to-move nil
6388 "Markers that should be moved with a cut-and-paste operation.
6389 Those markers are stored together with their positions relative to
6390 the start of the region.")
6392 (defun org-save-markers-in-region (beg end)
6393 "Check markers in region.
6394 If these markers are between BEG and END, record their position relative
6395 to BEG, so that after moving the block of text, we can put the markers back
6396 into place.
6397 This function gets called just before an entry or tree gets cut from the
6398 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6399 called immediately, to move the markers with the entries."
6400 (setq org-markers-to-move nil)
6401 (when (featurep 'org-clock)
6402 (org-clock-save-markers-for-cut-and-paste beg end))
6403 (when (featurep 'org-agenda)
6404 (org-agenda-save-markers-for-cut-and-paste beg end)))
6406 (defun org-check-and-save-marker (marker beg end)
6407 "Check if MARKER is between BEG and END.
6408 If yes, remember the marker and the distance to BEG."
6409 (when (and (marker-buffer marker)
6410 (equal (marker-buffer marker) (current-buffer)))
6411 (if (and (>= marker beg) (< marker end))
6412 (push (cons marker (- marker beg)) org-markers-to-move))))
6414 (defun org-reinstall-markers-in-region (beg)
6415 "Move all remembered markers to their position relative to BEG."
6416 (mapc (lambda (x)
6417 (move-marker (car x) (+ beg (cdr x))))
6418 org-markers-to-move)
6419 (setq org-markers-to-move nil))
6421 (defun org-narrow-to-subtree ()
6422 "Narrow buffer to the current subtree."
6423 (interactive)
6424 (save-excursion
6425 (save-match-data
6426 (narrow-to-region
6427 (progn (org-back-to-heading t) (point))
6428 (progn (org-end-of-subtree t t) (point))))))
6430 (defun org-clone-subtree-with-time-shift (n &optional shift)
6431 "Clone the task (subtree) at point N times.
6432 The clones will be inserted as siblings.
6434 In interactive use, the user will be prompted for the number of clones
6435 to be produced, and for a time SHIFT, which may be a repeater as used
6436 in time stamps, for example `+3d'.
6438 When a valid repeater is given and the entry contains any time stamps,
6439 the clones will become a sequence in time, with time stamps in the
6440 subtree shifted for each clone produced. If SHIFT is nil or the
6441 empty string, time stamps will be left alone.
6443 If the original subtree did contain time stamps with a repeater,
6444 the following will happen:
6445 - the repeater will be removed in each clone
6446 - an additional clone will be produced, with the current, unshifted
6447 date(s) in the entry.
6448 - the original entry will be placed *after* all the clones, with
6449 repeater intact.
6450 - the start days in the repeater in the original entry will be shifted
6451 to past the last clone.
6452 I this way you can spell out a number of instances of a repeating task,
6453 and still retain the repeater to cover future instances of the task."
6454 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6455 (let (beg end template task
6456 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6457 (if (not (and (integerp n) (> n 0)))
6458 (error "Invalid number of replications %s" n))
6459 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6460 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6461 shift)))
6462 (error "Invalid shift specification %s" shift))
6463 (when doshift
6464 (setq shift-n (string-to-number (match-string 1 shift))
6465 shift-what (cdr (assoc (match-string 2 shift)
6466 '(("d" . day) ("w" . week)
6467 ("m" . month) ("y" . year))))))
6468 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6469 (setq nmin 1 nmax n)
6470 (org-back-to-heading t)
6471 (setq beg (point))
6472 (org-end-of-subtree t t)
6473 (setq end (point))
6474 (setq template (buffer-substring beg end))
6475 (when (and doshift
6476 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6477 (delete-region beg end)
6478 (setq end beg)
6479 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6480 (goto-char end)
6481 (loop for n from nmin to nmax do
6482 (if (not doshift)
6483 (setq task template)
6484 (with-temp-buffer
6485 (insert template)
6486 (org-mode)
6487 (goto-char (point-min))
6488 (while (re-search-forward org-ts-regexp-both nil t)
6489 (org-timestamp-change (* n shift-n) shift-what))
6490 (unless (= n n-no-remove)
6491 (goto-char (point-min))
6492 (while (re-search-forward org-ts-regexp nil t)
6493 (save-excursion
6494 (goto-char (match-beginning 0))
6495 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6496 (delete-region (match-beginning 1) (match-end 1))))))
6497 (setq task (buffer-string))))
6498 (insert task))
6499 (goto-char beg)))
6501 ;;; Outline Sorting
6503 (defun org-sort (with-case)
6504 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6505 Optional argument WITH-CASE means sort case-sensitively.
6506 With a double prefix argument, also remove duplicate entries."
6507 (interactive "P")
6508 (if (org-at-table-p)
6509 (org-call-with-arg 'org-table-sort-lines with-case)
6510 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6512 (defun org-sort-remove-invisible (s)
6513 (remove-text-properties 0 (length s) org-rm-props s)
6514 (while (string-match org-bracket-link-regexp s)
6515 (setq s (replace-match (if (match-end 2)
6516 (match-string 3 s)
6517 (match-string 1 s)) t t s)))
6520 (defvar org-priority-regexp) ; defined later in the file
6522 (defvar org-after-sorting-entries-or-items-hook nil
6523 "Hook that is run after a bunch of entries or items have been sorted.
6524 When children are sorted, the cursor is in the parent line when this
6525 hook gets called. When a region or a plain list is sorted, the cursor
6526 will be in the first entry of the sorted region/list.")
6528 (defun org-sort-entries-or-items
6529 (&optional with-case sorting-type getkey-func compare-func property)
6530 "Sort entries on a certain level of an outline tree, or plain list items.
6531 If there is an active region, the entries in the region are sorted.
6532 Else, if the cursor is before the first entry, sort the top-level items.
6533 Else, the children of the entry at point are sorted.
6534 If the cursor is at the first item in a plain list, the list items will be
6535 sorted.
6537 Sorting can be alphabetically, numerically, by date/time as given by
6538 a time stamp, by a property or by priority.
6540 The command prompts for the sorting type unless it has been given to the
6541 function through the SORTING-TYPE argument, which needs to a character,
6542 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6543 precise meaning of each character:
6545 n Numerically, by converting the beginning of the entry/item to a number.
6546 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6547 t By date/time, either the first active time stamp in the entry, or, if
6548 none exist, by the first inactive one.
6549 In items, only the first line will be chekced.
6550 s By the scheduled date/time.
6551 d By deadline date/time.
6552 c By creation time, which is assumed to be the first inactive time stamp
6553 at the beginning of a line.
6554 p By priority according to the cookie.
6555 r By the value of a property.
6557 Capital letters will reverse the sort order.
6559 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6560 called with point at the beginning of the record. It must return either
6561 a string or a number that should serve as the sorting key for that record.
6563 Comparing entries ignores case by default. However, with an optional argument
6564 WITH-CASE, the sorting considers case as well."
6565 (interactive "P")
6566 (let ((case-func (if with-case 'identity 'downcase))
6567 start beg end stars re re2
6568 txt what tmp plain-list-p)
6569 ;; Find beginning and end of region to sort
6570 (cond
6571 ((org-region-active-p)
6572 ;; we will sort the region
6573 (setq end (region-end)
6574 what "region")
6575 (goto-char (region-beginning))
6576 (if (not (org-on-heading-p)) (outline-next-heading))
6577 (setq start (point)))
6578 ((org-at-item-p)
6579 ;; we will sort this plain list
6580 (org-beginning-of-item-list) (setq start (point))
6581 (org-end-of-item-list) (setq end (point))
6582 (goto-char start)
6583 (setq plain-list-p t
6584 what "plain list"))
6585 ((or (org-on-heading-p)
6586 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6587 ;; we will sort the children of the current headline
6588 (org-back-to-heading)
6589 (setq start (point)
6590 end (progn (org-end-of-subtree t t)
6591 (org-back-over-empty-lines)
6592 (point))
6593 what "children")
6594 (goto-char start)
6595 (show-subtree)
6596 (outline-next-heading))
6598 ;; we will sort the top-level entries in this file
6599 (goto-char (point-min))
6600 (or (org-on-heading-p) (outline-next-heading))
6601 (setq start (point) end (point-max) what "top-level")
6602 (goto-char start)
6603 (show-all)))
6605 (setq beg (point))
6606 (if (>= beg end) (error "Nothing to sort"))
6608 (unless plain-list-p
6609 (looking-at "\\(\\*+\\)")
6610 (setq stars (match-string 1)
6611 re (concat "^" (regexp-quote stars) " +")
6612 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6613 txt (buffer-substring beg end))
6614 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6615 (if (and (not (equal stars "*")) (string-match re2 txt))
6616 (error "Region to sort contains a level above the first entry")))
6618 (unless sorting-type
6619 (message
6620 (if plain-list-p
6621 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6622 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6623 [t]ime [s]cheduled [d]eadline [c]reated
6624 A/N/T/S/D/C/P/O/F means reversed:")
6625 what)
6626 (setq sorting-type (read-char-exclusive))
6628 (and (= (downcase sorting-type) ?f)
6629 (setq getkey-func
6630 (org-icompleting-read "Sort using function: "
6631 obarray 'fboundp t nil nil))
6632 (setq getkey-func (intern getkey-func)))
6634 (and (= (downcase sorting-type) ?r)
6635 (setq property
6636 (org-icompleting-read "Property: "
6637 (mapcar 'list (org-buffer-property-keys t))
6638 nil t))))
6640 (message "Sorting entries...")
6642 (save-restriction
6643 (narrow-to-region start end)
6645 (let ((dcst (downcase sorting-type))
6646 (case-fold-search nil)
6647 (now (current-time)))
6648 (sort-subr
6649 (/= dcst sorting-type)
6650 ;; This function moves to the beginning character of the "record" to
6651 ;; be sorted.
6652 (if plain-list-p
6653 (lambda nil
6654 (if (org-at-item-p) t (goto-char (point-max))))
6655 (lambda nil
6656 (if (re-search-forward re nil t)
6657 (goto-char (match-beginning 0))
6658 (goto-char (point-max)))))
6659 ;; This function moves to the last character of the "record" being
6660 ;; sorted.
6661 (if plain-list-p
6662 'org-end-of-item
6663 (lambda nil
6664 (save-match-data
6665 (condition-case nil
6666 (outline-forward-same-level 1)
6667 (error
6668 (goto-char (point-max)))))))
6670 ;; This function returns the value that gets sorted against.
6671 (if plain-list-p
6672 (lambda nil
6673 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6674 (cond
6675 ((= dcst ?n)
6676 (string-to-number (buffer-substring (match-end 0)
6677 (point-at-eol))))
6678 ((= dcst ?a)
6679 (buffer-substring (match-end 0) (point-at-eol)))
6680 ((= dcst ?t)
6681 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6682 (re-search-forward org-ts-regexp-both
6683 (point-at-eol) t))
6684 (org-time-string-to-seconds (match-string 0))
6685 (org-float-time now)))
6686 ((= dcst ?f)
6687 (if getkey-func
6688 (progn
6689 (setq tmp (funcall getkey-func))
6690 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6691 tmp)
6692 (error "Invalid key function `%s'" getkey-func)))
6693 (t (error "Invalid sorting type `%c'" sorting-type)))))
6694 (lambda nil
6695 (cond
6696 ((= dcst ?n)
6697 (if (looking-at org-complex-heading-regexp)
6698 (string-to-number (match-string 4))
6699 nil))
6700 ((= dcst ?a)
6701 (if (looking-at org-complex-heading-regexp)
6702 (funcall case-func (match-string 4))
6703 nil))
6704 ((= dcst ?t)
6705 (let ((end (save-excursion (outline-next-heading) (point))))
6706 (if (or (re-search-forward org-ts-regexp end t)
6707 (re-search-forward org-ts-regexp-both end t))
6708 (org-time-string-to-seconds (match-string 0))
6709 (org-float-time now))))
6710 ((= dcst ?c)
6711 (let ((end (save-excursion (outline-next-heading) (point))))
6712 (if (re-search-forward
6713 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6714 end t)
6715 (org-time-string-to-seconds (match-string 0))
6716 (org-float-time now))))
6717 ((= dcst ?s)
6718 (let ((end (save-excursion (outline-next-heading) (point))))
6719 (if (re-search-forward org-scheduled-time-regexp end t)
6720 (org-time-string-to-seconds (match-string 1))
6721 (org-float-time now))))
6722 ((= dcst ?d)
6723 (let ((end (save-excursion (outline-next-heading) (point))))
6724 (if (re-search-forward org-deadline-time-regexp end t)
6725 (org-time-string-to-seconds (match-string 1))
6726 (org-float-time now))))
6727 ((= dcst ?p)
6728 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6729 (string-to-char (match-string 2))
6730 org-default-priority))
6731 ((= dcst ?r)
6732 (or (org-entry-get nil property) ""))
6733 ((= dcst ?o)
6734 (if (looking-at org-complex-heading-regexp)
6735 (- 9999 (length (member (match-string 2)
6736 org-todo-keywords-1)))))
6737 ((= dcst ?f)
6738 (if getkey-func
6739 (progn
6740 (setq tmp (funcall getkey-func))
6741 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6742 tmp)
6743 (error "Invalid key function `%s'" getkey-func)))
6744 (t (error "Invalid sorting type `%c'" sorting-type)))))
6746 (cond
6747 ((= dcst ?a) 'string<)
6748 ((= dcst ?f) compare-func)
6749 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6750 (t nil)))))
6751 (run-hooks 'org-after-sorting-entries-or-items-hook)
6752 (message "Sorting entries...done")))
6754 (defun org-do-sort (table what &optional with-case sorting-type)
6755 "Sort TABLE of WHAT according to SORTING-TYPE.
6756 The user will be prompted for the SORTING-TYPE if the call to this
6757 function does not specify it. WHAT is only for the prompt, to indicate
6758 what is being sorted. The sorting key will be extracted from
6759 the car of the elements of the table.
6760 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6761 (unless sorting-type
6762 (message
6763 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6764 what)
6765 (setq sorting-type (read-char-exclusive)))
6766 (let ((dcst (downcase sorting-type))
6767 extractfun comparefun)
6768 ;; Define the appropriate functions
6769 (cond
6770 ((= dcst ?n)
6771 (setq extractfun 'string-to-number
6772 comparefun (if (= dcst sorting-type) '< '>)))
6773 ((= dcst ?a)
6774 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6775 (lambda(x) (downcase (org-sort-remove-invisible x))))
6776 comparefun (if (= dcst sorting-type)
6777 'string<
6778 (lambda (a b) (and (not (string< a b))
6779 (not (string= a b)))))))
6780 ((= dcst ?t)
6781 (setq extractfun
6782 (lambda (x)
6783 (if (or (string-match org-ts-regexp x)
6784 (string-match org-ts-regexp-both x))
6785 (org-float-time
6786 (org-time-string-to-time (match-string 0 x)))
6788 comparefun (if (= dcst sorting-type) '< '>)))
6789 (t (error "Invalid sorting type `%c'" sorting-type)))
6791 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6792 table)
6793 (lambda (a b) (funcall comparefun (car a) (car b))))))
6796 ;;; The orgstruct minor mode
6798 ;; Define a minor mode which can be used in other modes in order to
6799 ;; integrate the org-mode structure editing commands.
6801 ;; This is really a hack, because the org-mode structure commands use
6802 ;; keys which normally belong to the major mode. Here is how it
6803 ;; works: The minor mode defines all the keys necessary to operate the
6804 ;; structure commands, but wraps the commands into a function which
6805 ;; tests if the cursor is currently at a headline or a plain list
6806 ;; item. If that is the case, the structure command is used,
6807 ;; temporarily setting many Org-mode variables like regular
6808 ;; expressions for filling etc. However, when any of those keys is
6809 ;; used at a different location, function uses `key-binding' to look
6810 ;; up if the key has an associated command in another currently active
6811 ;; keymap (minor modes, major mode, global), and executes that
6812 ;; command. There might be problems if any of the keys is otherwise
6813 ;; used as a prefix key.
6815 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6816 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6817 ;; addresses this by checking explicitly for both bindings.
6819 (defvar orgstruct-mode-map (make-sparse-keymap)
6820 "Keymap for the minor `orgstruct-mode'.")
6822 (defvar org-local-vars nil
6823 "List of local variables, for use by `orgstruct-mode'")
6825 ;;;###autoload
6826 (define-minor-mode orgstruct-mode
6827 "Toggle the minor more `orgstruct-mode'.
6828 This mode is for using Org-mode structure commands in other modes.
6829 The following key behave as if Org-mode was active, if the cursor
6830 is on a headline, or on a plain list item (both in the definition
6831 of Org-mode).
6833 M-up Move entry/item up
6834 M-down Move entry/item down
6835 M-left Promote
6836 M-right Demote
6837 M-S-up Move entry/item up
6838 M-S-down Move entry/item down
6839 M-S-left Promote subtree
6840 M-S-right Demote subtree
6841 M-q Fill paragraph and items like in Org-mode
6842 C-c ^ Sort entries
6843 C-c - Cycle list bullet
6844 TAB Cycle item visibility
6845 M-RET Insert new heading/item
6846 S-M-RET Insert new TODO heading / Checkbox item
6847 C-c C-c Set tags / toggle checkbox"
6848 nil " OrgStruct" nil
6849 (org-load-modules-maybe)
6850 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6852 ;;;###autoload
6853 (defun turn-on-orgstruct ()
6854 "Unconditionally turn on `orgstruct-mode'."
6855 (orgstruct-mode 1))
6857 (defun orgstruct++-mode (&optional arg)
6858 "Toggle `orgstruct-mode', the enhanced version of it.
6859 In addition to setting orgstruct-mode, this also exports all indentation
6860 and autofilling variables from org-mode into the buffer. It will also
6861 recognize item context in multiline items.
6862 Note that turning off orgstruct-mode will *not* remove the
6863 indentation/paragraph settings. This can only be done by refreshing the
6864 major mode, for example with \\[normal-mode]."
6865 (interactive "P")
6866 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6867 (if (< arg 1)
6868 (orgstruct-mode -1)
6869 (orgstruct-mode 1)
6870 (let (var val)
6871 (mapc
6872 (lambda (x)
6873 (when (string-match
6874 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6875 (symbol-name (car x)))
6876 (setq var (car x) val (nth 1 x))
6877 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6878 org-local-vars)
6879 (org-set-local 'orgstruct-is-++ t))))
6881 (defvar orgstruct-is-++ nil
6882 "Is orgstruct-mode in ++ version in the current-buffer?")
6883 (make-variable-buffer-local 'orgstruct-is-++)
6885 ;;;###autoload
6886 (defun turn-on-orgstruct++ ()
6887 "Unconditionally turn on `orgstruct++-mode'."
6888 (orgstruct++-mode 1))
6890 (defun orgstruct-error ()
6891 "Error when there is no default binding for a structure key."
6892 (interactive)
6893 (error "This key has no function outside structure elements"))
6895 (defun orgstruct-setup ()
6896 "Setup orgstruct keymaps."
6897 (let ((nfunc 0)
6898 (bindings
6899 (list
6900 '([(meta up)] org-metaup)
6901 '([(meta down)] org-metadown)
6902 '([(meta left)] org-metaleft)
6903 '([(meta right)] org-metaright)
6904 '([(meta shift up)] org-shiftmetaup)
6905 '([(meta shift down)] org-shiftmetadown)
6906 '([(meta shift left)] org-shiftmetaleft)
6907 '([(meta shift right)] org-shiftmetaright)
6908 '([?\e (up)] org-metaup)
6909 '([?\e (down)] org-metadown)
6910 '([?\e (left)] org-metaleft)
6911 '([?\e (right)] org-metaright)
6912 '([?\e (shift up)] org-shiftmetaup)
6913 '([?\e (shift down)] org-shiftmetadown)
6914 '([?\e (shift left)] org-shiftmetaleft)
6915 '([?\e (shift right)] org-shiftmetaright)
6916 '([(shift up)] org-shiftup)
6917 '([(shift down)] org-shiftdown)
6918 '([(shift left)] org-shiftleft)
6919 '([(shift right)] org-shiftright)
6920 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6921 '("\M-q" fill-paragraph)
6922 '("\C-c^" org-sort)
6923 '("\C-c-" org-cycle-list-bullet)))
6924 elt key fun cmd)
6925 (while (setq elt (pop bindings))
6926 (setq nfunc (1+ nfunc))
6927 (setq key (org-key (car elt))
6928 fun (nth 1 elt)
6929 cmd (orgstruct-make-binding fun nfunc key))
6930 (org-defkey orgstruct-mode-map key cmd))
6932 ;; Special treatment needed for TAB and RET
6933 (org-defkey orgstruct-mode-map [(tab)]
6934 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6935 (org-defkey orgstruct-mode-map "\C-i"
6936 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6938 (org-defkey orgstruct-mode-map "\M-\C-m"
6939 (orgstruct-make-binding 'org-insert-heading 105
6940 "\M-\C-m" [(meta return)]))
6941 (org-defkey orgstruct-mode-map [(meta return)]
6942 (orgstruct-make-binding 'org-insert-heading 106
6943 [(meta return)] "\M-\C-m"))
6945 (org-defkey orgstruct-mode-map [(shift meta return)]
6946 (orgstruct-make-binding 'org-insert-todo-heading 107
6947 [(meta return)] "\M-\C-m"))
6949 (org-defkey orgstruct-mode-map "\e\C-m"
6950 (orgstruct-make-binding 'org-insert-heading 108
6951 "\e\C-m" [?\e (return)]))
6952 (org-defkey orgstruct-mode-map [?\e (return)]
6953 (orgstruct-make-binding 'org-insert-heading 109
6954 [?\e (return)] "\e\C-m"))
6955 (org-defkey orgstruct-mode-map [?\e (shift return)]
6956 (orgstruct-make-binding 'org-insert-todo-heading 110
6957 [?\e (return)] "\e\C-m"))
6959 (unless org-local-vars
6960 (setq org-local-vars (org-get-local-variables)))
6964 (defun orgstruct-make-binding (fun n &rest keys)
6965 "Create a function for binding in the structure minor mode.
6966 FUN is the command to call inside a table. N is used to create a unique
6967 command name. KEYS are keys that should be checked in for a command
6968 to execute outside of tables."
6969 (eval
6970 (list 'defun
6971 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6972 '(arg)
6973 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6974 "Outside of structure, run the binding of `"
6975 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6976 "'.")
6977 '(interactive "p")
6978 (list 'if
6979 `(org-context-p 'headline 'item
6980 (and orgstruct-is-++
6981 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6982 'item-body))
6983 (list 'org-run-like-in-org-mode (list 'quote fun))
6984 (list 'let '(orgstruct-mode)
6985 (list 'call-interactively
6986 (append '(or)
6987 (mapcar (lambda (k)
6988 (list 'key-binding k))
6989 keys)
6990 '('orgstruct-error))))))))
6992 (defun org-context-p (&rest contexts)
6993 "Check if local context is any of CONTEXTS.
6994 Possible values in the list of contexts are `table', `headline', and `item'."
6995 (let ((pos (point)))
6996 (goto-char (point-at-bol))
6997 (prog1 (or (and (memq 'table contexts)
6998 (looking-at "[ \t]*|"))
6999 (and (memq 'headline contexts)
7000 ;;????????? (looking-at "\\*+"))
7001 (looking-at outline-regexp))
7002 (and (memq 'item contexts)
7003 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7004 (and (memq 'item-body contexts)
7005 (org-in-item-p)))
7006 (goto-char pos))))
7008 (defun org-get-local-variables ()
7009 "Return a list of all local variables in an org-mode buffer."
7010 (let (varlist)
7011 (with-current-buffer (get-buffer-create "*Org tmp*")
7012 (erase-buffer)
7013 (org-mode)
7014 (setq varlist (buffer-local-variables)))
7015 (kill-buffer "*Org tmp*")
7016 (delq nil
7017 (mapcar
7018 (lambda (x)
7019 (setq x
7020 (if (symbolp x)
7021 (list x)
7022 (list (car x) (list 'quote (cdr x)))))
7023 (if (string-match
7024 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7025 (symbol-name (car x)))
7026 x nil))
7027 varlist))))
7029 ;;;###autoload
7030 (defun org-run-like-in-org-mode (cmd)
7031 "Run a command, pretending that the current buffer is in Org-mode.
7032 This will temporarily bind local variables that are typically bound in
7033 Org-mode to the values they have in Org-mode, and then interactively
7034 call CMD."
7035 (org-load-modules-maybe)
7036 (unless org-local-vars
7037 (setq org-local-vars (org-get-local-variables)))
7038 (eval (list 'let org-local-vars
7039 (list 'call-interactively (list 'quote cmd)))))
7041 ;;;; Archiving
7043 (defun org-get-category (&optional pos)
7044 "Get the category applying to position POS."
7045 (get-text-property (or pos (point)) 'org-category))
7047 (defun org-refresh-category-properties ()
7048 "Refresh category text properties in the buffer."
7049 (let ((def-cat (cond
7050 ((null org-category)
7051 (if buffer-file-name
7052 (file-name-sans-extension
7053 (file-name-nondirectory buffer-file-name))
7054 "???"))
7055 ((symbolp org-category) (symbol-name org-category))
7056 (t org-category)))
7057 beg end cat pos optionp)
7058 (org-unmodified
7059 (save-excursion
7060 (save-restriction
7061 (widen)
7062 (goto-char (point-min))
7063 (put-text-property (point) (point-max) 'org-category def-cat)
7064 (while (re-search-forward
7065 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7066 (setq pos (match-end 0)
7067 optionp (equal (char-after (match-beginning 0)) ?#)
7068 cat (org-trim (match-string 2)))
7069 (if optionp
7070 (setq beg (point-at-bol) end (point-max))
7071 (org-back-to-heading t)
7072 (setq beg (point) end (org-end-of-subtree t t)))
7073 (put-text-property beg end 'org-category cat)
7074 (goto-char pos)))))))
7077 ;;;; Link Stuff
7079 ;;; Link abbreviations
7081 (defun org-link-expand-abbrev (link)
7082 "Apply replacements as defined in `org-link-abbrev-alist."
7083 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7084 (let* ((key (match-string 1 link))
7085 (as (or (assoc key org-link-abbrev-alist-local)
7086 (assoc key org-link-abbrev-alist)))
7087 (tag (and (match-end 2) (match-string 3 link)))
7088 rpl)
7089 (if (not as)
7090 link
7091 (setq rpl (cdr as))
7092 (cond
7093 ((symbolp rpl) (funcall rpl tag))
7094 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7095 ((string-match "%h" rpl)
7096 (replace-match (url-hexify-string (or tag "")) t t rpl))
7097 (t (concat rpl tag)))))
7098 link))
7100 ;;; Storing and inserting links
7102 (defvar org-insert-link-history nil
7103 "Minibuffer history for links inserted with `org-insert-link'.")
7105 (defvar org-stored-links nil
7106 "Contains the links stored with `org-store-link'.")
7108 (defvar org-store-link-plist nil
7109 "Plist with info about the most recently link created with `org-store-link'.")
7111 (defvar org-link-protocols nil
7112 "Link protocols added to Org-mode using `org-add-link-type'.")
7114 (defvar org-store-link-functions nil
7115 "List of functions that are called to create and store a link.
7116 Each function will be called in turn until one returns a non-nil
7117 value. Each function should check if it is responsible for creating
7118 this link (for example by looking at the major mode).
7119 If not, it must exit and return nil.
7120 If yes, it should return a non-nil value after a calling
7121 `org-store-link-props' with a list of properties and values.
7122 Special properties are:
7124 :type The link prefix. like \"http\". This must be given.
7125 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7126 This is obligatory as well.
7127 :description Optional default description for the second pair
7128 of brackets in an Org-mode link. The user can still change
7129 this when inserting this link into an Org-mode buffer.
7131 In addition to these, any additional properties can be specified
7132 and then used in remember templates.")
7134 (defun org-add-link-type (type &optional follow export)
7135 "Add TYPE to the list of `org-link-types'.
7136 Re-compute all regular expressions depending on `org-link-types'
7138 FOLLOW and EXPORT are two functions.
7140 FOLLOW should take the link path as the single argument and do whatever
7141 is necessary to follow the link, for example find a file or display
7142 a mail message.
7144 EXPORT should format the link path for export to one of the export formats.
7145 It should be a function accepting three arguments:
7147 path the path of the link, the text after the prefix (like \"http:\")
7148 desc the description of the link, if any, nil if there was no description
7149 format the export format, a symbol like `html' or `latex'.
7151 The function may use the FORMAT information to return different values
7152 depending on the format. The return value will be put literally into
7153 the exported file.
7154 Org-mode has a built-in default for exporting links. If you are happy with
7155 this default, there is no need to define an export function for the link
7156 type. For a simple example of an export function, see `org-bbdb.el'."
7157 (add-to-list 'org-link-types type t)
7158 (org-make-link-regexps)
7159 (if (assoc type org-link-protocols)
7160 (setcdr (assoc type org-link-protocols) (list follow export))
7161 (push (list type follow export) org-link-protocols)))
7163 (defvar org-agenda-buffer-name)
7165 ;;;###autoload
7166 (defun org-store-link (arg)
7167 "\\<org-mode-map>Store an org-link to the current location.
7168 This link is added to `org-stored-links' and can later be inserted
7169 into an org-buffer with \\[org-insert-link].
7171 For some link types, a prefix arg is interpreted:
7172 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7173 For file links, arg negates `org-context-in-file-links'."
7174 (interactive "P")
7175 (org-load-modules-maybe)
7176 (setq org-store-link-plist nil) ; reset
7177 (let ((outline-regexp (org-get-limited-outline-regexp))
7178 link cpltxt desc description search txt custom-id)
7179 (cond
7181 ((run-hook-with-args-until-success 'org-store-link-functions)
7182 (setq link (plist-get org-store-link-plist :link)
7183 desc (or (plist-get org-store-link-plist :description) link)))
7185 ((equal (buffer-name) "*Org Edit Src Example*")
7186 (let (label gc)
7187 (while (or (not label)
7188 (save-excursion
7189 (save-restriction
7190 (widen)
7191 (goto-char (point-min))
7192 (re-search-forward
7193 (regexp-quote (format org-coderef-label-format label))
7194 nil t))))
7195 (when label (message "Label exists already") (sit-for 2))
7196 (setq label (read-string "Code line label: " label)))
7197 (end-of-line 1)
7198 (setq link (format org-coderef-label-format label))
7199 (setq gc (- 79 (length link)))
7200 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7201 (insert link)
7202 (setq link (concat "(" label ")") desc nil)))
7204 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7205 ;; We are in the agenda, link to referenced location
7206 (let ((m (or (get-text-property (point) 'org-hd-marker)
7207 (get-text-property (point) 'org-marker))))
7208 (unless m (error "Don't know what location to link to"))
7209 (org-with-point-at m
7210 (call-interactively 'org-store-link))))
7212 ((eq major-mode 'calendar-mode)
7213 (let ((cd (calendar-cursor-to-date)))
7214 (setq link
7215 (format-time-string
7216 (car org-time-stamp-formats)
7217 (apply 'encode-time
7218 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7219 nil nil nil))))
7220 (org-store-link-props :type "calendar" :date cd)))
7222 ((eq major-mode 'w3-mode)
7223 (setq cpltxt (if (and (buffer-name)
7224 (not (string-match "Untitled" (buffer-name))))
7225 (buffer-name)
7226 (url-view-url t))
7227 link (org-make-link (url-view-url t)))
7228 (org-store-link-props :type "w3" :url (url-view-url t)))
7230 ((eq major-mode 'w3m-mode)
7231 (setq cpltxt (or w3m-current-title w3m-current-url)
7232 link (org-make-link w3m-current-url))
7233 (org-store-link-props :type "w3m" :url (url-view-url t)))
7235 ((setq search (run-hook-with-args-until-success
7236 'org-create-file-search-functions))
7237 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7238 "::" search))
7239 (setq cpltxt (or description link)))
7241 ((eq major-mode 'image-mode)
7242 (setq cpltxt (concat "file:"
7243 (abbreviate-file-name buffer-file-name))
7244 link (org-make-link cpltxt))
7245 (org-store-link-props :type "image" :file buffer-file-name))
7247 ((eq major-mode 'dired-mode)
7248 ;; link to the file in the current line
7249 (setq cpltxt (concat "file:"
7250 (abbreviate-file-name
7251 (expand-file-name
7252 (dired-get-filename nil t))))
7253 link (org-make-link cpltxt)))
7255 ((and buffer-file-name (org-mode-p))
7256 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7257 (cond
7258 ((org-in-regexp "<<\\(.*?\\)>>")
7259 (setq cpltxt
7260 (concat "file:"
7261 (abbreviate-file-name buffer-file-name)
7262 "::" (match-string 1))
7263 link (org-make-link cpltxt)))
7264 ((and (featurep 'org-id)
7265 (or (eq org-link-to-org-use-id t)
7266 (and (eq org-link-to-org-use-id 'create-if-interactive)
7267 (interactive-p))
7268 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7269 (interactive-p)
7270 (not custom-id))
7271 (and org-link-to-org-use-id
7272 (condition-case nil
7273 (org-entry-get nil "ID")
7274 (error nil)))))
7275 ;; We can make a link using the ID.
7276 (setq link (condition-case nil
7277 (prog1 (org-id-store-link)
7278 (setq desc (plist-get org-store-link-plist
7279 :description)))
7280 (error
7281 ;; probably before first headline, link to file only
7282 (concat "file:"
7283 (abbreviate-file-name buffer-file-name))))))
7285 ;; Just link to current headline
7286 (setq cpltxt (concat "file:"
7287 (abbreviate-file-name buffer-file-name)))
7288 ;; Add a context search string
7289 (when (org-xor org-context-in-file-links arg)
7290 (setq txt (cond
7291 ((org-on-heading-p) nil)
7292 ((org-region-active-p)
7293 (buffer-substring (region-beginning) (region-end)))
7294 (t nil)))
7295 (when (or (null txt) (string-match "\\S-" txt))
7296 (setq cpltxt
7297 (concat cpltxt "::"
7298 (condition-case nil
7299 (org-make-org-heading-search-string txt)
7300 (error "")))
7301 desc (or (nth 4 (ignore-errors
7302 (org-heading-components))) "NONE"))))
7303 (if (string-match "::\\'" cpltxt)
7304 (setq cpltxt (substring cpltxt 0 -2)))
7305 (setq link (org-make-link cpltxt)))))
7307 ((buffer-file-name (buffer-base-buffer))
7308 ;; Just link to this file here.
7309 (setq cpltxt (concat "file:"
7310 (abbreviate-file-name
7311 (buffer-file-name (buffer-base-buffer)))))
7312 ;; Add a context string
7313 (when (org-xor org-context-in-file-links arg)
7314 (setq txt (if (org-region-active-p)
7315 (buffer-substring (region-beginning) (region-end))
7316 (buffer-substring (point-at-bol) (point-at-eol))))
7317 ;; Only use search option if there is some text.
7318 (when (string-match "\\S-" txt)
7319 (setq cpltxt
7320 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7321 desc "NONE")))
7322 (setq link (org-make-link cpltxt)))
7324 ((interactive-p)
7325 (error "Cannot link to a buffer which is not visiting a file"))
7327 (t (setq link nil)))
7329 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7330 (setq link (or link cpltxt)
7331 desc (or desc cpltxt))
7332 (if (equal desc "NONE") (setq desc nil))
7334 (if (and (or (interactive-p) executing-kbd-macro) link)
7335 (progn
7336 (setq org-stored-links
7337 (cons (list link desc) org-stored-links))
7338 (message "Stored: %s" (or desc link))
7339 (when custom-id
7340 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7341 "::#" custom-id))
7342 (setq org-stored-links
7343 (cons (list link desc) org-stored-links))))
7344 (and link (org-make-link-string link desc)))))
7346 (defun org-store-link-props (&rest plist)
7347 "Store link properties, extract names and addresses."
7348 (let (x adr)
7349 (when (setq x (plist-get plist :from))
7350 (setq adr (mail-extract-address-components x))
7351 (setq plist (plist-put plist :fromname (car adr)))
7352 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7353 (when (setq x (plist-get plist :to))
7354 (setq adr (mail-extract-address-components x))
7355 (setq plist (plist-put plist :toname (car adr)))
7356 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7357 (let ((from (plist-get plist :from))
7358 (to (plist-get plist :to)))
7359 (when (and from to org-from-is-user-regexp)
7360 (setq plist
7361 (plist-put plist :fromto
7362 (if (string-match org-from-is-user-regexp from)
7363 (concat "to %t")
7364 (concat "from %f"))))))
7365 (setq org-store-link-plist plist))
7367 (defun org-add-link-props (&rest plist)
7368 "Add these properties to the link property list."
7369 (let (key value)
7370 (while plist
7371 (setq key (pop plist) value (pop plist))
7372 (setq org-store-link-plist
7373 (plist-put org-store-link-plist key value)))))
7375 (defun org-email-link-description (&optional fmt)
7376 "Return the description part of an email link.
7377 This takes information from `org-store-link-plist' and formats it
7378 according to FMT (default from `org-email-link-description-format')."
7379 (setq fmt (or fmt org-email-link-description-format))
7380 (let* ((p org-store-link-plist)
7381 (to (plist-get p :toaddress))
7382 (from (plist-get p :fromaddress))
7383 (table
7384 (list
7385 (cons "%c" (plist-get p :fromto))
7386 (cons "%F" (plist-get p :from))
7387 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7388 (cons "%T" (plist-get p :to))
7389 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7390 (cons "%s" (plist-get p :subject))
7391 (cons "%m" (plist-get p :message-id)))))
7392 (when (string-match "%c" fmt)
7393 ;; Check if the user wrote this message
7394 (if (and org-from-is-user-regexp from to
7395 (save-match-data (string-match org-from-is-user-regexp from)))
7396 (setq fmt (replace-match "to %t" t t fmt))
7397 (setq fmt (replace-match "from %f" t t fmt))))
7398 (org-replace-escapes fmt table)))
7400 (defun org-make-org-heading-search-string (&optional string heading)
7401 "Make search string for STRING or current headline."
7402 (interactive)
7403 (let ((s (or string (org-get-heading))))
7404 (unless (and string (not heading))
7405 ;; We are using a headline, clean up garbage in there.
7406 (if (string-match org-todo-regexp s)
7407 (setq s (replace-match "" t t s)))
7408 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7409 (setq s (replace-match "" t t s)))
7410 (setq s (org-trim s))
7411 (if (string-match (concat "^\\(" org-quote-string "\\|"
7412 org-comment-string "\\)") s)
7413 (setq s (replace-match "" t t s)))
7414 (while (string-match org-ts-regexp s)
7415 (setq s (replace-match "" t t s))))
7416 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7417 (setq s (replace-match " " t t s)))
7418 (or string (setq s (concat "*" s))) ; Add * for headlines
7419 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7421 (defun org-make-link (&rest strings)
7422 "Concatenate STRINGS."
7423 (apply 'concat strings))
7425 (defun org-make-link-string (link &optional description)
7426 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7427 (unless (string-match "\\S-" link)
7428 (error "Empty link"))
7429 (when (stringp description)
7430 ;; Remove brackets from the description, they are fatal.
7431 (while (string-match "\\[" description)
7432 (setq description (replace-match "{" t t description)))
7433 (while (string-match "\\]" description)
7434 (setq description (replace-match "}" t t description))))
7435 (when (equal (org-link-escape link) description)
7436 ;; No description needed, it is identical
7437 (setq description nil))
7438 (when (and (not description)
7439 (not (equal link (org-link-escape link))))
7440 (setq description (org-extract-attributes link)))
7441 (concat "[[" (org-link-escape link) "]"
7442 (if description (concat "[" description "]") "")
7443 "]"))
7445 (defconst org-link-escape-chars
7446 '((?\ . "%20")
7447 (?\[ . "%5B")
7448 (?\] . "%5D")
7449 (?\340 . "%E0") ; `a
7450 (?\342 . "%E2") ; ^a
7451 (?\347 . "%E7") ; ,c
7452 (?\350 . "%E8") ; `e
7453 (?\351 . "%E9") ; 'e
7454 (?\352 . "%EA") ; ^e
7455 (?\356 . "%EE") ; ^i
7456 (?\364 . "%F4") ; ^o
7457 (?\371 . "%F9") ; `u
7458 (?\373 . "%FB") ; ^u
7459 (?\; . "%3B")
7460 (?? . "%3F")
7461 (?= . "%3D")
7462 (?+ . "%2B")
7464 "Association list of escapes for some characters problematic in links.
7465 This is the list that is used for internal purposes.")
7467 (defvar org-url-encoding-use-url-hexify nil)
7469 (defconst org-link-escape-chars-browser
7470 '((?\ . "%20")) ; 32 for the SPC char
7471 "Association list of escapes for some characters problematic in links.
7472 This is the list that is used before handing over to the browser.")
7474 (defun org-link-escape (text &optional table)
7475 "Escape characters in TEXT that are problematic for links."
7476 (if org-url-encoding-use-url-hexify
7477 (url-hexify-string text)
7478 (setq table (or table org-link-escape-chars))
7479 (when text
7480 (let ((re (mapconcat (lambda (x) (regexp-quote
7481 (char-to-string (car x))))
7482 table "\\|")))
7483 (while (string-match re text)
7484 (setq text
7485 (replace-match
7486 (cdr (assoc (string-to-char (match-string 0 text))
7487 table))
7488 t t text)))
7489 text))))
7491 (defun org-link-unescape (text &optional table)
7492 "Reverse the action of `org-link-escape'."
7493 (if org-url-encoding-use-url-hexify
7494 (url-unhex-string text)
7495 (setq table (or table org-link-escape-chars))
7496 (when text
7497 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7498 table "\\|")))
7499 (while (string-match re text)
7500 (setq text
7501 (replace-match
7502 (char-to-string (car (rassoc (match-string 0 text) table)))
7503 t t text)))
7504 text))))
7506 (defun org-xor (a b)
7507 "Exclusive or."
7508 (if a (not b) b))
7510 (defun org-fixup-message-id-for-http (s)
7511 "Replace special characters in a message id, so it can be used in an http query."
7512 (while (string-match "<" s)
7513 (setq s (replace-match "%3C" t t s)))
7514 (while (string-match ">" s)
7515 (setq s (replace-match "%3E" t t s)))
7516 (while (string-match "@" s)
7517 (setq s (replace-match "%40" t t s)))
7520 ;;;###autoload
7521 (defun org-insert-link-global ()
7522 "Insert a link like Org-mode does.
7523 This command can be called in any mode to insert a link in Org-mode syntax."
7524 (interactive)
7525 (org-load-modules-maybe)
7526 (org-run-like-in-org-mode 'org-insert-link))
7528 (defun org-insert-link (&optional complete-file link-location)
7529 "Insert a link. At the prompt, enter the link.
7531 Completion can be used to insert any of the link protocol prefixes like
7532 http or ftp in use.
7534 The history can be used to select a link previously stored with
7535 `org-store-link'. When the empty string is entered (i.e. if you just
7536 press RET at the prompt), the link defaults to the most recently
7537 stored link. As SPC triggers completion in the minibuffer, you need to
7538 use M-SPC or C-q SPC to force the insertion of a space character.
7540 You will also be prompted for a description, and if one is given, it will
7541 be displayed in the buffer instead of the link.
7543 If there is already a link at point, this command will allow you to edit link
7544 and description parts.
7546 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7547 be selected using completion. The path to the file will be relative to the
7548 current directory if the file is in the current directory or a subdirectory.
7549 Otherwise, the link will be the absolute path as completed in the minibuffer
7550 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7551 option `org-link-file-path-type'.
7553 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7554 the current directory or below.
7556 With three \\[universal-argument] prefixes, negate the meaning of
7557 `org-keep-stored-link-after-insertion'.
7559 If `org-make-link-description-function' is non-nil, this function will be
7560 called with the link target, and the result will be the default
7561 link description.
7563 If the LINK-LOCATION parameter is non-nil, this value will be
7564 used as the link location instead of reading one interactively."
7565 (interactive "P")
7566 (let* ((wcf (current-window-configuration))
7567 (region (if (org-region-active-p)
7568 (buffer-substring (region-beginning) (region-end))))
7569 (remove (and region (list (region-beginning) (region-end))))
7570 (desc region)
7571 tmphist ; byte-compile incorrectly complains about this
7572 (link link-location)
7573 entry file all-prefixes)
7574 (cond
7575 (link-location) ; specified by arg, just use it.
7576 ((org-in-regexp org-bracket-link-regexp 1)
7577 ;; We do have a link at point, and we are going to edit it.
7578 (setq remove (list (match-beginning 0) (match-end 0)))
7579 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7580 (setq link (read-string "Link: "
7581 (org-link-unescape
7582 (org-match-string-no-properties 1)))))
7583 ((or (org-in-regexp org-angle-link-re)
7584 (org-in-regexp org-plain-link-re))
7585 ;; Convert to bracket link
7586 (setq remove (list (match-beginning 0) (match-end 0))
7587 link (read-string "Link: "
7588 (org-remove-angle-brackets (match-string 0)))))
7589 ((member complete-file '((4) (16)))
7590 ;; Completing read for file names.
7591 (setq link (org-file-complete-link complete-file)))
7593 ;; Read link, with completion for stored links.
7594 (with-output-to-temp-buffer "*Org Links*"
7595 (princ "Insert a link.
7596 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7597 (when org-stored-links
7598 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7599 (princ (mapconcat
7600 (lambda (x)
7601 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7602 (reverse org-stored-links) "\n"))))
7603 (let ((cw (selected-window)))
7604 (select-window (get-buffer-window "*Org Links*"))
7605 (setq truncate-lines t)
7606 (unless (pos-visible-in-window-p (point-max))
7607 (org-fit-window-to-buffer))
7608 (and (window-live-p cw) (select-window cw)))
7609 ;; Fake a link history, containing the stored links.
7610 (setq tmphist (append (mapcar 'car org-stored-links)
7611 org-insert-link-history))
7612 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7613 (mapcar 'car org-link-abbrev-alist)
7614 org-link-types))
7615 (unwind-protect
7616 (progn
7617 (setq link
7618 (let ((org-completion-use-ido nil)
7619 (org-completion-use-iswitchb nil))
7620 (org-completing-read
7621 "Link: "
7622 (append
7623 (mapcar (lambda (x) (list (concat x ":")))
7624 all-prefixes)
7625 (mapcar 'car org-stored-links))
7626 nil nil nil
7627 'tmphist
7628 (car (car org-stored-links)))))
7629 (if (or (member link all-prefixes)
7630 (and (equal ":" (substring link -1))
7631 (member (substring link 0 -1) all-prefixes)
7632 (setq link (substring link 0 -1))))
7633 (setq link (org-link-try-special-completion link))))
7634 (set-window-configuration wcf)
7635 (kill-buffer "*Org Links*"))
7636 (setq entry (assoc link org-stored-links))
7637 (or entry (push link org-insert-link-history))
7638 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7639 (not org-keep-stored-link-after-insertion))
7640 (setq org-stored-links (delq (assoc link org-stored-links)
7641 org-stored-links)))
7642 (setq desc (or desc (nth 1 entry)))))
7644 (if (string-match org-plain-link-re link)
7645 ;; URL-like link, normalize the use of angular brackets.
7646 (setq link (org-make-link (org-remove-angle-brackets link))))
7648 ;; Check if we are linking to the current file with a search option
7649 ;; If yes, simplify the link by using only the search option.
7650 (when (and buffer-file-name
7651 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7652 (let* ((path (match-string 1 link))
7653 (case-fold-search nil)
7654 (search (match-string 2 link)))
7655 (save-match-data
7656 (if (equal (file-truename buffer-file-name) (file-truename path))
7657 ;; We are linking to this same file, with a search option
7658 (setq link search)))))
7660 ;; Check if we can/should use a relative path. If yes, simplify the link
7661 (when (string-match "^file:\\(.*\\)" link)
7662 (let* ((path (match-string 1 link))
7663 (origpath path)
7664 (case-fold-search nil))
7665 (cond
7666 ((or (eq org-link-file-path-type 'absolute)
7667 (equal complete-file '(16)))
7668 (setq path (abbreviate-file-name (expand-file-name path))))
7669 ((eq org-link-file-path-type 'noabbrev)
7670 (setq path (expand-file-name path)))
7671 ((eq org-link-file-path-type 'relative)
7672 (setq path (file-relative-name path)))
7674 (save-match-data
7675 (if (string-match (concat "^" (regexp-quote
7676 (file-name-as-directory
7677 (expand-file-name "."))))
7678 (expand-file-name path))
7679 ;; We are linking a file with relative path name.
7680 (setq path (substring (expand-file-name path)
7681 (match-end 0)))
7682 (setq path (abbreviate-file-name (expand-file-name path)))))))
7683 (setq link (concat "file:" path))
7684 (if (equal desc origpath)
7685 (setq desc path))))
7687 (if org-make-link-description-function
7688 (setq desc (funcall org-make-link-description-function link desc)))
7690 (setq desc (read-string "Description: " desc))
7691 (unless (string-match "\\S-" desc) (setq desc nil))
7692 (if remove (apply 'delete-region remove))
7693 (insert (org-make-link-string link desc))))
7695 (defun org-link-try-special-completion (type)
7696 "If there is completion support for link type TYPE, offer it."
7697 (let ((fun (intern (concat "org-" type "-complete-link"))))
7698 (if (functionp fun)
7699 (funcall fun)
7700 (read-string "Link (no completion support): " (concat type ":")))))
7702 (defun org-file-complete-link (&optional arg)
7703 "Create a file link using completion."
7704 (let (file link)
7705 (setq file (read-file-name "File: "))
7706 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7707 (pwd1 (file-name-as-directory (abbreviate-file-name
7708 (expand-file-name ".")))))
7709 (cond
7710 ((equal arg '(16))
7711 (setq link (org-make-link
7712 "file:"
7713 (abbreviate-file-name (expand-file-name file)))))
7714 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7715 (setq link (org-make-link "file:" (match-string 1 file))))
7716 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7717 (expand-file-name file))
7718 (setq link (org-make-link
7719 "file:" (match-string 1 (expand-file-name file)))))
7720 (t (setq link (org-make-link "file:" file)))))
7721 link))
7723 (defun org-completing-read (&rest args)
7724 "Completing-read with SPACE being a normal character."
7725 (let ((minibuffer-local-completion-map
7726 (copy-keymap minibuffer-local-completion-map)))
7727 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7728 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7729 (apply 'org-icompleting-read args)))
7731 (defun org-completing-read-no-i (&rest args)
7732 (let (org-completion-use-ido org-completion-use-iswitchb)
7733 (apply 'org-completing-read args)))
7735 (defun org-iswitchb-completing-read (prompt choices &rest args)
7736 "Use iswitch as a completing-read replacement to choose from choices.
7737 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7738 from."
7739 (let* ((iswitchb-use-virtual-buffers nil)
7740 (iswitchb-make-buflist-hook
7741 (lambda ()
7742 (setq iswitchb-temp-buflist choices))))
7743 (iswitchb-read-buffer prompt)))
7745 (defun org-icompleting-read (&rest args)
7746 "Completing-read using `ido-mode' or `iswitchb' speedups if available"
7747 (if (and org-completion-use-ido
7748 (fboundp 'ido-completing-read)
7749 (boundp 'ido-mode) ido-mode
7750 (listp (second args)))
7751 (let ((ido-enter-matching-directory nil))
7752 (apply 'ido-completing-read (concat (car args))
7753 (if (consp (car (nth 1 args)))
7754 (mapcar (lambda (x) (car x)) (nth 1 args))
7755 (nth 1 args))
7756 (cddr args)))
7757 (if (and org-completion-use-iswitchb
7758 (boundp 'iswitchb-mode) iswitchb-mode
7759 (listp (second args)))
7760 (apply 'org-iswitchb-completing-read (concat (car args))
7761 (mapcar (lambda (x) (car x)) (nth 1 args))
7762 (cddr args))
7763 (apply 'completing-read args))))
7765 (defun org-extract-attributes (s)
7766 "Extract the attributes cookie from a string and set as text property."
7767 (let (a attr (start 0) key value)
7768 (save-match-data
7769 (when (string-match "{{\\([^}]+\\)}}$" s)
7770 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7771 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7772 (setq key (match-string 1 a) value (match-string 2 a)
7773 start (match-end 0)
7774 attr (plist-put attr (intern key) value))))
7775 (org-add-props s nil 'org-attr attr))
7778 (defun org-extract-attributes-from-string (tag)
7779 (let (key value attr)
7780 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7781 (setq key (match-string 1 tag) value (match-string 2 tag)
7782 tag (replace-match "" t t tag)
7783 attr (plist-put attr (intern key) value)))
7784 (cons tag attr)))
7786 (defun org-attributes-to-string (plist)
7787 "Format a property list into an HTML attribute list."
7788 (let ((s "") key value)
7789 (while plist
7790 (setq key (pop plist) value (pop plist))
7791 (and value
7792 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7795 ;;; Opening/following a link
7797 (defvar org-link-search-failed nil)
7799 (defun org-next-link ()
7800 "Move forward to the next link.
7801 If the link is in hidden text, expose it."
7802 (interactive)
7803 (when (and org-link-search-failed (eq this-command last-command))
7804 (goto-char (point-min))
7805 (message "Link search wrapped back to beginning of buffer"))
7806 (setq org-link-search-failed nil)
7807 (let* ((pos (point))
7808 (ct (org-context))
7809 (a (assoc :link ct)))
7810 (if a (goto-char (nth 2 a)))
7811 (if (re-search-forward org-any-link-re nil t)
7812 (progn
7813 (goto-char (match-beginning 0))
7814 (if (org-invisible-p) (org-show-context)))
7815 (goto-char pos)
7816 (setq org-link-search-failed t)
7817 (error "No further link found"))))
7819 (defun org-previous-link ()
7820 "Move backward to the previous link.
7821 If the link is in hidden text, expose it."
7822 (interactive)
7823 (when (and org-link-search-failed (eq this-command last-command))
7824 (goto-char (point-max))
7825 (message "Link search wrapped back to end of buffer"))
7826 (setq org-link-search-failed nil)
7827 (let* ((pos (point))
7828 (ct (org-context))
7829 (a (assoc :link ct)))
7830 (if a (goto-char (nth 1 a)))
7831 (if (re-search-backward org-any-link-re nil t)
7832 (progn
7833 (goto-char (match-beginning 0))
7834 (if (org-invisible-p) (org-show-context)))
7835 (goto-char pos)
7836 (setq org-link-search-failed t)
7837 (error "No further link found"))))
7839 (defun org-translate-link (s)
7840 "Translate a link string if a translation function has been defined."
7841 (if (and org-link-translation-function
7842 (fboundp org-link-translation-function)
7843 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7844 (progn
7845 (setq s (funcall org-link-translation-function
7846 (match-string 1) (match-string 2)))
7847 (concat (car s) ":" (cdr s)))
7850 (defun org-translate-link-from-planner (type path)
7851 "Translate a link from Emacs Planner syntax so that Org can follow it.
7852 This is still an experimental function, your mileage may vary."
7853 (cond
7854 ((member type '("http" "https" "news" "ftp"))
7855 ;; standard Internet links are the same.
7856 nil)
7857 ((and (equal type "irc") (string-match "^//" path))
7858 ;; Planner has two / at the beginning of an irc link, we have 1.
7859 ;; We should have zero, actually....
7860 (setq path (substring path 1)))
7861 ((and (equal type "lisp") (string-match "^/" path))
7862 ;; Planner has a slash, we do not.
7863 (setq type "elisp" path (substring path 1)))
7864 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7865 ;; A typical message link. Planner has the id after the fina slash,
7866 ;; we separate it with a hash mark
7867 (setq path (concat (match-string 1 path) "#"
7868 (org-remove-angle-brackets (match-string 2 path)))))
7870 (cons type path))
7872 (defun org-find-file-at-mouse (ev)
7873 "Open file link or URL at mouse."
7874 (interactive "e")
7875 (mouse-set-point ev)
7876 (org-open-at-point 'in-emacs))
7878 (defun org-open-at-mouse (ev)
7879 "Open file link or URL at mouse."
7880 (interactive "e")
7881 (mouse-set-point ev)
7882 (if (eq major-mode 'org-agenda-mode)
7883 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7884 (org-open-at-point))
7886 (defvar org-window-config-before-follow-link nil
7887 "The window configuration before following a link.
7888 This is saved in case the need arises to restore it.")
7890 (defvar org-open-link-marker (make-marker)
7891 "Marker pointing to the location where `org-open-at-point; was called.")
7893 ;;;###autoload
7894 (defun org-open-at-point-global ()
7895 "Follow a link like Org-mode does.
7896 This command can be called in any mode to follow a link that has
7897 Org-mode syntax."
7898 (interactive)
7899 (org-run-like-in-org-mode 'org-open-at-point))
7901 ;;;###autoload
7902 (defun org-open-link-from-string (s &optional arg reference-buffer)
7903 "Open a link in the string S, as if it was in Org-mode."
7904 (interactive "sLink: \nP")
7905 (let ((reference-buffer (or reference-buffer (current-buffer))))
7906 (with-temp-buffer
7907 (let ((org-inhibit-startup t))
7908 (org-mode)
7909 (insert s)
7910 (goto-char (point-min))
7911 (org-open-at-point arg reference-buffer)))))
7913 (defun org-open-at-point (&optional in-emacs reference-buffer)
7914 "Open link at or after point.
7915 If there is no link at point, this function will search forward up to
7916 the end of the current line.
7917 Normally, files will be opened by an appropriate application. If the
7918 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7919 With a double prefix argument, try to open outside of Emacs, in the
7920 application the system uses for this file type."
7921 (interactive "P")
7922 (org-load-modules-maybe)
7923 (move-marker org-open-link-marker (point))
7924 (setq org-window-config-before-follow-link (current-window-configuration))
7925 (org-remove-occur-highlights nil nil t)
7926 (cond
7927 ((and (org-on-heading-p)
7928 (not (org-in-regexp
7929 (concat org-plain-link-re "\\|"
7930 org-bracket-link-regexp "\\|"
7931 org-angle-link-re "\\|"
7932 "[ \t]:[^ \t\n]+:[ \t]*$"))))
7933 (org-offer-links-in-entry in-emacs))
7934 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7935 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7936 (org-footnote-action))
7938 (let (type path link line search (pos (point)))
7939 (catch 'match
7940 (save-excursion
7941 (skip-chars-forward "^]\n\r")
7942 (when (org-in-regexp org-bracket-link-regexp)
7943 (setq link (org-extract-attributes
7944 (org-link-unescape (org-match-string-no-properties 1))))
7945 (while (string-match " *\n *" link)
7946 (setq link (replace-match " " t t link)))
7947 (setq link (org-link-expand-abbrev link))
7948 (cond
7949 ((or (file-name-absolute-p link)
7950 (string-match "^\\.\\.?/" link))
7951 (setq type "file" path link))
7952 ((string-match org-link-re-with-space3 link)
7953 (setq type (match-string 1 link) path (match-string 2 link)))
7954 (t (setq type "thisfile" path link)))
7955 (throw 'match t)))
7957 (when (get-text-property (point) 'org-linked-text)
7958 (setq type "thisfile"
7959 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7960 (1+ (point)) (point))
7961 path (buffer-substring
7962 (previous-single-property-change pos 'org-linked-text)
7963 (next-single-property-change pos 'org-linked-text)))
7964 (throw 'match t))
7966 (save-excursion
7967 (when (or (org-in-regexp org-angle-link-re)
7968 (org-in-regexp org-plain-link-re))
7969 (setq type (match-string 1) path (match-string 2))
7970 (throw 'match t)))
7971 (save-excursion
7972 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7973 (setq type "tags"
7974 path (match-string 1))
7975 (while (string-match ":" path)
7976 (setq path (replace-match "+" t t path)))
7977 (throw 'match t)))
7978 (when (org-in-regexp "<\\([^><\n]+\\)>")
7979 (setq type "tree-match"
7980 path (match-string 1))
7981 (throw 'match t)))
7982 (unless path
7983 (error "No link found"))
7985 ;; switch back to reference buffer
7986 ;; needed when if called in a temporary buffer through
7987 ;; org-open-link-from-string
7988 (with-current-buffer (or reference-buffer (current-buffer))
7990 ;; Remove any trailing spaces in path
7991 (if (string-match " +\\'" path)
7992 (setq path (replace-match "" t t path)))
7993 (if (and org-link-translation-function
7994 (fboundp org-link-translation-function))
7995 ;; Check if we need to translate the link
7996 (let ((tmp (funcall org-link-translation-function type path)))
7997 (setq type (car tmp) path (cdr tmp))))
7999 (cond
8001 ((assoc type org-link-protocols)
8002 (funcall (nth 1 (assoc type org-link-protocols)) path))
8004 ((equal type "mailto")
8005 (let ((cmd (car org-link-mailto-program))
8006 (args (cdr org-link-mailto-program)) args1
8007 (address path) (subject "") a)
8008 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8009 (setq address (match-string 1 path)
8010 subject (org-link-escape (match-string 2 path))))
8011 (while args
8012 (cond
8013 ((not (stringp (car args))) (push (pop args) args1))
8014 (t (setq a (pop args))
8015 (if (string-match "%a" a)
8016 (setq a (replace-match address t t a)))
8017 (if (string-match "%s" a)
8018 (setq a (replace-match subject t t a)))
8019 (push a args1))))
8020 (apply cmd (nreverse args1))))
8022 ((member type '("http" "https" "ftp" "news"))
8023 (browse-url (concat type ":" (org-link-escape
8024 path org-link-escape-chars-browser))))
8026 ((member type '("message"))
8027 (browse-url (concat type ":" path)))
8029 ((string= type "tags")
8030 (org-tags-view in-emacs path))
8031 ((string= type "thisfile")
8032 (if in-emacs
8033 (switch-to-buffer-other-window
8034 (org-get-buffer-for-internal-link (current-buffer)))
8035 (org-mark-ring-push))
8036 (let ((cmd `(org-link-search
8037 ,path
8038 ,(cond ((equal in-emacs '(4)) 'occur)
8039 ((equal in-emacs '(16)) 'org-occur)
8040 (t nil))
8041 ,pos)))
8042 (condition-case nil (eval cmd)
8043 (error (progn (widen) (eval cmd))))))
8045 ((string= type "tree-match")
8046 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8048 ((string= type "file")
8049 (if (string-match "::\\([0-9]+\\)\\'" path)
8050 (setq line (string-to-number (match-string 1 path))
8051 path (substring path 0 (match-beginning 0)))
8052 (if (string-match "::\\(.+\\)\\'" path)
8053 (setq search (match-string 1 path)
8054 path (substring path 0 (match-beginning 0)))))
8055 (if (string-match "[*?{]" (file-name-nondirectory path))
8056 (dired path)
8057 (org-open-file path in-emacs line search)))
8059 ((string= type "news")
8060 (require 'org-gnus)
8061 (org-gnus-follow-link path))
8063 ((string= type "shell")
8064 (let ((cmd path))
8065 (if (or (not org-confirm-shell-link-function)
8066 (funcall org-confirm-shell-link-function
8067 (format "Execute \"%s\" in shell? "
8068 (org-add-props cmd nil
8069 'face 'org-warning))))
8070 (progn
8071 (message "Executing %s" cmd)
8072 (shell-command cmd))
8073 (error "Abort"))))
8075 ((string= type "elisp")
8076 (let ((cmd path))
8077 (if (or (not org-confirm-elisp-link-function)
8078 (funcall org-confirm-elisp-link-function
8079 (format "Execute \"%s\" as elisp? "
8080 (org-add-props cmd nil
8081 'face 'org-warning))))
8082 (message "%s => %s" cmd
8083 (if (equal (string-to-char cmd) ?\()
8084 (eval (read cmd))
8085 (call-interactively (read cmd))))
8086 (error "Abort"))))
8089 (browse-url-at-point))))))
8090 (move-marker org-open-link-marker nil)
8091 (run-hook-with-args 'org-follow-link-hook)))
8093 (defun org-offer-links-in-entry (&optional nth zero)
8094 "Offer links in the curren entry and follow the selected link.
8095 If there is only one link, follow it immediately as well.
8096 If NTH is an integer, immediately pick the NTH link found.
8097 If ZERO is a string, check also this string for a link, and if
8098 there is one, offer it as link number zero."
8099 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8100 "\\(" org-angle-link-re "\\)\\|"
8101 "\\(" org-plain-link-re "\\)"))
8102 (cnt ?0)
8103 (in-emacs (if (integerp nth) nil nth))
8104 have-zero end links link c)
8105 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8106 (push (match-string 0 zero) links)
8107 (setq cnt (1- cnt) have-zero t))
8108 (save-excursion
8109 (org-back-to-heading t)
8110 (setq end (save-excursion (outline-next-heading) (point)))
8111 (while (re-search-forward re end t)
8112 (push (match-string 0) links))
8113 (setq links (org-uniquify (reverse links))))
8115 (cond
8116 ((null links) (error "No links"))
8117 ((equal (length links) 1)
8118 (setq link (car links)))
8119 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8120 (setq link (nth (if have-zero nth (1- nth)) links)))
8121 (t ; we have to select a link
8122 (save-excursion
8123 (save-window-excursion
8124 (delete-other-windows)
8125 (with-output-to-temp-buffer "*Select Link*"
8126 (mapc (lambda (l)
8127 (if (not (string-match org-bracket-link-regexp l))
8128 (princ (format "[%c] %s\n" (incf cnt)
8129 (org-remove-angle-brackets l)))
8130 (if (match-end 3)
8131 (princ (format "[%c] %s (%s)\n" (incf cnt)
8132 (match-string 3 l) (match-string 1 l)))
8133 (princ (format "[%c] %s\n" (incf cnt)
8134 (match-string 1 l))))))
8135 links))
8136 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8137 (message "Select link to open:")
8138 (setq c (read-char-exclusive))
8139 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8140 (when (equal c ?q) (error "Abort"))
8141 (setq nth (- c ?0))
8142 (if have-zero (setq nth (1+ nth)))
8143 (unless (and (integerp nth) (>= (length links) nth))
8144 (error "Invalid link selection"))
8145 (setq link (nth (1- nth) links))))
8146 (org-open-link-from-string link in-emacs (current-buffer))))
8148 ;;;; Time estimates
8150 (defun org-get-effort (&optional pom)
8151 "Get the effort estimate for the current entry."
8152 (org-entry-get pom org-effort-property))
8154 ;;; File search
8156 (defvar org-create-file-search-functions nil
8157 "List of functions to construct the right search string for a file link.
8158 These functions are called in turn with point at the location to
8159 which the link should point.
8161 A function in the hook should first test if it would like to
8162 handle this file type, for example by checking the major-mode or
8163 the file extension. If it decides not to handle this file, it
8164 should just return nil to give other functions a chance. If it
8165 does handle the file, it must return the search string to be used
8166 when following the link. The search string will be part of the
8167 file link, given after a double colon, and `org-open-at-point'
8168 will automatically search for it. If special measures must be
8169 taken to make the search successful, another function should be
8170 added to the companion hook `org-execute-file-search-functions',
8171 which see.
8173 A function in this hook may also use `setq' to set the variable
8174 `description' to provide a suggestion for the descriptive text to
8175 be used for this link when it gets inserted into an Org-mode
8176 buffer with \\[org-insert-link].")
8178 (defvar org-execute-file-search-functions nil
8179 "List of functions to execute a file search triggered by a link.
8181 Functions added to this hook must accept a single argument, the
8182 search string that was part of the file link, the part after the
8183 double colon. The function must first check if it would like to
8184 handle this search, for example by checking the major-mode or the
8185 file extension. If it decides not to handle this search, it
8186 should just return nil to give other functions a chance. If it
8187 does handle the search, it must return a non-nil value to keep
8188 other functions from trying.
8190 Each function can access the current prefix argument through the
8191 variable `current-prefix-argument'. Note that a single prefix is
8192 used to force opening a link in Emacs, so it may be good to only
8193 use a numeric or double prefix to guide the search function.
8195 In case this is needed, a function in this hook can also restore
8196 the window configuration before `org-open-at-point' was called using:
8198 (set-window-configuration org-window-config-before-follow-link)")
8200 (defun org-link-search (s &optional type avoid-pos)
8201 "Search for a link search option.
8202 If S is surrounded by forward slashes, it is interpreted as a
8203 regular expression. In org-mode files, this will create an `org-occur'
8204 sparse tree. In ordinary files, `occur' will be used to list matches.
8205 If the current buffer is in `dired-mode', grep will be used to search
8206 in all files. If AVOID-POS is given, ignore matches near that position."
8207 (let ((case-fold-search t)
8208 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8209 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8210 (append '(("") (" ") ("\t") ("\n"))
8211 org-emphasis-alist)
8212 "\\|") "\\)"))
8213 (pos (point))
8214 (pre nil) (post nil)
8215 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8216 (cond
8217 ;; First check if there are any special
8218 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8219 ;; Now try the builtin stuff
8220 ((and (equal (string-to-char s0) ?#)
8221 (> (length s0) 1)
8222 (save-excursion
8223 (goto-char (point-min))
8224 (and
8225 (re-search-forward
8226 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8227 (setq type 'dedicated
8228 pos (match-beginning 0))))
8229 ;; There is an exact target for this
8230 (goto-char pos)
8231 (org-back-to-heading t)))
8232 ((save-excursion
8233 (goto-char (point-min))
8234 (and
8235 (re-search-forward
8236 (concat "<<" (regexp-quote s0) ">>") nil t)
8237 (setq type 'dedicated
8238 pos (match-beginning 0))))
8239 ;; There is an exact target for this
8240 (goto-char pos))
8241 ((and (string-match "^(\\(.*\\))$" s0)
8242 (save-excursion
8243 (goto-char (point-min))
8244 (and
8245 (re-search-forward
8246 (concat "[^[]" (regexp-quote
8247 (format org-coderef-label-format
8248 (match-string 1 s0))))
8249 nil t)
8250 (setq type 'dedicated
8251 pos (1+ (match-beginning 0))))))
8252 ;; There is a coderef target for this
8253 (goto-char pos))
8254 ((string-match "^/\\(.*\\)/$" s)
8255 ;; A regular expression
8256 (cond
8257 ((org-mode-p)
8258 (org-occur (match-string 1 s)))
8259 ;;((eq major-mode 'dired-mode)
8260 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8261 (t (org-do-occur (match-string 1 s)))))
8263 ;; A normal search strings
8264 (when (equal (string-to-char s) ?*)
8265 ;; Anchor on headlines, post may include tags.
8266 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8267 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8268 s (substring s 1)))
8269 (remove-text-properties
8270 0 (length s)
8271 '(face nil mouse-face nil keymap nil fontified nil) s)
8272 ;; Make a series of regular expressions to find a match
8273 (setq words (org-split-string s "[ \n\r\t]+")
8275 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8276 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8277 "\\)" markers)
8278 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8279 re2a (concat "[ \t\r\n]" re2a_)
8280 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8281 re4 (concat "[^a-zA-Z_]" re4_)
8283 re1 (concat pre re2 post)
8284 re3 (concat pre (if pre re4_ re4) post)
8285 re5 (concat pre ".*" re4)
8286 re2 (concat pre re2)
8287 re2a (concat pre (if pre re2a_ re2a))
8288 re4 (concat pre (if pre re4_ re4))
8289 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8290 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8291 re5 "\\)"
8293 (cond
8294 ((eq type 'org-occur) (org-occur reall))
8295 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8296 (t (goto-char (point-min))
8297 (setq type 'fuzzy)
8298 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8299 (org-search-not-self 1 re1 nil t)
8300 (org-search-not-self 1 re2 nil t)
8301 (org-search-not-self 1 re2a nil t)
8302 (org-search-not-self 1 re3 nil t)
8303 (org-search-not-self 1 re4 nil t)
8304 (org-search-not-self 1 re5 nil t)
8306 (goto-char (match-beginning 1))
8307 (goto-char pos)
8308 (error "No match")))))
8310 ;; Normal string-search
8311 (goto-char (point-min))
8312 (if (search-forward s nil t)
8313 (goto-char (match-beginning 0))
8314 (error "No match"))))
8315 (and (org-mode-p) (org-show-context 'link-search))
8316 type))
8318 (defun org-search-not-self (group &rest args)
8319 "Execute `re-search-forward', but only accept matches that do not
8320 enclose the position of `org-open-link-marker'."
8321 (let ((m org-open-link-marker))
8322 (catch 'exit
8323 (while (apply 're-search-forward args)
8324 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8325 (goto-char (match-end group))
8326 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8327 (> (match-beginning 0) (marker-position m))
8328 (< (match-end 0) (marker-position m)))
8329 (save-match-data
8330 (or (not (org-in-regexp
8331 org-bracket-link-analytic-regexp 1))
8332 (not (match-end 4)) ; no description
8333 (and (<= (match-beginning 4) (point))
8334 (>= (match-end 4) (point))))))
8335 (throw 'exit (point))))))))
8337 (defun org-get-buffer-for-internal-link (buffer)
8338 "Return a buffer to be used for displaying the link target of internal links."
8339 (cond
8340 ((not org-display-internal-link-with-indirect-buffer)
8341 buffer)
8342 ((string-match "(Clone)$" (buffer-name buffer))
8343 (message "Buffer is already a clone, not making another one")
8344 ;; we also do not modify visibility in this case
8345 buffer)
8346 (t ; make a new indirect buffer for displaying the link
8347 (let* ((bn (buffer-name buffer))
8348 (ibn (concat bn "(Clone)"))
8349 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8350 (with-current-buffer ib (org-overview))
8351 ib))))
8353 (defun org-do-occur (regexp &optional cleanup)
8354 "Call the Emacs command `occur'.
8355 If CLEANUP is non-nil, remove the printout of the regular expression
8356 in the *Occur* buffer. This is useful if the regex is long and not useful
8357 to read."
8358 (occur regexp)
8359 (when cleanup
8360 (let ((cwin (selected-window)) win beg end)
8361 (when (setq win (get-buffer-window "*Occur*"))
8362 (select-window win))
8363 (goto-char (point-min))
8364 (when (re-search-forward "match[a-z]+" nil t)
8365 (setq beg (match-end 0))
8366 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8367 (setq end (1- (match-beginning 0)))))
8368 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8369 (goto-char (point-min))
8370 (select-window cwin))))
8372 ;;; The mark ring for links jumps
8374 (defvar org-mark-ring nil
8375 "Mark ring for positions before jumps in Org-mode.")
8376 (defvar org-mark-ring-last-goto nil
8377 "Last position in the mark ring used to go back.")
8378 ;; Fill and close the ring
8379 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8380 (loop for i from 1 to org-mark-ring-length do
8381 (push (make-marker) org-mark-ring))
8382 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8383 org-mark-ring)
8385 (defun org-mark-ring-push (&optional pos buffer)
8386 "Put the current position or POS into the mark ring and rotate it."
8387 (interactive)
8388 (setq pos (or pos (point)))
8389 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8390 (move-marker (car org-mark-ring)
8391 (or pos (point))
8392 (or buffer (current-buffer)))
8393 (message "%s"
8394 (substitute-command-keys
8395 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8397 (defun org-mark-ring-goto (&optional n)
8398 "Jump to the previous position in the mark ring.
8399 With prefix arg N, jump back that many stored positions. When
8400 called several times in succession, walk through the entire ring.
8401 Org-mode commands jumping to a different position in the current file,
8402 or to another Org-mode file, automatically push the old position
8403 onto the ring."
8404 (interactive "p")
8405 (let (p m)
8406 (if (eq last-command this-command)
8407 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8408 (setq p org-mark-ring))
8409 (setq org-mark-ring-last-goto p)
8410 (setq m (car p))
8411 (switch-to-buffer (marker-buffer m))
8412 (goto-char m)
8413 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8415 (defun org-remove-angle-brackets (s)
8416 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8417 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8419 (defun org-add-angle-brackets (s)
8420 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8421 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8423 (defun org-remove-double-quotes (s)
8424 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8425 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8428 ;;; Following specific links
8430 (defun org-follow-timestamp-link ()
8431 (cond
8432 ((org-at-date-range-p t)
8433 (let ((org-agenda-start-on-weekday)
8434 (t1 (match-string 1))
8435 (t2 (match-string 2)))
8436 (setq t1 (time-to-days (org-time-string-to-time t1))
8437 t2 (time-to-days (org-time-string-to-time t2)))
8438 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8439 ((org-at-timestamp-p t)
8440 (org-agenda-list nil (time-to-days (org-time-string-to-time
8441 (substring (match-string 1) 0 10)))
8443 (t (error "This should not happen"))))
8446 ;;; Following file links
8447 (defvar org-wait nil)
8448 (defun org-open-file (path &optional in-emacs line search)
8449 "Open the file at PATH.
8450 First, this expands any special file name abbreviations. Then the
8451 configuration variable `org-file-apps' is checked if it contains an
8452 entry for this file type, and if yes, the corresponding command is launched.
8454 If no application is found, Emacs simply visits the file.
8456 With optional prefix argument IN-EMACS, Emacs will visit the file.
8457 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8458 and o use an external application to visit the file.
8460 Optional LINE specifies a line to go to, optional SEARCH a string to
8461 search for. If LINE or SEARCH is given, the file will always be
8462 opened in Emacs.
8463 If the file does not exist, an error is thrown."
8464 (setq in-emacs (or in-emacs line search))
8465 (let* ((file (if (equal path "")
8466 buffer-file-name
8467 (substitute-in-file-name (expand-file-name path))))
8468 (apps (append org-file-apps (org-default-apps)))
8469 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8470 (dirp (if remp nil (file-directory-p file)))
8471 (file (if (and dirp org-open-directory-means-index-dot-org)
8472 (concat (file-name-as-directory file) "index.org")
8473 file))
8474 (a-m-a-p (assq 'auto-mode apps))
8475 (dfile (downcase file))
8476 (old-buffer (current-buffer))
8477 (old-pos (point))
8478 (old-mode major-mode)
8479 ext cmd)
8480 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8481 (setq ext (match-string 1 dfile))
8482 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8483 (setq ext (match-string 1 dfile))))
8484 (cond
8485 ((equal in-emacs '(16))
8486 (setq cmd (cdr (assoc 'system apps))))
8487 (in-emacs (setq cmd 'emacs))
8489 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8490 (and dirp (cdr (assoc 'directory apps)))
8491 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8492 'string-match)
8493 (cdr (assoc ext apps))
8494 (cdr (assoc t apps))))))
8495 (when (eq cmd 'system)
8496 (setq cmd (cdr (assoc 'system apps))))
8497 (when (eq cmd 'default)
8498 (setq cmd (cdr (assoc t apps))))
8499 (when (eq cmd 'mailcap)
8500 (require 'mailcap)
8501 (mailcap-parse-mailcaps)
8502 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8503 (command (mailcap-mime-info mime-type)))
8504 (if (stringp command)
8505 (setq cmd command)
8506 (setq cmd 'emacs))))
8507 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8508 (not (file-exists-p file))
8509 (not org-open-non-existing-files))
8510 (error "No such file: %s" file))
8511 (cond
8512 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8513 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8514 (while (string-match "['\"]%s['\"]" cmd)
8515 (setq cmd (replace-match "%s" t t cmd)))
8516 (while (string-match "%s" cmd)
8517 (setq cmd (replace-match
8518 (save-match-data
8519 (shell-quote-argument
8520 (convert-standard-filename file)))
8521 t t cmd)))
8522 (save-window-excursion
8523 (start-process-shell-command cmd nil cmd)
8524 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8526 ((or (stringp cmd)
8527 (eq cmd 'emacs))
8528 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8529 (widen)
8530 (if line (org-goto-line line)
8531 (if search (org-link-search search))))
8532 ((consp cmd)
8533 (let ((file (convert-standard-filename file)))
8534 (eval cmd)))
8535 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8536 (and (org-mode-p) (eq old-mode 'org-mode)
8537 (or (not (equal old-buffer (current-buffer)))
8538 (not (equal old-pos (point))))
8539 (org-mark-ring-push old-pos old-buffer))))
8541 (defun org-default-apps ()
8542 "Return the default applications for this operating system."
8543 (cond
8544 ((eq system-type 'darwin)
8545 org-file-apps-defaults-macosx)
8546 ((eq system-type 'windows-nt)
8547 org-file-apps-defaults-windowsnt)
8548 (t org-file-apps-defaults-gnu)))
8550 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8551 "Convert extensions to regular expressions in the cars of LIST.
8552 Also, weed out any non-string entries, because the return value is used
8553 only for regexp matching.
8554 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8555 point to the symbol `emacs', indicating that the file should
8556 be opened in Emacs."
8557 (append
8558 (delq nil
8559 (mapcar (lambda (x)
8560 (if (not (stringp (car x)))
8562 (if (string-match "\\W" (car x))
8564 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8565 list))
8566 (if add-auto-mode
8567 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8569 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8570 (defun org-file-remote-p (file)
8571 "Test whether FILE specifies a location on a remote system.
8572 Return non-nil if the location is indeed remote.
8574 For example, the filename \"/user@host:/foo\" specifies a location
8575 on the system \"/user@host:\"."
8576 (cond ((fboundp 'file-remote-p)
8577 (file-remote-p file))
8578 ((fboundp 'tramp-handle-file-remote-p)
8579 (tramp-handle-file-remote-p file))
8580 ((and (boundp 'ange-ftp-name-format)
8581 (string-match (car ange-ftp-name-format) file))
8583 (t nil)))
8586 ;;;; Refiling
8588 (defun org-get-org-file ()
8589 "Read a filename, with default directory `org-directory'."
8590 (let ((default (or org-default-notes-file remember-data-file)))
8591 (read-file-name (format "File name [%s]: " default)
8592 (file-name-as-directory org-directory)
8593 default)))
8595 (defun org-notes-order-reversed-p ()
8596 "Check if the current file should receive notes in reversed order."
8597 (cond
8598 ((not org-reverse-note-order) nil)
8599 ((eq t org-reverse-note-order) t)
8600 ((not (listp org-reverse-note-order)) nil)
8601 (t (catch 'exit
8602 (let ((all org-reverse-note-order)
8603 entry)
8604 (while (setq entry (pop all))
8605 (if (string-match (car entry) buffer-file-name)
8606 (throw 'exit (cdr entry))))
8607 nil)))))
8609 (defvar org-refile-target-table nil
8610 "The list of refile targets, created by `org-refile'.")
8612 (defvar org-agenda-new-buffers nil
8613 "Buffers created to visit agenda files.")
8615 (defun org-get-refile-targets (&optional default-buffer)
8616 "Produce a table with refile targets."
8617 (let ((case-fold-search nil)
8618 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8619 (entries (or org-refile-targets '((nil . (:level . 1)))))
8620 targets txt re files f desc descre fast-path-p level pos0)
8621 (message "Getting targets...")
8622 (with-current-buffer (or default-buffer (current-buffer))
8623 (while (setq entry (pop entries))
8624 (setq files (car entry) desc (cdr entry))
8625 (setq fast-path-p nil)
8626 (cond
8627 ((null files) (setq files (list (current-buffer))))
8628 ((eq files 'org-agenda-files)
8629 (setq files (org-agenda-files 'unrestricted)))
8630 ((and (symbolp files) (fboundp files))
8631 (setq files (funcall files)))
8632 ((and (symbolp files) (boundp files))
8633 (setq files (symbol-value files))))
8634 (if (stringp files) (setq files (list files)))
8635 (cond
8636 ((eq (car desc) :tag)
8637 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8638 ((eq (car desc) :todo)
8639 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8640 ((eq (car desc) :regexp)
8641 (setq descre (cdr desc)))
8642 ((eq (car desc) :level)
8643 (setq descre (concat "^\\*\\{" (number-to-string
8644 (if org-odd-levels-only
8645 (1- (* 2 (cdr desc)))
8646 (cdr desc)))
8647 "\\}[ \t]")))
8648 ((eq (car desc) :maxlevel)
8649 (setq fast-path-p t)
8650 (setq descre (concat "^\\*\\{1," (number-to-string
8651 (if org-odd-levels-only
8652 (1- (* 2 (cdr desc)))
8653 (cdr desc)))
8654 "\\}[ \t]")))
8655 (t (error "Bad refiling target description %s" desc)))
8656 (while (setq f (pop files))
8657 (save-excursion
8658 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8659 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8660 (setq f (expand-file-name f))
8661 (if (eq org-refile-use-outline-path 'file)
8662 (push (list (file-name-nondirectory f) f nil nil) targets))
8663 (save-excursion
8664 (save-restriction
8665 (widen)
8666 (goto-char (point-min))
8667 (while (re-search-forward descre nil t)
8668 (goto-char (setq pos0 (point-at-bol)))
8669 (catch 'next
8670 (when org-refile-target-verify-function
8671 (save-match-data
8672 (or (funcall org-refile-target-verify-function)
8673 (throw 'next t))))
8674 (when (looking-at org-complex-heading-regexp)
8675 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8676 txt (org-link-display-format (match-string 4))
8677 re (concat "^" (regexp-quote
8678 (buffer-substring (match-beginning 1)
8679 (match-end 4)))))
8680 (if (match-end 5) (setq re (concat re "[ \t]+"
8681 (regexp-quote
8682 (match-string 5)))))
8683 (setq re (concat re "[ \t]*$"))
8684 (when org-refile-use-outline-path
8685 (setq txt (mapconcat 'org-protect-slash
8686 (append
8687 (if (eq org-refile-use-outline-path 'file)
8688 (list (file-name-nondirectory
8689 (buffer-file-name (buffer-base-buffer))))
8690 (if (eq org-refile-use-outline-path 'full-file-path)
8691 (list (buffer-file-name (buffer-base-buffer)))))
8692 (org-get-outline-path fast-path-p level txt)
8693 (list txt))
8694 "/")))
8695 (push (list txt f re (point)) targets)))
8696 (when (= (point) pos0)
8697 ;; verification function has not moved point
8698 (goto-char (point-at-eol))))))))))
8699 (message "Getting targets...done")
8700 (nreverse targets)))
8702 (defun org-protect-slash (s)
8703 (while (string-match "/" s)
8704 (setq s (replace-match "\\" t t s)))
8707 (defvar org-olpa (make-vector 20 nil))
8709 (defun org-get-outline-path (&optional fastp level heading)
8710 "Return the outline path to the current entry, as a list."
8711 (if fastp
8712 (progn
8713 (if (> level 19)
8714 (error "Outline path failure, more than 19 levels."))
8715 (loop for i from level upto 19 do
8716 (aset org-olpa i nil))
8717 (prog1
8718 (delq nil (append org-olpa nil))
8719 (aset org-olpa level heading)))
8720 (let (rtn)
8721 (save-excursion
8722 (while (org-up-heading-safe)
8723 (when (looking-at org-complex-heading-regexp)
8724 (push (org-match-string-no-properties 4) rtn)))
8725 rtn))))
8727 (defvar org-refile-history nil
8728 "History for refiling operations.")
8730 (defvar org-after-refile-insert-hook nil
8731 "Hook run after `org-refile' has inserted its stuff at the new location.
8732 Note that this is still *before* the stuff will be removed from
8733 the *old* location.")
8735 (defun org-refile (&optional goto default-buffer rfloc)
8736 "Move the entry at point to another heading.
8737 The list of target headings is compiled using the information in
8738 `org-refile-targets', which see. This list is created before each use
8739 and will therefore always be up-to-date.
8741 At the target location, the entry is filed as a subitem of the target heading.
8742 Depending on `org-reverse-note-order', the new subitem will either be the
8743 first or the last subitem.
8745 If there is an active region, all entries in that region will be moved.
8746 However, the region must fulfil the requirement that the first heading
8747 is the first one sets the top-level of the moved text - at most siblings
8748 below it are allowed.
8750 With prefix arg GOTO, the command will only visit the target location,
8751 not actually move anything.
8752 With a double prefix `C-u C-u', go to the location where the last refiling
8753 operation has put the subtree.
8755 RFLOC can be a refile location obtained in a different way.
8757 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8758 (interactive "P")
8759 (let* ((cbuf (current-buffer))
8760 (regionp (org-region-active-p))
8761 (region-start (and regionp (region-beginning)))
8762 (region-end (and regionp (region-end)))
8763 (region-length (and regionp (- region-end region-start)))
8764 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8765 pos it nbuf file re level reversed)
8766 (when regionp
8767 (goto-char region-start)
8768 (or (bolp) (goto-char (point-at-bol)))
8769 (setq region-start (point))
8770 (unless (org-kill-is-subtree-p
8771 (buffer-substring region-start region-end))
8772 (error "The region is not a (sequence of) subtree(s)")))
8773 (if (equal goto '(16))
8774 (org-refile-goto-last-stored)
8775 (when (setq it (or rfloc
8776 (save-excursion
8777 (org-refile-get-location
8778 (if goto "Goto: " "Refile to: ") default-buffer
8779 org-refile-allow-creating-parent-nodes))))
8780 (setq file (nth 1 it)
8781 re (nth 2 it)
8782 pos (nth 3 it))
8783 (if (and (not goto)
8785 (equal (buffer-file-name) file)
8786 (if regionp
8787 (and (>= pos region-start)
8788 (<= pos region-end))
8789 (and (>= pos (point))
8790 (< pos (save-excursion
8791 (org-end-of-subtree t t))))))
8792 (error "Cannot refile to position inside the tree or region"))
8794 (setq nbuf (or (find-buffer-visiting file)
8795 (find-file-noselect file)))
8796 (if goto
8797 (progn
8798 (switch-to-buffer nbuf)
8799 (goto-char pos)
8800 (org-show-context 'org-goto))
8801 (if regionp
8802 (progn
8803 (org-kill-new (buffer-substring region-start region-end))
8804 (org-save-markers-in-region region-start region-end))
8805 (org-copy-subtree 1 nil t))
8806 (save-excursion
8807 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8808 (find-file-noselect file))))
8809 (setq reversed (org-notes-order-reversed-p))
8810 (save-excursion
8811 (save-restriction
8812 (widen)
8813 (if pos
8814 (progn
8815 (goto-char pos)
8816 (looking-at outline-regexp)
8817 (setq level (org-get-valid-level (funcall outline-level) 1))
8818 (goto-char
8819 (if reversed
8820 (or (outline-next-heading) (point-max))
8821 (or (save-excursion (org-get-next-sibling))
8822 (org-end-of-subtree t t)
8823 (point-max)))))
8824 (setq level 1)
8825 (if (not reversed)
8826 (goto-char (point-max))
8827 (goto-char (point-min))
8828 (or (outline-next-heading) (goto-char (point-max)))))
8829 (if (not (bolp)) (newline))
8830 (bookmark-set "org-refile-last-stored")
8831 (org-paste-subtree level)
8832 (if (fboundp 'deactivate-mark) (deactivate-mark))
8833 (run-hooks 'org-after-refile-insert-hook))))
8834 (if regionp
8835 (delete-region (point) (+ (point) region-length))
8836 (org-cut-subtree))
8837 (when (featurep 'org-inlinetask)
8838 (org-inlinetask-remove-END-maybe))
8839 (setq org-markers-to-move nil)
8840 (message "Refiled to \"%s\"" (car it))))))
8841 (org-reveal))
8843 (defun org-refile-goto-last-stored ()
8844 "Go to the location where the last refile was stored."
8845 (interactive)
8846 (bookmark-jump "org-refile-last-stored")
8847 (message "This is the location of the last refile"))
8849 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8850 "Prompt the user for a refile location, using PROMPT."
8851 (let ((org-refile-targets org-refile-targets)
8852 (org-refile-use-outline-path org-refile-use-outline-path))
8853 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8854 (unless org-refile-target-table
8855 (error "No refile targets"))
8856 (let* ((cbuf (current-buffer))
8857 (partial-completion-mode nil)
8858 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8859 (cfunc (if (and org-refile-use-outline-path
8860 org-outline-path-complete-in-steps)
8861 'org-olpath-completing-read
8862 'org-icompleting-read))
8863 (extra (if org-refile-use-outline-path "/" ""))
8864 (filename (and cfn (expand-file-name cfn)))
8865 (tbl (mapcar
8866 (lambda (x)
8867 (if (and (not (member org-refile-use-outline-path
8868 '(file full-file-path)))
8869 (not (equal filename (nth 1 x))))
8870 (cons (concat (car x) extra " ("
8871 (file-name-nondirectory (nth 1 x)) ")")
8872 (cdr x))
8873 (cons (concat (car x) extra) (cdr x))))
8874 org-refile-target-table))
8875 (completion-ignore-case t)
8876 pa answ parent-target child parent old-hist)
8877 (setq old-hist org-refile-history)
8878 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8879 nil 'org-refile-history))
8880 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8881 (if pa
8882 (progn
8883 (when (or (not org-refile-history)
8884 (not (eq old-hist org-refile-history))
8885 (not (equal (car pa) (car org-refile-history))))
8886 (setq org-refile-history
8887 (cons (car pa) (if (assoc (car org-refile-history) tbl)
8888 org-refile-history
8889 (cdr org-refile-history))))
8890 (if (equal (car org-refile-history) (nth 1 org-refile-history))
8891 (pop org-refile-history)))
8893 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8894 (setq parent (match-string 1 answ)
8895 child (match-string 2 answ))
8896 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8897 (when (and parent-target
8898 (or (eq new-nodes t)
8899 (and (eq new-nodes 'confirm)
8900 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8901 (org-refile-new-child parent-target child))))))
8903 (defun org-refile-new-child (parent-target child)
8904 "Use refile target PARENT-TARGET to add new CHILD below it."
8905 (unless parent-target
8906 (error "Cannot find parent for new node"))
8907 (let ((file (nth 1 parent-target))
8908 (pos (nth 3 parent-target))
8909 level)
8910 (with-current-buffer (or (find-buffer-visiting file)
8911 (find-file-noselect file))
8912 (save-excursion
8913 (save-restriction
8914 (widen)
8915 (if pos
8916 (goto-char pos)
8917 (goto-char (point-max))
8918 (if (not (bolp)) (newline)))
8919 (when (looking-at outline-regexp)
8920 (setq level (funcall outline-level))
8921 (org-end-of-subtree t t))
8922 (org-back-over-empty-lines)
8923 (insert "\n" (make-string
8924 (if pos (org-get-valid-level level 1) 1) ?*)
8925 " " child "\n")
8926 (beginning-of-line 0)
8927 (list (concat (car parent-target) "/" child) file "" (point)))))))
8929 (defun org-olpath-completing-read (prompt collection &rest args)
8930 "Read an outline path like a file name."
8931 (let ((thetable collection)
8932 (org-completion-use-ido nil) ; does not work with ido.
8933 (org-completion-use-iswitchb nil)) ; or iswitchb
8934 (apply
8935 'org-icompleting-read prompt
8936 (lambda (string predicate &optional flag)
8937 (let (rtn r f (l (length string)))
8938 (cond
8939 ((eq flag nil)
8940 ;; try completion
8941 (try-completion string thetable))
8942 ((eq flag t)
8943 ;; all-completions
8944 (setq rtn (all-completions string thetable predicate))
8945 (mapcar
8946 (lambda (x)
8947 (setq r (substring x l))
8948 (if (string-match " ([^)]*)$" x)
8949 (setq f (match-string 0 x))
8950 (setq f ""))
8951 (if (string-match "/" r)
8952 (concat string (substring r 0 (match-end 0)) f)
8954 rtn))
8955 ((eq flag 'lambda)
8956 ;; exact match?
8957 (assoc string thetable)))
8959 args)))
8961 ;;;; Dynamic blocks
8963 (defun org-find-dblock (name)
8964 "Find the first dynamic block with name NAME in the buffer.
8965 If not found, stay at current position and return nil."
8966 (let (pos)
8967 (save-excursion
8968 (goto-char (point-min))
8969 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8970 nil t)
8971 (match-beginning 0))))
8972 (if pos (goto-char pos))
8973 pos))
8975 (defconst org-dblock-start-re
8976 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8977 "Matches the startline of a dynamic block, with parameters.")
8979 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
8980 "Matches the end of a dynamic block.")
8982 (defun org-create-dblock (plist)
8983 "Create a dynamic block section, with parameters taken from PLIST.
8984 PLIST must contain a :name entry which is used as name of the block."
8985 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
8986 (end-of-line 1)
8987 (newline))
8988 (let ((col (current-column))
8989 (name (plist-get plist :name)))
8990 (insert "#+BEGIN: " name)
8991 (while plist
8992 (if (eq (car plist) :name)
8993 (setq plist (cddr plist))
8994 (insert " " (prin1-to-string (pop plist)))))
8995 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
8996 (beginning-of-line -2)))
8998 (defun org-prepare-dblock ()
8999 "Prepare dynamic block for refresh.
9000 This empties the block, puts the cursor at the insert position and returns
9001 the property list including an extra property :name with the block name."
9002 (unless (looking-at org-dblock-start-re)
9003 (error "Not at a dynamic block"))
9004 (let* ((begdel (1+ (match-end 0)))
9005 (name (org-no-properties (match-string 1)))
9006 (params (append (list :name name)
9007 (read (concat "(" (match-string 3) ")")))))
9008 (save-excursion
9009 (beginning-of-line 1)
9010 (skip-chars-forward " \t")
9011 (setq params (plist-put params :indentation-column (current-column))))
9012 (unless (re-search-forward org-dblock-end-re nil t)
9013 (error "Dynamic block not terminated"))
9014 (setq params
9015 (append params
9016 (list :content (buffer-substring
9017 begdel (match-beginning 0)))))
9018 (delete-region begdel (match-beginning 0))
9019 (goto-char begdel)
9020 (open-line 1)
9021 params))
9023 (defun org-map-dblocks (&optional command)
9024 "Apply COMMAND to all dynamic blocks in the current buffer.
9025 If COMMAND is not given, use `org-update-dblock'."
9026 (let ((cmd (or command 'org-update-dblock))
9027 pos)
9028 (save-excursion
9029 (goto-char (point-min))
9030 (while (re-search-forward org-dblock-start-re nil t)
9031 (goto-char (setq pos (match-beginning 0)))
9032 (condition-case nil
9033 (funcall cmd)
9034 (error (message "Error during update of dynamic block")))
9035 (goto-char pos)
9036 (unless (re-search-forward org-dblock-end-re nil t)
9037 (error "Dynamic block not terminated"))))))
9039 (defun org-dblock-update (&optional arg)
9040 "User command for updating dynamic blocks.
9041 Update the dynamic block at point. With prefix ARG, update all dynamic
9042 blocks in the buffer."
9043 (interactive "P")
9044 (if arg
9045 (org-update-all-dblocks)
9046 (or (looking-at org-dblock-start-re)
9047 (org-beginning-of-dblock))
9048 (org-update-dblock)))
9050 (defun org-update-dblock ()
9051 "Update the dynamic block at point
9052 This means to empty the block, parse for parameters and then call
9053 the correct writing function."
9054 (save-window-excursion
9055 (let* ((pos (point))
9056 (line (org-current-line))
9057 (params (org-prepare-dblock))
9058 (name (plist-get params :name))
9059 (indent (plist-get params :indentation-column))
9060 (cmd (intern (concat "org-dblock-write:" name))))
9061 (message "Updating dynamic block `%s' at line %d..." name line)
9062 (funcall cmd params)
9063 (message "Updating dynamic block `%s' at line %d...done" name line)
9064 (goto-char pos)
9065 (when (and indent (> indent 0))
9066 (setq indent (make-string indent ?\ ))
9067 (save-excursion
9068 (org-beginning-of-dblock)
9069 (forward-line 1)
9070 (while (not (looking-at org-dblock-end-re))
9071 (insert indent)
9072 (beginning-of-line 2))
9073 (when (looking-at org-dblock-end-re)
9074 (and (looking-at "[ \t]+")
9075 (replace-match ""))
9076 (insert indent)))))))
9078 (defun org-beginning-of-dblock ()
9079 "Find the beginning of the dynamic block at point.
9080 Error if there is no such block at point."
9081 (let ((pos (point))
9082 beg)
9083 (end-of-line 1)
9084 (if (and (re-search-backward org-dblock-start-re nil t)
9085 (setq beg (match-beginning 0))
9086 (re-search-forward org-dblock-end-re nil t)
9087 (> (match-end 0) pos))
9088 (goto-char beg)
9089 (goto-char pos)
9090 (error "Not in a dynamic block"))))
9092 (defun org-update-all-dblocks ()
9093 "Update all dynamic blocks in the buffer.
9094 This function can be used in a hook."
9095 (when (org-mode-p)
9096 (org-map-dblocks 'org-update-dblock)))
9099 ;;;; Completion
9101 (defconst org-additional-option-like-keywords
9102 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9103 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9104 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
9105 "BEGIN:" "END:"
9106 "ORGTBL" "TBLFM:" "TBLNAME:"
9107 "BEGIN_EXAMPLE" "END_EXAMPLE"
9108 "BEGIN_QUOTE" "END_QUOTE"
9109 "BEGIN_VERSE" "END_VERSE"
9110 "BEGIN_CENTER" "END_CENTER"
9111 "BEGIN_SRC" "END_SRC"
9112 "CATEGORY" "COLUMNS"
9113 "CAPTION" "LABEL"
9114 "BIND"
9115 "MACRO"))
9117 (defcustom org-structure-template-alist
9119 ("s" "#+begin_src ?\n\n#+end_src"
9120 "<src lang=\"?\">\n\n</src>")
9121 ("e" "#+begin_example\n?\n#+end_example"
9122 "<example>\n?\n</example>")
9123 ("q" "#+begin_quote\n?\n#+end_quote"
9124 "<quote>\n?\n</quote>")
9125 ("v" "#+begin_verse\n?\n#+end_verse"
9126 "<verse>\n?\n/verse>")
9127 ("c" "#+begin_center\n?\n#+end_center"
9128 "<center>\n?\n/center>")
9129 ("l" "#+begin_latex\n?\n#+end_latex"
9130 "<literal style=\"latex\">\n?\n</literal>")
9131 ("L" "#+latex: "
9132 "<literal style=\"latex\">?</literal>")
9133 ("h" "#+begin_html\n?\n#+end_html"
9134 "<literal style=\"html\">\n?\n</literal>")
9135 ("H" "#+html: "
9136 "<literal style=\"html\">?</literal>")
9137 ("a" "#+begin_ascii\n?\n#+end_ascii")
9138 ("A" "#+ascii: ")
9139 ("i" "#+include %file ?"
9140 "<include file=%file markup=\"?\">")
9142 "Structure completion elements.
9143 This is a list of abbreviation keys and values. The value gets inserted
9144 it you type @samp{.} followed by the key and then the completion key,
9145 usually `M-TAB'. %file will be replaced by a file name after prompting
9146 for the file using completion.
9147 There are two templates for each key, the first uses the original Org syntax,
9148 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9149 the default when the /org-mtags.el/ module has been loaded. See also the
9150 variable `org-mtags-prefer-muse-templates'.
9151 This is an experimental feature, it is undecided if it is going to stay in."
9152 :group 'org-completion
9153 :type '(repeat
9154 (string :tag "Key")
9155 (string :tag "Template")
9156 (string :tag "Muse Template")))
9158 (defun org-try-structure-completion ()
9159 "Try to complete a structure template before point.
9160 This looks for strings like \"<e\" on an otherwise empty line and
9161 expands them."
9162 (let ((l (buffer-substring (point-at-bol) (point)))
9164 (when (and (looking-at "[ \t]*$")
9165 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9166 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9167 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9168 (match-beginning 1)) a)
9169 t)))
9171 (defun org-complete-expand-structure-template (start cell)
9172 "Expand a structure template."
9173 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9174 (rpl (nth (if musep 2 1) cell))
9175 (ind ""))
9176 (delete-region start (point))
9177 (when (string-match "\\`#\\+" rpl)
9178 (cond
9179 ((bolp))
9180 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9181 (setq ind (buffer-substring (point-at-bol) (point))))
9182 (t (newline))))
9183 (setq start (point))
9184 (if (string-match "%file" rpl)
9185 (setq rpl (replace-match
9186 (concat
9187 "\""
9188 (save-match-data
9189 (abbreviate-file-name (read-file-name "Include file: ")))
9190 "\"")
9191 t t rpl)))
9192 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9193 (concat "\n" ind)))
9194 (insert rpl)
9195 (if (re-search-backward "\\?" start t) (delete-char 1))))
9198 (defun org-complete (&optional arg)
9199 "Perform completion on word at point.
9200 At the beginning of a headline, this completes TODO keywords as given in
9201 `org-todo-keywords'.
9202 If the current word is preceded by a backslash, completes the TeX symbols
9203 that are supported for HTML support.
9204 If the current word is preceded by \"#+\", completes special words for
9205 setting file options.
9206 In the line after \"#+STARTUP:, complete valid keywords.\"
9207 At all other locations, this simply calls the value of
9208 `org-completion-fallback-command'."
9209 (interactive "P")
9210 (org-without-partial-completion
9211 (catch 'exit
9212 (let* ((a nil)
9213 (end (point))
9214 (beg1 (save-excursion
9215 (skip-chars-backward (org-re "[:alnum:]_@"))
9216 (point)))
9217 (beg (save-excursion
9218 (skip-chars-backward "a-zA-Z0-9_:$")
9219 (point)))
9220 (confirm (lambda (x) (stringp (car x))))
9221 (searchhead (equal (char-before beg) ?*))
9222 (struct
9223 (when (and (member (char-before beg1) '(?. ?<))
9224 (setq a (assoc (buffer-substring beg1 (point))
9225 org-structure-template-alist)))
9226 (org-complete-expand-structure-template (1- beg1) a)
9227 (throw 'exit t)))
9228 (tag (and (equal (char-before beg1) ?:)
9229 (equal (char-after (point-at-bol)) ?*)))
9230 (prop (and (equal (char-before beg1) ?:)
9231 (not (equal (char-after (point-at-bol)) ?*))))
9232 (texp (equal (char-before beg) ?\\))
9233 (link (equal (char-before beg) ?\[))
9234 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9235 beg)
9236 "#+"))
9237 (startup (string-match "^#\\+STARTUP:.*"
9238 (buffer-substring (point-at-bol) (point))))
9239 (completion-ignore-case opt)
9240 (type nil)
9241 (tbl nil)
9242 (table (cond
9243 (opt
9244 (setq type :opt)
9245 (require 'org-exp)
9246 (append
9247 (delq nil
9248 (mapcar
9249 (lambda (x)
9250 (if (string-match
9251 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9252 (cons (match-string 2 x)
9253 (match-string 1 x))))
9254 (org-split-string (org-get-current-options) "\n")))
9255 (mapcar 'list org-additional-option-like-keywords)))
9256 (startup
9257 (setq type :startup)
9258 org-startup-options)
9259 (link (append org-link-abbrev-alist-local
9260 org-link-abbrev-alist))
9261 (texp
9262 (setq type :tex)
9263 org-html-entities)
9264 ((string-match "\\`\\*+[ \t]+\\'"
9265 (buffer-substring (point-at-bol) beg))
9266 (setq type :todo)
9267 (mapcar 'list org-todo-keywords-1))
9268 (searchhead
9269 (setq type :searchhead)
9270 (save-excursion
9271 (goto-char (point-min))
9272 (while (re-search-forward org-todo-line-regexp nil t)
9273 (push (list
9274 (org-make-org-heading-search-string
9275 (match-string 3) t))
9276 tbl)))
9277 tbl)
9278 (tag (setq type :tag beg beg1)
9279 (or org-tag-alist (org-get-buffer-tags)))
9280 (prop (setq type :prop beg beg1)
9281 (mapcar 'list (org-buffer-property-keys nil t t)))
9282 (t (progn
9283 (call-interactively org-completion-fallback-command)
9284 (throw 'exit nil)))))
9285 (pattern (buffer-substring-no-properties beg end))
9286 (completion (try-completion pattern table confirm)))
9287 (cond ((eq completion t)
9288 (if (not (assoc (upcase pattern) table))
9289 (message "Already complete")
9290 (if (and (equal type :opt)
9291 (not (member (car (assoc (upcase pattern) table))
9292 org-additional-option-like-keywords)))
9293 (insert (substring (cdr (assoc (upcase pattern) table))
9294 (length pattern)))
9295 (if (memq type '(:tag :prop)) (insert ":")))))
9296 ((null completion)
9297 (message "Can't find completion for \"%s\"" pattern)
9298 (ding))
9299 ((not (string= pattern completion))
9300 (delete-region beg end)
9301 (if (string-match " +$" completion)
9302 (setq completion (replace-match "" t t completion)))
9303 (insert completion)
9304 (if (get-buffer-window "*Completions*")
9305 (delete-window (get-buffer-window "*Completions*")))
9306 (if (assoc completion table)
9307 (if (eq type :todo) (insert " ")
9308 (if (memq type '(:tag :prop)) (insert ":"))))
9309 (if (and (equal type :opt) (assoc completion table))
9310 (message "%s" (substitute-command-keys
9311 "Press \\[org-complete] again to insert example settings"))))
9313 (message "Making completion list...")
9314 (let ((list (sort (all-completions pattern table confirm)
9315 'string<)))
9316 (with-output-to-temp-buffer "*Completions*"
9317 (condition-case nil
9318 ;; Protection needed for XEmacs and emacs 21
9319 (display-completion-list list pattern)
9320 (error (display-completion-list list)))))
9321 (message "Making completion list...%s" "done")))))))
9323 ;;;; TODO, DEADLINE, Comments
9325 (defun org-toggle-comment ()
9326 "Change the COMMENT state of an entry."
9327 (interactive)
9328 (save-excursion
9329 (org-back-to-heading)
9330 (let (case-fold-search)
9331 (if (looking-at (concat outline-regexp
9332 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9333 (replace-match "" t t nil 1)
9334 (if (looking-at outline-regexp)
9335 (progn
9336 (goto-char (match-end 0))
9337 (insert org-comment-string " ")))))))
9339 (defvar org-last-todo-state-is-todo nil
9340 "This is non-nil when the last TODO state change led to a TODO state.
9341 If the last change removed the TODO tag or switched to DONE, then
9342 this is nil.")
9344 (defvar org-setting-tags nil) ; dynamically skipped
9346 (defun org-parse-local-options (string var)
9347 "Parse STRING for startup setting relevant for variable VAR."
9348 (let ((rtn (symbol-value var))
9349 e opts)
9350 (save-match-data
9351 (if (or (not string) (not (string-match "\\S-" string)))
9353 (setq opts (delq nil (mapcar (lambda (x)
9354 (setq e (assoc x org-startup-options))
9355 (if (eq (nth 1 e) var) e nil))
9356 (org-split-string string "[ \t]+"))))
9357 (if (not opts)
9359 (setq rtn nil)
9360 (while (setq e (pop opts))
9361 (if (not (nth 3 e))
9362 (setq rtn (nth 2 e))
9363 (if (not (listp rtn)) (setq rtn nil))
9364 (push (nth 2 e) rtn)))
9365 rtn)))))
9367 (defvar org-todo-setup-filter-hook nil
9368 "Hook for functions that pre-filter todo specs.
9370 Each function takes a todo spec and returns either `nil' or the spec
9371 transformed into canonical form." )
9373 (defvar org-todo-get-default-hook nil
9374 "Hook for functions that get a default item for todo.
9376 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9377 `nil' or a string to be used for the todo mark." )
9379 (defvar org-agenda-headline-snapshot-before-repeat)
9381 (defun org-todo (&optional arg)
9382 "Change the TODO state of an item.
9383 The state of an item is given by a keyword at the start of the heading,
9384 like
9385 *** TODO Write paper
9386 *** DONE Call mom
9388 The different keywords are specified in the variable `org-todo-keywords'.
9389 By default the available states are \"TODO\" and \"DONE\".
9390 So for this example: when the item starts with TODO, it is changed to DONE.
9391 When it starts with DONE, the DONE is removed. And when neither TODO nor
9392 DONE are present, add TODO at the beginning of the heading.
9394 With C-u prefix arg, use completion to determine the new state.
9395 With numeric prefix arg, switch to that state.
9396 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9397 With a tripple C-u prefix, circumvent any state blocking.
9399 For calling through lisp, arg is also interpreted in the following way:
9400 'none -> empty state
9401 \"\"(empty string) -> switch to empty state
9402 'done -> switch to DONE
9403 'nextset -> switch to the next set of keywords
9404 'previousset -> switch to the previous set of keywords
9405 \"WAITING\" -> switch to the specified keyword, but only if it
9406 really is a member of `org-todo-keywords'."
9407 (interactive "P")
9408 (if (equal arg '(16)) (setq arg 'nextset))
9409 (let ((org-blocker-hook org-blocker-hook)
9410 (case-fold-search nil))
9411 (when (equal arg '(64))
9412 (setq arg nil org-blocker-hook nil))
9413 (when (and org-blocker-hook
9414 (or org-inhibit-blocking
9415 (org-entry-get nil "NOBLOCKING")))
9416 (setq org-blocker-hook nil))
9417 (save-excursion
9418 (catch 'exit
9419 (org-back-to-heading)
9420 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9421 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9422 (looking-at " *"))
9423 (let* ((match-data (match-data))
9424 (startpos (point-at-bol))
9425 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9426 (org-log-done org-log-done)
9427 (org-log-repeat org-log-repeat)
9428 (org-todo-log-states org-todo-log-states)
9429 (this (match-string 1))
9430 (hl-pos (match-beginning 0))
9431 (head (org-get-todo-sequence-head this))
9432 (ass (assoc head org-todo-kwd-alist))
9433 (interpret (nth 1 ass))
9434 (done-word (nth 3 ass))
9435 (final-done-word (nth 4 ass))
9436 (last-state (or this ""))
9437 (completion-ignore-case t)
9438 (member (member this org-todo-keywords-1))
9439 (tail (cdr member))
9440 (state (cond
9441 ((and org-todo-key-trigger
9442 (or (and (equal arg '(4))
9443 (eq org-use-fast-todo-selection 'prefix))
9444 (and (not arg) org-use-fast-todo-selection
9445 (not (eq org-use-fast-todo-selection
9446 'prefix)))))
9447 ;; Use fast selection
9448 (org-fast-todo-selection))
9449 ((and (equal arg '(4))
9450 (or (not org-use-fast-todo-selection)
9451 (not org-todo-key-trigger)))
9452 ;; Read a state with completion
9453 (org-icompleting-read
9454 "State: " (mapcar (lambda(x) (list x))
9455 org-todo-keywords-1)
9456 nil t))
9457 ((eq arg 'right)
9458 (if this
9459 (if tail (car tail) nil)
9460 (car org-todo-keywords-1)))
9461 ((eq arg 'left)
9462 (if (equal member org-todo-keywords-1)
9464 (if this
9465 (nth (- (length org-todo-keywords-1)
9466 (length tail) 2)
9467 org-todo-keywords-1)
9468 (org-last org-todo-keywords-1))))
9469 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9470 (setq arg nil))) ; hack to fall back to cycling
9471 (arg
9472 ;; user or caller requests a specific state
9473 (cond
9474 ((equal arg "") nil)
9475 ((eq arg 'none) nil)
9476 ((eq arg 'done) (or done-word (car org-done-keywords)))
9477 ((eq arg 'nextset)
9478 (or (car (cdr (member head org-todo-heads)))
9479 (car org-todo-heads)))
9480 ((eq arg 'previousset)
9481 (let ((org-todo-heads (reverse org-todo-heads)))
9482 (or (car (cdr (member head org-todo-heads)))
9483 (car org-todo-heads))))
9484 ((car (member arg org-todo-keywords-1)))
9485 ((nth (1- (prefix-numeric-value arg))
9486 org-todo-keywords-1))))
9487 ((null member) (or head (car org-todo-keywords-1)))
9488 ((equal this final-done-word) nil) ;; -> make empty
9489 ((null tail) nil) ;; -> first entry
9490 ((memq interpret '(type priority))
9491 (if (eq this-command last-command)
9492 (car tail)
9493 (if (> (length tail) 0)
9494 (or done-word (car org-done-keywords))
9495 nil)))
9497 (car tail))))
9498 (state (or
9499 (run-hook-with-args-until-success
9500 'org-todo-get-default-hook state last-state)
9501 state))
9502 (next (if state (concat " " state " ") " "))
9503 (change-plist (list :type 'todo-state-change :from this :to state
9504 :position startpos))
9505 dolog now-done-p)
9506 (when org-blocker-hook
9507 (setq org-last-todo-state-is-todo
9508 (not (member this org-done-keywords)))
9509 (unless (save-excursion
9510 (save-match-data
9511 (run-hook-with-args-until-failure
9512 'org-blocker-hook change-plist)))
9513 (if (interactive-p)
9514 (error "TODO state change from %s to %s blocked" this state)
9515 ;; fail silently
9516 (message "TODO state change from %s to %s blocked" this state)
9517 (throw 'exit nil))))
9518 (store-match-data match-data)
9519 (replace-match next t t)
9520 (unless (pos-visible-in-window-p hl-pos)
9521 (message "TODO state changed to %s" (org-trim next)))
9522 (unless head
9523 (setq head (org-get-todo-sequence-head state)
9524 ass (assoc head org-todo-kwd-alist)
9525 interpret (nth 1 ass)
9526 done-word (nth 3 ass)
9527 final-done-word (nth 4 ass)))
9528 (when (memq arg '(nextset previousset))
9529 (message "Keyword-Set %d/%d: %s"
9530 (- (length org-todo-sets) -1
9531 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9532 (length org-todo-sets)
9533 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9534 (setq org-last-todo-state-is-todo
9535 (not (member state org-done-keywords)))
9536 (setq now-done-p (and (member state org-done-keywords)
9537 (not (member this org-done-keywords))))
9538 (and logging (org-local-logging logging))
9539 (when (and (or org-todo-log-states org-log-done)
9540 (not (eq org-inhibit-logging t))
9541 (not (memq arg '(nextset previousset))))
9542 ;; we need to look at recording a time and note
9543 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9544 (nth 2 (assoc this org-todo-log-states))))
9545 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9546 (setq dolog 'time))
9547 (when (and state
9548 (member state org-not-done-keywords)
9549 (not (member this org-not-done-keywords)))
9550 ;; This is now a todo state and was not one before
9551 ;; If there was a CLOSED time stamp, get rid of it.
9552 (org-add-planning-info nil nil 'closed))
9553 (when (and now-done-p org-log-done)
9554 ;; It is now done, and it was not done before
9555 (org-add-planning-info 'closed (org-current-time))
9556 (if (and (not dolog) (eq 'note org-log-done))
9557 (org-add-log-setup 'done state this 'findpos 'note)))
9558 (when (and state dolog)
9559 ;; This is a non-nil state, and we need to log it
9560 (org-add-log-setup 'state state this 'findpos dolog)))
9561 ;; Fixup tag positioning
9562 (org-todo-trigger-tag-changes state)
9563 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9564 (when org-provide-todo-statistics
9565 (org-update-parent-todo-statistics))
9566 (run-hooks 'org-after-todo-state-change-hook)
9567 (if (and arg (not (member state org-done-keywords)))
9568 (setq head (org-get-todo-sequence-head state)))
9569 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9570 ;; Do we need to trigger a repeat?
9571 (when now-done-p
9572 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9573 ;; This is for the agenda, take a snapshot of the headline.
9574 (save-match-data
9575 (setq org-agenda-headline-snapshot-before-repeat
9576 (org-get-heading))))
9577 (org-auto-repeat-maybe state))
9578 ;; Fixup cursor location if close to the keyword
9579 (if (and (outline-on-heading-p)
9580 (not (bolp))
9581 (save-excursion (beginning-of-line 1)
9582 (looking-at org-todo-line-regexp))
9583 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9584 (progn
9585 (goto-char (or (match-end 2) (match-end 1)))
9586 (and (looking-at " ") (just-one-space))))
9587 (when org-trigger-hook
9588 (save-excursion
9589 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9591 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9592 "Block turning an entry into a TODO, using the hierarchy.
9593 This checks whether the current task should be blocked from state
9594 changes. Such blocking occurs when:
9596 1. The task has children which are not all in a completed state.
9598 2. A task has a parent with the property :ORDERED:, and there
9599 are siblings prior to the current task with incomplete
9600 status.
9602 3. The parent of the task is blocked because it has siblings that should
9603 be done first, or is child of a block grandparent TODO entry."
9605 (catch 'dont-block
9606 ;; If this is not a todo state change, or if this entry is already DONE,
9607 ;; do not block
9608 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9609 (member (plist-get change-plist :from)
9610 (cons 'done org-done-keywords))
9611 (member (plist-get change-plist :to)
9612 (cons 'todo org-not-done-keywords)))
9613 (throw 'dont-block t))
9614 ;; If this task has children, and any are undone, it's blocked
9615 (save-excursion
9616 (org-back-to-heading t)
9617 (let ((this-level (funcall outline-level)))
9618 (outline-next-heading)
9619 (let ((child-level (funcall outline-level)))
9620 (while (and (not (eobp))
9621 (> child-level this-level))
9622 ;; this todo has children, check whether they are all
9623 ;; completed
9624 (if (and (not (org-entry-is-done-p))
9625 (org-entry-is-todo-p))
9626 (throw 'dont-block nil))
9627 (outline-next-heading)
9628 (setq child-level (funcall outline-level))))))
9629 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9630 ;; any previous siblings are undone, it's blocked
9631 (save-excursion
9632 (org-back-to-heading t)
9633 (let* ((pos (point))
9634 (parent-pos (and (org-up-heading-safe) (point))))
9635 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9636 (when (and (org-entry-get (point) "ORDERED")
9637 (forward-line 1)
9638 (re-search-forward org-not-done-heading-regexp pos t))
9639 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9640 ;; Search further up the hierarchy, to see if an anchestor is blocked
9641 (while t
9642 (goto-char parent-pos)
9643 (if (not (looking-at org-not-done-heading-regexp))
9644 (throw 'dont-block t)) ; do not block, parent is not a TODO
9645 (setq pos (point))
9646 (setq parent-pos (and (org-up-heading-safe) (point)))
9647 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9648 (when (and (org-entry-get (point) "ORDERED")
9649 (forward-line 1)
9650 (re-search-forward org-not-done-heading-regexp pos t))
9651 (throw 'dont-block nil))))))) ; block, older sibling not done.
9653 (defcustom org-track-ordered-property-with-tag nil
9654 "Should the ORDERED property also be shown as a tag?
9655 The ORDERED property decides if an entry should require subtasks to be
9656 completed in sequence. Since a property is not very visible, setting
9657 this option means that toggling the ORDERED property with the command
9658 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9659 not relevant for the behavior, but it makes things more visible.
9661 Note that toggling the tag with tags commands will not change the property
9662 and therefore not influence behavior!
9664 This can be t, meaning the tag ORDERED should be used, It can also be a
9665 string to select a different tag for this task."
9666 :group 'org-todo
9667 :type '(choice
9668 (const :tag "No tracking" nil)
9669 (const :tag "Track with ORDERED tag" t)
9670 (string :tag "Use other tag")))
9672 (defun org-toggle-ordered-property ()
9673 "Toggle the ORDERED property of the current entry.
9674 For better visibility, you can track the value of this property with a tag.
9675 See variable `org-track-ordered-property-with-tag'."
9676 (interactive)
9677 (let* ((t1 org-track-ordered-property-with-tag)
9678 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9679 (save-excursion
9680 (org-back-to-heading)
9681 (if (org-entry-get nil "ORDERED")
9682 (progn
9683 (org-delete-property "ORDERED")
9684 (and tag (org-toggle-tag tag 'off))
9685 (message "Subtasks can be completed in arbitrary order"))
9686 (org-entry-put nil "ORDERED" "t")
9687 (and tag (org-toggle-tag tag 'on))
9688 (message "Subtasks must be completed in sequence")))))
9690 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9691 (defun org-block-todo-from-checkboxes (change-plist)
9692 "Block turning an entry into a TODO, using checkboxes.
9693 This checks whether the current task should be blocked from state
9694 changes because there are uncheckd boxes in this entry."
9695 (catch 'dont-block
9696 ;; If this is not a todo state change, or if this entry is already DONE,
9697 ;; do not block
9698 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9699 (member (plist-get change-plist :from)
9700 (cons 'done org-done-keywords))
9701 (member (plist-get change-plist :to)
9702 (cons 'todo org-not-done-keywords)))
9703 (throw 'dont-block t))
9704 ;; If this task has checkboxes that are not checked, it's blocked
9705 (save-excursion
9706 (org-back-to-heading t)
9707 (let ((beg (point)) end)
9708 (outline-next-heading)
9709 (setq end (point))
9710 (goto-char beg)
9711 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9712 end t)
9713 (progn
9714 (if (boundp 'org-blocked-by-checkboxes)
9715 (setq org-blocked-by-checkboxes t))
9716 (throw 'dont-block nil)))))
9717 t)) ; do not block
9719 (defun org-update-statistics-cookies (all)
9720 "Update the statistics cookie, either from TODO or from checkboxes.
9721 This should be called with the cursor in a line with a statistics cookie."
9722 (interactive "P")
9723 (if all
9724 (progn
9725 (org-update-checkbox-count 'all)
9726 (org-map-entries 'org-update-parent-todo-statistics))
9727 (if (not (org-on-heading-p))
9728 (org-update-checkbox-count)
9729 (let ((pos (move-marker (make-marker) (point)))
9730 end l1 l2)
9731 (ignore-errors (org-back-to-heading t))
9732 (if (not (org-on-heading-p))
9733 (org-update-checkbox-count)
9734 (setq l1 (org-outline-level))
9735 (setq end (save-excursion
9736 (outline-next-heading)
9737 (if (org-on-heading-p) (setq l2 (org-outline-level)))
9738 (point)))
9739 (if (and (save-excursion (re-search-forward
9740 "^[ \t]*[-+*] \\[[- X]\\]" end t))
9741 (not (save-excursion (re-search-forward
9742 ":COOKIE_DATA:.*\\<todo\\>" end t))))
9743 (org-update-checkbox-count)
9744 (if (and l2 (> l2 l1))
9745 (progn
9746 (goto-char end)
9747 (org-update-parent-todo-statistics))
9748 (error "No data for statistics cookie"))))
9749 (goto-char pos)
9750 (move-marker pos nil)))))
9752 (defvar org-entry-property-inherited-from) ;; defined below
9753 (defun org-update-parent-todo-statistics ()
9754 "Update any statistics cookie in the parent of the current headline.
9755 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9756 the entire subtree and this will travel up the hierarchy and update
9757 statistics everywhere."
9758 (interactive)
9759 (let* ((lim 0) prop
9760 (recursive (or (not org-hierarchical-todo-statistics)
9761 (string-match
9762 "\\<recursive\\>"
9763 (or (setq prop (org-entry-get
9764 nil "COOKIE_DATA" 'inherit)) ""))))
9765 (lim (or (and prop (marker-position
9766 org-entry-property-inherited-from))
9767 lim))
9768 (first t)
9769 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9770 level ltoggle l1
9771 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9772 (catch 'exit
9773 (save-excursion
9774 (beginning-of-line 1)
9775 (if (org-at-heading-p)
9776 (setq ltoggle (funcall outline-level))
9777 (error "This should not happen"))
9778 (while (and (setq level (org-up-heading-safe))
9779 (or recursive first)
9780 (>= (point) lim))
9781 (setq first nil)
9782 (unless (and level
9783 (not (string-match
9784 "\\<checkbox\\>"
9785 (downcase
9786 (or (org-entry-get
9787 nil "COOKIE_DATA")
9788 "")))))
9789 (throw 'exit nil))
9790 (while (re-search-forward box-re (point-at-eol) t)
9791 (setq cnt-all 0 cnt-done 0 cookie-present t)
9792 (setq is-percent (match-end 2))
9793 (save-match-data
9794 (unless (outline-next-heading) (throw 'exit nil))
9795 (while (and (looking-at org-complex-heading-regexp)
9796 (> (setq l1 (length (match-string 1))) level))
9797 (setq kwd (and (or recursive (= l1 ltoggle))
9798 (match-string 2)))
9799 (if (or (eq org-provide-todo-statistics 'all-headlines)
9800 (and (listp org-provide-todo-statistics)
9801 (or (member kwd org-provide-todo-statistics)
9802 (member kwd org-done-keywords))))
9803 (setq cnt-all (1+ cnt-all))
9804 (if (eq org-provide-todo-statistics t)
9805 (and kwd (setq cnt-all (1+ cnt-all)))))
9806 (and (member kwd org-done-keywords)
9807 (setq cnt-done (1+ cnt-done)))
9808 (outline-next-heading)))
9809 (replace-match
9810 (if is-percent
9811 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9812 (format "[%d/%d]" cnt-done cnt-all)))))
9813 (when cookie-present
9814 (run-hook-with-args 'org-after-todo-statistics-hook
9815 cnt-done (- cnt-all cnt-done)))))
9816 (run-hooks 'org-todo-statistics-hook)))
9818 (defvar org-after-todo-statistics-hook nil
9819 "Hook that is called after a TODO statistics cookie has been updated.
9820 Each function is called with two arguments: the number of not-done entries
9821 and the number of done entries.
9823 For example, the following function, when added to this hook, will switch
9824 an entry to DONE when all children are done, and back to TODO when new
9825 entries are set to a TODO status. Note that this hook is only called
9826 when there is a statistics cookie in the headline!
9828 (defun org-summary-todo (n-done n-not-done)
9829 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9830 (let (org-log-done org-log-states) ; turn off logging
9831 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9834 (defvar org-todo-statistics-hook nil
9835 "Hook that is run whenever Org thinks TODO statistics should be updated.
9836 This hook runs even if there is no statisics cookie present, in which case
9837 `org-after-todo-statistics-hook' would not run.")
9839 (defun org-todo-trigger-tag-changes (state)
9840 "Apply the changes defined in `org-todo-state-tags-triggers'."
9841 (let ((l org-todo-state-tags-triggers)
9842 changes)
9843 (when (or (not state) (equal state ""))
9844 (setq changes (append changes (cdr (assoc "" l)))))
9845 (when (and (stringp state) (> (length state) 0))
9846 (setq changes (append changes (cdr (assoc state l)))))
9847 (when (member state org-not-done-keywords)
9848 (setq changes (append changes (cdr (assoc 'todo l)))))
9849 (when (member state org-done-keywords)
9850 (setq changes (append changes (cdr (assoc 'done l)))))
9851 (dolist (c changes)
9852 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9854 (defun org-local-logging (value)
9855 "Get logging settings from a property VALUE."
9856 (let* (words w a)
9857 ;; directly set the variables, they are already local.
9858 (setq org-log-done nil
9859 org-log-repeat nil
9860 org-todo-log-states nil)
9861 (setq words (org-split-string value))
9862 (while (setq w (pop words))
9863 (cond
9864 ((setq a (assoc w org-startup-options))
9865 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9866 (set (nth 1 a) (nth 2 a))))
9867 ((setq a (org-extract-log-state-settings w))
9868 (and (member (car a) org-todo-keywords-1)
9869 (push a org-todo-log-states)))))))
9871 (defun org-get-todo-sequence-head (kwd)
9872 "Return the head of the TODO sequence to which KWD belongs.
9873 If KWD is not set, check if there is a text property remembering the
9874 right sequence."
9875 (let (p)
9876 (cond
9877 ((not kwd)
9878 (or (get-text-property (point-at-bol) 'org-todo-head)
9879 (progn
9880 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9881 nil (point-at-eol)))
9882 (get-text-property p 'org-todo-head))))
9883 ((not (member kwd org-todo-keywords-1))
9884 (car org-todo-keywords-1))
9885 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9887 (defun org-fast-todo-selection ()
9888 "Fast TODO keyword selection with single keys.
9889 Returns the new TODO keyword, or nil if no state change should occur."
9890 (let* ((fulltable org-todo-key-alist)
9891 (done-keywords org-done-keywords) ;; needed for the faces.
9892 (maxlen (apply 'max (mapcar
9893 (lambda (x)
9894 (if (stringp (car x)) (string-width (car x)) 0))
9895 fulltable)))
9896 (expert nil)
9897 (fwidth (+ maxlen 3 1 3))
9898 (ncol (/ (- (window-width) 4) fwidth))
9899 tg cnt e c tbl
9900 groups ingroup)
9901 (save-excursion
9902 (save-window-excursion
9903 (if expert
9904 (set-buffer (get-buffer-create " *Org todo*"))
9905 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9906 (erase-buffer)
9907 (org-set-local 'org-done-keywords done-keywords)
9908 (setq tbl fulltable cnt 0)
9909 (while (setq e (pop tbl))
9910 (cond
9911 ((equal e '(:startgroup))
9912 (push '() groups) (setq ingroup t)
9913 (when (not (= cnt 0))
9914 (setq cnt 0)
9915 (insert "\n"))
9916 (insert "{ "))
9917 ((equal e '(:endgroup))
9918 (setq ingroup nil cnt 0)
9919 (insert "}\n"))
9920 ((equal e '(:newline))
9921 (when (not (= cnt 0))
9922 (setq cnt 0)
9923 (insert "\n")
9924 (setq e (car tbl))
9925 (while (equal (car tbl) '(:newline))
9926 (insert "\n")
9927 (setq tbl (cdr tbl)))))
9929 (setq tg (car e) c (cdr e))
9930 (if ingroup (push tg (car groups)))
9931 (setq tg (org-add-props tg nil 'face
9932 (org-get-todo-face tg)))
9933 (if (and (= cnt 0) (not ingroup)) (insert " "))
9934 (insert "[" c "] " tg (make-string
9935 (- fwidth 4 (length tg)) ?\ ))
9936 (when (= (setq cnt (1+ cnt)) ncol)
9937 (insert "\n")
9938 (if ingroup (insert " "))
9939 (setq cnt 0)))))
9940 (insert "\n")
9941 (goto-char (point-min))
9942 (if (not expert) (org-fit-window-to-buffer))
9943 (message "[a-z..]:Set [SPC]:clear")
9944 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9945 (cond
9946 ((or (= c ?\C-g)
9947 (and (= c ?q) (not (rassoc c fulltable))))
9948 (setq quit-flag t))
9949 ((= c ?\ ) nil)
9950 ((setq e (rassoc c fulltable) tg (car e))
9952 (t (setq quit-flag t)))))))
9954 (defun org-entry-is-todo-p ()
9955 (member (org-get-todo-state) org-not-done-keywords))
9957 (defun org-entry-is-done-p ()
9958 (member (org-get-todo-state) org-done-keywords))
9960 (defun org-get-todo-state ()
9961 (save-excursion
9962 (org-back-to-heading t)
9963 (and (looking-at org-todo-line-regexp)
9964 (match-end 2)
9965 (match-string 2))))
9967 (defun org-at-date-range-p (&optional inactive-ok)
9968 "Is the cursor inside a date range?"
9969 (interactive)
9970 (save-excursion
9971 (catch 'exit
9972 (let ((pos (point)))
9973 (skip-chars-backward "^[<\r\n")
9974 (skip-chars-backward "<[")
9975 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9976 (>= (match-end 0) pos)
9977 (throw 'exit t))
9978 (skip-chars-backward "^<[\r\n")
9979 (skip-chars-backward "<[")
9980 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9981 (>= (match-end 0) pos)
9982 (throw 'exit t)))
9983 nil)))
9985 (defun org-get-repeat ()
9986 "Check if there is a deadline/schedule with repeater in this entry."
9987 (save-match-data
9988 (save-excursion
9989 (org-back-to-heading t)
9990 (if (re-search-forward
9991 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9992 (match-string 1)))))
9994 (defvar org-last-changed-timestamp)
9995 (defvar org-last-inserted-timestamp)
9996 (defvar org-log-post-message)
9997 (defvar org-log-note-purpose)
9998 (defvar org-log-note-how)
9999 (defvar org-log-note-extra)
10000 (defun org-auto-repeat-maybe (done-word)
10001 "Check if the current headline contains a repeated deadline/schedule.
10002 If yes, set TODO state back to what it was and change the base date
10003 of repeating deadline/scheduled time stamps to new date.
10004 This function is run automatically after each state change to a DONE state."
10005 ;; last-state is dynamically scoped into this function
10006 (let* ((repeat (org-get-repeat))
10007 (aa (assoc last-state org-todo-kwd-alist))
10008 (interpret (nth 1 aa))
10009 (head (nth 2 aa))
10010 (whata '(("d" . day) ("m" . month) ("y" . year)))
10011 (msg "Entry repeats: ")
10012 (org-log-done nil)
10013 (org-todo-log-states nil)
10014 (nshiftmax 10) (nshift 0)
10015 re type n what ts time)
10016 (when repeat
10017 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10018 (org-todo (if (eq interpret 'type) last-state head))
10019 (org-entry-put nil "LAST_REPEAT" (format-time-string
10020 (org-time-stamp-format t t)))
10021 (when org-log-repeat
10022 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10023 (memq 'org-add-log-note post-command-hook))
10024 ;; OK, we are already setup for some record
10025 (if (eq org-log-repeat 'note)
10026 ;; make sure we take a note, not only a time stamp
10027 (setq org-log-note-how 'note))
10028 ;; Set up for taking a record
10029 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10030 last-state
10031 'findpos org-log-repeat)))
10032 (org-back-to-heading t)
10033 (org-add-planning-info nil nil 'closed)
10034 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10035 org-deadline-time-regexp "\\)\\|\\("
10036 org-ts-regexp "\\)"))
10037 (while (re-search-forward
10038 re (save-excursion (outline-next-heading) (point)) t)
10039 (setq type (if (match-end 1) org-scheduled-string
10040 (if (match-end 3) org-deadline-string "Plain:"))
10041 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10042 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10043 (setq n (string-to-number (match-string 2 ts))
10044 what (match-string 3 ts))
10045 (if (equal what "w") (setq n (* n 7) what "d"))
10046 ;; Preparation, see if we need to modify the start date for the change
10047 (when (match-end 1)
10048 (setq time (save-match-data (org-time-string-to-time ts)))
10049 (cond
10050 ((equal (match-string 1 ts) ".")
10051 ;; Shift starting date to today
10052 (org-timestamp-change
10053 (- (time-to-days (current-time)) (time-to-days time))
10054 'day))
10055 ((equal (match-string 1 ts) "+")
10056 (while (or (= nshift 0)
10057 (<= (time-to-days time) (time-to-days (current-time))))
10058 (when (= (incf nshift) nshiftmax)
10059 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10060 (error "Abort")))
10061 (org-timestamp-change n (cdr (assoc what whata)))
10062 (org-at-timestamp-p t)
10063 (setq ts (match-string 1))
10064 (setq time (save-match-data (org-time-string-to-time ts))))
10065 (org-timestamp-change (- n) (cdr (assoc what whata)))
10066 ;; rematch, so that we have everything in place for the real shift
10067 (org-at-timestamp-p t)
10068 (setq ts (match-string 1))
10069 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10070 (org-timestamp-change n (cdr (assoc what whata)))
10071 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10072 (setq org-log-post-message msg)
10073 (message "%s" msg))))
10075 (defun org-show-todo-tree (arg)
10076 "Make a compact tree which shows all headlines marked with TODO.
10077 The tree will show the lines where the regexp matches, and all higher
10078 headlines above the match.
10079 With a \\[universal-argument] prefix, prompt for a regexp to match.
10080 With a numeric prefix N, construct a sparse tree for the Nth element
10081 of `org-todo-keywords-1'."
10082 (interactive "P")
10083 (let ((case-fold-search nil)
10084 (kwd-re
10085 (cond ((null arg) org-not-done-regexp)
10086 ((equal arg '(4))
10087 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10088 (mapcar 'list org-todo-keywords-1))))
10089 (concat "\\("
10090 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10091 "\\)\\>")))
10092 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10093 (regexp-quote (nth (1- (prefix-numeric-value arg))
10094 org-todo-keywords-1)))
10095 (t (error "Invalid prefix argument: %s" arg)))))
10096 (message "%d TODO entries found"
10097 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10099 (defun org-deadline (&optional remove time)
10100 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10101 With argument REMOVE, remove any deadline from the item.
10102 When TIME is set, it should be an internal time specification, and the
10103 scheduling will use the corresponding date."
10104 (interactive "P")
10105 (if remove
10106 (progn
10107 (org-remove-timestamp-with-keyword org-deadline-string)
10108 (message "Item no longer has a deadline."))
10109 (if (org-get-repeat)
10110 (error "Cannot change deadline on task with repeater, please do that by hand")
10111 (org-add-planning-info 'deadline time 'closed)
10112 (message "Deadline on %s" org-last-inserted-timestamp))))
10114 (defun org-schedule (&optional remove time)
10115 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10116 With argument REMOVE, remove any scheduling date from the item.
10117 When TIME is set, it should be an internal time specification, and the
10118 scheduling will use the corresponding date."
10119 (interactive "P")
10120 (if remove
10121 (progn
10122 (org-remove-timestamp-with-keyword org-scheduled-string)
10123 (message "Item is no longer scheduled."))
10124 (if (org-get-repeat)
10125 (error "Cannot reschedule task with repeater, please do that by hand")
10126 (org-add-planning-info 'scheduled time 'closed)
10127 (message "Scheduled to %s" org-last-inserted-timestamp))))
10129 (defun org-get-scheduled-time (pom &optional inherit)
10130 "Get the scheduled time as a time tuple, of a format suitable
10131 for calling org-schedule with, or if there is no scheduling,
10132 returns nil."
10133 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10134 (when time
10135 (apply 'encode-time (org-parse-time-string time)))))
10137 (defun org-get-deadline-time (pom &optional inherit)
10138 "Get the deadine as a time tuple, of a format suitable for
10139 calling org-deadlin with, or if there is no scheduling, returns
10140 nil."
10141 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10142 (when time
10143 (apply 'encode-time (org-parse-time-string time)))))
10145 (defun org-remove-timestamp-with-keyword (keyword)
10146 "Remove all time stamps with KEYWORD in the current entry."
10147 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10148 beg)
10149 (save-excursion
10150 (org-back-to-heading t)
10151 (setq beg (point))
10152 (outline-next-heading)
10153 (while (re-search-backward re beg t)
10154 (replace-match "")
10155 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10156 (equal (char-before) ?\ ))
10157 (backward-delete-char 1)
10158 (if (string-match "^[ \t]*$" (buffer-substring
10159 (point-at-bol) (point-at-eol)))
10160 (delete-region (point-at-bol)
10161 (min (point-max) (1+ (point-at-eol))))))))))
10163 (defun org-add-planning-info (what &optional time &rest remove)
10164 "Insert new timestamp with keyword in the line directly after the headline.
10165 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10166 If non is given, the user is prompted for a date.
10167 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10168 be removed."
10169 (interactive)
10170 (let (org-time-was-given org-end-time-was-given ts
10171 end default-time default-input)
10173 (catch 'exit
10174 (when (and (not time) (memq what '(scheduled deadline)))
10175 ;; Try to get a default date/time from existing timestamp
10176 (save-excursion
10177 (org-back-to-heading t)
10178 (setq end (save-excursion (outline-next-heading) (point)))
10179 (when (re-search-forward (if (eq what 'scheduled)
10180 org-scheduled-time-regexp
10181 org-deadline-time-regexp)
10182 end t)
10183 (setq ts (match-string 1)
10184 default-time
10185 (apply 'encode-time (org-parse-time-string ts))
10186 default-input (and ts (org-get-compact-tod ts))))))
10187 (when what
10188 ;; If necessary, get the time from the user
10189 (setq time (or time (org-read-date nil 'to-time nil nil
10190 default-time default-input))))
10192 (when (and org-insert-labeled-timestamps-at-point
10193 (member what '(scheduled deadline)))
10194 (insert
10195 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10196 (org-insert-time-stamp time org-time-was-given
10197 nil nil nil (list org-end-time-was-given))
10198 (setq what nil))
10199 (save-excursion
10200 (save-restriction
10201 (let (col list elt ts buffer-invisibility-spec)
10202 (org-back-to-heading t)
10203 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10204 (goto-char (match-end 1))
10205 (setq col (current-column))
10206 (goto-char (match-end 0))
10207 (if (eobp) (insert "\n") (forward-char 1))
10208 (when (and (not what)
10209 (not (looking-at
10210 (concat "[ \t]*"
10211 org-keyword-time-not-clock-regexp))))
10212 ;; Nothing to add, nothing to remove...... :-)
10213 (throw 'exit nil))
10214 (if (and (not (looking-at outline-regexp))
10215 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10216 "[^\r\n]*"))
10217 (not (equal (match-string 1) org-clock-string)))
10218 (narrow-to-region (match-beginning 0) (match-end 0))
10219 (insert-before-markers "\n")
10220 (backward-char 1)
10221 (narrow-to-region (point) (point))
10222 (and org-adapt-indentation (org-indent-to-column col)))
10223 ;; Check if we have to remove something.
10224 (setq list (cons what remove))
10225 (while list
10226 (setq elt (pop list))
10227 (goto-char (point-min))
10228 (when (or (and (eq elt 'scheduled)
10229 (re-search-forward org-scheduled-time-regexp nil t))
10230 (and (eq elt 'deadline)
10231 (re-search-forward org-deadline-time-regexp nil t))
10232 (and (eq elt 'closed)
10233 (re-search-forward org-closed-time-regexp nil t)))
10234 (replace-match "")
10235 (if (looking-at "--+<[^>]+>") (replace-match ""))
10236 (skip-chars-backward " ")
10237 (if (looking-at " +") (replace-match ""))))
10238 (goto-char (point-max))
10239 (when what
10240 (insert
10241 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10242 (cond ((eq what 'scheduled) org-scheduled-string)
10243 ((eq what 'deadline) org-deadline-string)
10244 ((eq what 'closed) org-closed-string))
10245 " ")
10246 (setq ts (org-insert-time-stamp
10247 time
10248 (or org-time-was-given
10249 (and (eq what 'closed) org-log-done-with-time))
10250 (eq what 'closed)
10251 nil nil (list org-end-time-was-given)))
10252 (end-of-line 1))
10253 (goto-char (point-min))
10254 (widen)
10255 (if (and (looking-at "[ \t]+\n")
10256 (equal (char-before) ?\n))
10257 (delete-region (1- (point)) (point-at-eol)))
10258 ts))))))
10260 (defvar org-log-note-marker (make-marker))
10261 (defvar org-log-note-purpose nil)
10262 (defvar org-log-note-state nil)
10263 (defvar org-log-note-previous-state nil)
10264 (defvar org-log-note-how nil)
10265 (defvar org-log-note-extra nil)
10266 (defvar org-log-note-window-configuration nil)
10267 (defvar org-log-note-return-to (make-marker))
10268 (defvar org-log-post-message nil
10269 "Message to be displayed after a log note has been stored.
10270 The auto-repeater uses this.")
10272 (defun org-add-note ()
10273 "Add a note to the current entry.
10274 This is done in the same way as adding a state change note."
10275 (interactive)
10276 (org-add-log-setup 'note nil nil 'findpos nil))
10278 (defvar org-property-end-re)
10279 (defun org-add-log-setup (&optional purpose state prev-state
10280 findpos how &optional extra)
10281 "Set up the post command hook to take a note.
10282 If this is about to TODO state change, the new state is expected in STATE.
10283 When FINDPOS is non-nil, find the correct position for the note in
10284 the current entry. If not, assume that it can be inserted at point.
10285 HOW is an indicator what kind of note should be created.
10286 EXTRA is additional text that will be inserted into the notes buffer."
10287 (let* ((org-log-into-drawer (org-log-into-drawer))
10288 (drawer (cond ((stringp org-log-into-drawer)
10289 org-log-into-drawer)
10290 (org-log-into-drawer "LOGBOOK")
10291 (t nil))))
10292 (save-restriction
10293 (save-excursion
10294 (when findpos
10295 (org-back-to-heading t)
10296 (narrow-to-region (point) (save-excursion
10297 (outline-next-heading) (point)))
10298 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10299 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10300 "[^\r\n]*\\)?"))
10301 (goto-char (match-end 0))
10302 (cond
10303 (drawer
10304 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10305 nil t)
10306 (progn
10307 (goto-char (match-end 0))
10308 (or org-log-states-order-reversed
10309 (and (re-search-forward org-property-end-re nil t)
10310 (goto-char (1- (match-beginning 0))))))
10311 (insert "\n:" drawer ":\n:END:")
10312 (beginning-of-line 0)
10313 (org-indent-line-function)
10314 (beginning-of-line 2)
10315 (org-indent-line-function)
10316 (end-of-line 0)))
10317 ((and org-log-state-notes-insert-after-drawers
10318 (save-excursion
10319 (forward-line) (looking-at org-drawer-regexp)))
10320 (forward-line)
10321 (while (looking-at org-drawer-regexp)
10322 (goto-char (match-end 0))
10323 (re-search-forward org-property-end-re (point-max) t)
10324 (forward-line))
10325 (forward-line -1)))
10326 (unless org-log-states-order-reversed
10327 (and (= (char-after) ?\n) (forward-char 1))
10328 (org-skip-over-state-notes)
10329 (skip-chars-backward " \t\n\r")))
10330 (move-marker org-log-note-marker (point))
10331 (setq org-log-note-purpose purpose
10332 org-log-note-state state
10333 org-log-note-previous-state prev-state
10334 org-log-note-how how
10335 org-log-note-extra extra)
10336 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10338 (defun org-skip-over-state-notes ()
10339 "Skip past the list of State notes in an entry."
10340 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10341 (while (looking-at "[ \t]*- State")
10342 (condition-case nil
10343 (org-next-item)
10344 (error (org-end-of-item)))))
10346 (defun org-add-log-note (&optional purpose)
10347 "Pop up a window for taking a note, and add this note later at point."
10348 (remove-hook 'post-command-hook 'org-add-log-note)
10349 (setq org-log-note-window-configuration (current-window-configuration))
10350 (delete-other-windows)
10351 (move-marker org-log-note-return-to (point))
10352 (switch-to-buffer (marker-buffer org-log-note-marker))
10353 (goto-char org-log-note-marker)
10354 (org-switch-to-buffer-other-window "*Org Note*")
10355 (erase-buffer)
10356 (if (memq org-log-note-how '(time state))
10357 (let (current-prefix-arg) (org-store-log-note))
10358 (let ((org-inhibit-startup t)) (org-mode))
10359 (insert (format "# Insert note for %s.
10360 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10361 (cond
10362 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10363 ((eq org-log-note-purpose 'done) "closed todo item")
10364 ((eq org-log-note-purpose 'state)
10365 (format "state change from \"%s\" to \"%s\""
10366 (or org-log-note-previous-state "")
10367 (or org-log-note-state "")))
10368 ((eq org-log-note-purpose 'note)
10369 "this entry")
10370 (t (error "This should not happen")))))
10371 (if org-log-note-extra (insert org-log-note-extra))
10372 (org-set-local 'org-finish-function 'org-store-log-note)))
10374 (defvar org-note-abort nil) ; dynamically scoped
10375 (defun org-store-log-note ()
10376 "Finish taking a log note, and insert it to where it belongs."
10377 (let ((txt (buffer-string))
10378 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10379 lines ind)
10380 (kill-buffer (current-buffer))
10381 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10382 (setq txt (replace-match "" t t txt)))
10383 (if (string-match "\\s-+\\'" txt)
10384 (setq txt (replace-match "" t t txt)))
10385 (setq lines (org-split-string txt "\n"))
10386 (when (and note (string-match "\\S-" note))
10387 (setq note
10388 (org-replace-escapes
10389 note
10390 (list (cons "%u" (user-login-name))
10391 (cons "%U" user-full-name)
10392 (cons "%t" (format-time-string
10393 (org-time-stamp-format 'long 'inactive)
10394 (current-time)))
10395 (cons "%s" (if org-log-note-state
10396 (concat "\"" org-log-note-state "\"")
10397 ""))
10398 (cons "%S" (if org-log-note-previous-state
10399 (concat "\"" org-log-note-previous-state "\"")
10400 "\"\"")))))
10401 (if lines (setq note (concat note " \\\\")))
10402 (push note lines))
10403 (when (or current-prefix-arg org-note-abort)
10404 (when org-log-into-drawer
10405 (org-remove-empty-drawer-at
10406 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10407 org-log-note-marker))
10408 (setq lines nil))
10409 (when lines
10410 (save-excursion
10411 (set-buffer (marker-buffer org-log-note-marker))
10412 (save-excursion
10413 (goto-char org-log-note-marker)
10414 (move-marker org-log-note-marker nil)
10415 (end-of-line 1)
10416 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10417 (insert "- " (pop lines))
10418 (org-indent-line-function)
10419 (beginning-of-line 1)
10420 (looking-at "[ \t]*")
10421 (setq ind (concat (match-string 0) " "))
10422 (end-of-line 1)
10423 (while lines (insert "\n" ind (pop lines)))
10424 (message "Note stored")
10425 (org-back-to-heading t)
10426 (org-cycle-hide-drawers 'children)))))
10427 (set-window-configuration org-log-note-window-configuration)
10428 (with-current-buffer (marker-buffer org-log-note-return-to)
10429 (goto-char org-log-note-return-to))
10430 (move-marker org-log-note-return-to nil)
10431 (and org-log-post-message (message "%s" org-log-post-message)))
10433 (defun org-remove-empty-drawer-at (drawer pos)
10434 "Remove an emptyr DARWER drawer at position POS.
10435 POS may also be a marker."
10436 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10437 (save-excursion
10438 (save-restriction
10439 (widen)
10440 (goto-char pos)
10441 (if (org-in-regexp
10442 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10443 (replace-match ""))))))
10445 (defun org-sparse-tree (&optional arg)
10446 "Create a sparse tree, prompt for the details.
10447 This command can create sparse trees. You first need to select the type
10448 of match used to create the tree:
10450 t Show entries with a specific TODO keyword.
10451 m Show entries selected by a tags/property match.
10452 p Enter a property name and its value (both with completion on existing
10453 names/values) and show entries with that property.
10454 r Show entries matching a regular expression.
10455 d Show deadlines due within `org-deadline-warning-days'.
10456 b Show deadlines and scheduled items before a date.
10457 a Show deadlines and scheduled items after a date."
10458 (interactive "P")
10459 (let (ans kwd value)
10460 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10461 (setq ans (read-char-exclusive))
10462 (cond
10463 ((equal ans ?d)
10464 (call-interactively 'org-check-deadlines))
10465 ((equal ans ?b)
10466 (call-interactively 'org-check-before-date))
10467 ((equal ans ?a)
10468 (call-interactively 'org-check-after-date))
10469 ((equal ans ?t)
10470 (org-show-todo-tree '(4)))
10471 ((member ans '(?T ?m))
10472 (call-interactively 'org-match-sparse-tree))
10473 ((member ans '(?p ?P))
10474 (setq kwd (org-icompleting-read "Property: "
10475 (mapcar 'list (org-buffer-property-keys))))
10476 (setq value (org-icompleting-read "Value: "
10477 (mapcar 'list (org-property-values kwd))))
10478 (unless (string-match "\\`{.*}\\'" value)
10479 (setq value (concat "\"" value "\"")))
10480 (org-match-sparse-tree arg (concat kwd "=" value)))
10481 ((member ans '(?r ?R ?/))
10482 (call-interactively 'org-occur))
10483 (t (error "No such sparse tree command \"%c\"" ans)))))
10485 (defvar org-occur-highlights nil
10486 "List of overlays used for occur matches.")
10487 (make-variable-buffer-local 'org-occur-highlights)
10488 (defvar org-occur-parameters nil
10489 "Parameters of the active org-occur calls.
10490 This is a list, each call to org-occur pushes as cons cell,
10491 containing the regular expression and the callback, onto the list.
10492 The list can contain several entries if `org-occur' has been called
10493 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10494 will only contain one set of parameters. When the highlights are
10495 removed (for example with `C-c C-c', or with the next edit (depending
10496 on `org-remove-highlights-with-change'), this variable is emptied
10497 as well.")
10498 (make-variable-buffer-local 'org-occur-parameters)
10500 (defun org-occur (regexp &optional keep-previous callback)
10501 "Make a compact tree which shows all matches of REGEXP.
10502 The tree will show the lines where the regexp matches, and all higher
10503 headlines above the match. It will also show the heading after the match,
10504 to make sure editing the matching entry is easy.
10505 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10506 call to `org-occur' will be kept, to allow stacking of calls to this
10507 command.
10508 If CALLBACK is non-nil, it is a function which is called to confirm
10509 that the match should indeed be shown."
10510 (interactive "sRegexp: \nP")
10511 (when (equal regexp "")
10512 (error "Regexp cannot be empty"))
10513 (unless keep-previous
10514 (org-remove-occur-highlights nil nil t))
10515 (push (cons regexp callback) org-occur-parameters)
10516 (let ((cnt 0))
10517 (save-excursion
10518 (goto-char (point-min))
10519 (if (or (not keep-previous) ; do not want to keep
10520 (not org-occur-highlights)) ; no previous matches
10521 ;; hide everything
10522 (org-overview))
10523 (while (re-search-forward regexp nil t)
10524 (when (or (not callback)
10525 (save-match-data (funcall callback)))
10526 (setq cnt (1+ cnt))
10527 (when org-highlight-sparse-tree-matches
10528 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10529 (org-show-context 'occur-tree))))
10530 (when org-remove-highlights-with-change
10531 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10532 nil 'local))
10533 (unless org-sparse-tree-open-archived-trees
10534 (org-hide-archived-subtrees (point-min) (point-max)))
10535 (run-hooks 'org-occur-hook)
10536 (if (interactive-p)
10537 (message "%d match(es) for regexp %s" cnt regexp))
10538 cnt))
10540 (defun org-show-context (&optional key)
10541 "Make sure point and context and visible.
10542 How much context is shown depends upon the variables
10543 `org-show-hierarchy-above', `org-show-following-heading'. and
10544 `org-show-siblings'."
10545 (let ((heading-p (org-on-heading-p t))
10546 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10547 (following-p (org-get-alist-option org-show-following-heading key))
10548 (entry-p (org-get-alist-option org-show-entry-below key))
10549 (siblings-p (org-get-alist-option org-show-siblings key)))
10550 (catch 'exit
10551 ;; Show heading or entry text
10552 (if (and heading-p (not entry-p))
10553 (org-flag-heading nil) ; only show the heading
10554 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10555 (org-show-hidden-entry))) ; show entire entry
10556 (when following-p
10557 ;; Show next sibling, or heading below text
10558 (save-excursion
10559 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10560 (org-flag-heading nil))))
10561 (when siblings-p (org-show-siblings))
10562 (when hierarchy-p
10563 ;; show all higher headings, possibly with siblings
10564 (save-excursion
10565 (while (and (condition-case nil
10566 (progn (org-up-heading-all 1) t)
10567 (error nil))
10568 (not (bobp)))
10569 (org-flag-heading nil)
10570 (when siblings-p (org-show-siblings))))))))
10572 (defun org-reveal (&optional siblings)
10573 "Show current entry, hierarchy above it, and the following headline.
10574 This can be used to show a consistent set of context around locations
10575 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10576 not t for the search context.
10578 With optional argument SIBLINGS, on each level of the hierarchy all
10579 siblings are shown. This repairs the tree structure to what it would
10580 look like when opened with hierarchical calls to `org-cycle'."
10581 (interactive "P")
10582 (let ((org-show-hierarchy-above t)
10583 (org-show-following-heading t)
10584 (org-show-siblings (if siblings t org-show-siblings)))
10585 (org-show-context nil)))
10587 (defun org-highlight-new-match (beg end)
10588 "Highlight from BEG to END and mark the highlight is an occur headline."
10589 (let ((ov (org-make-overlay beg end)))
10590 (org-overlay-put ov 'face 'secondary-selection)
10591 (push ov org-occur-highlights)))
10593 (defun org-remove-occur-highlights (&optional beg end noremove)
10594 "Remove the occur highlights from the buffer.
10595 BEG and END are ignored. If NOREMOVE is nil, remove this function
10596 from the `before-change-functions' in the current buffer."
10597 (interactive)
10598 (unless org-inhibit-highlight-removal
10599 (mapc 'org-delete-overlay org-occur-highlights)
10600 (setq org-occur-highlights nil)
10601 (setq org-occur-parameters nil)
10602 (unless noremove
10603 (remove-hook 'before-change-functions
10604 'org-remove-occur-highlights 'local))))
10606 ;;;; Priorities
10608 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10609 "Regular expression matching the priority indicator.")
10611 (defvar org-remove-priority-next-time nil)
10613 (defun org-priority-up ()
10614 "Increase the priority of the current item."
10615 (interactive)
10616 (org-priority 'up))
10618 (defun org-priority-down ()
10619 "Decrease the priority of the current item."
10620 (interactive)
10621 (org-priority 'down))
10623 (defun org-priority (&optional action)
10624 "Change the priority of an item by ARG.
10625 ACTION can be `set', `up', `down', or a character."
10626 (interactive)
10627 (unless org-enable-priority-commands
10628 (error "Priority commands are disabled"))
10629 (setq action (or action 'set))
10630 (let (current new news have remove)
10631 (save-excursion
10632 (org-back-to-heading t)
10633 (if (looking-at org-priority-regexp)
10634 (setq current (string-to-char (match-string 2))
10635 have t)
10636 (setq current org-default-priority))
10637 (cond
10638 ((or (eq action 'set)
10639 (if (featurep 'xemacs) (characterp action) (integerp action)))
10640 (if (not (eq action 'set))
10641 (setq new action)
10642 (message "Priority %c-%c, SPC to remove: "
10643 org-highest-priority org-lowest-priority)
10644 (setq new (read-char-exclusive)))
10645 (if (and (= (upcase org-highest-priority) org-highest-priority)
10646 (= (upcase org-lowest-priority) org-lowest-priority))
10647 (setq new (upcase new)))
10648 (cond ((equal new ?\ ) (setq remove t))
10649 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10650 (error "Priority must be between `%c' and `%c'"
10651 org-highest-priority org-lowest-priority))))
10652 ((eq action 'up)
10653 (if (and (not have) (eq last-command this-command))
10654 (setq new org-lowest-priority)
10655 (setq new (if (and org-priority-start-cycle-with-default (not have))
10656 org-default-priority (1- current)))))
10657 ((eq action 'down)
10658 (if (and (not have) (eq last-command this-command))
10659 (setq new org-highest-priority)
10660 (setq new (if (and org-priority-start-cycle-with-default (not have))
10661 org-default-priority (1+ current)))))
10662 (t (error "Invalid action")))
10663 (if (or (< (upcase new) org-highest-priority)
10664 (> (upcase new) org-lowest-priority))
10665 (setq remove t))
10666 (setq news (format "%c" new))
10667 (if have
10668 (if remove
10669 (replace-match "" t t nil 1)
10670 (replace-match news t t nil 2))
10671 (if remove
10672 (error "No priority cookie found in line")
10673 (let ((case-fold-search nil))
10674 (looking-at org-todo-line-regexp))
10675 (if (match-end 2)
10676 (progn
10677 (goto-char (match-end 2))
10678 (insert " [#" news "]"))
10679 (goto-char (match-beginning 3))
10680 (insert "[#" news "] "))))
10681 (org-preserve-lc (org-set-tags nil 'align)))
10682 (if remove
10683 (message "Priority removed")
10684 (message "Priority of current item set to %s" news))))
10686 (defun org-get-priority (s)
10687 "Find priority cookie and return priority."
10688 (save-match-data
10689 (if (not (string-match org-priority-regexp s))
10690 (* 1000 (- org-lowest-priority org-default-priority))
10691 (* 1000 (- org-lowest-priority
10692 (string-to-char (match-string 2 s)))))))
10694 ;;;; Tags
10696 (defvar org-agenda-archives-mode)
10697 (defvar org-map-continue-from nil
10698 "Position from where mapping should continue.
10699 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10701 (defvar org-scanner-tags nil
10702 "The current tag list while the tags scanner is running.")
10703 (defvar org-trust-scanner-tags nil
10704 "Should `org-get-tags-at' use the tags fro the scanner.
10705 This is for internal dynamical scoping only.
10706 When this is non-nil, the function `org-get-tags-at' will return the value
10707 of `org-scanner-tags' instead of building the list by itself. This
10708 can lead to large speed-ups when the tags scanner is used in a file with
10709 many entries, and when the list of tags is retrieved, for example to
10710 obtain a list of properties. Building the tags list for each entry in such
10711 a file becomes an N^2 operation - but with this variable set, it scales
10712 as N.")
10714 (defun org-scan-tags (action matcher &optional todo-only)
10715 "Scan headline tags with inheritance and produce output ACTION.
10717 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10718 or `agenda' to produce an entry list for an agenda view. It can also be
10719 a Lisp form or a function that should be called at each matched headline, in
10720 this case the return value is a list of all return values from these calls.
10722 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10723 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10724 only lines with a TODO keyword are included in the output."
10725 (require 'org-agenda)
10726 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10727 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10728 (org-re
10729 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10730 (props (list 'face 'default
10731 'done-face 'org-agenda-done
10732 'undone-face 'default
10733 'mouse-face 'highlight
10734 'org-not-done-regexp org-not-done-regexp
10735 'org-todo-regexp org-todo-regexp
10736 'keymap org-agenda-keymap
10737 'help-echo
10738 (format "mouse-2 or RET jump to org file %s"
10739 (abbreviate-file-name
10740 (or (buffer-file-name (buffer-base-buffer))
10741 (buffer-name (buffer-base-buffer)))))))
10742 (case-fold-search nil)
10743 (org-map-continue-from nil)
10744 lspos tags tags-list
10745 (tags-alist (list (cons 0 org-file-tags)))
10746 (llast 0) rtn rtn1 level category i txt
10747 todo marker entry priority)
10748 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10749 (setq action (list 'lambda nil action)))
10750 (save-excursion
10751 (goto-char (point-min))
10752 (when (eq action 'sparse-tree)
10753 (org-overview)
10754 (org-remove-occur-highlights))
10755 (while (re-search-forward re nil t)
10756 (catch :skip
10757 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10758 tags (if (match-end 4) (org-match-string-no-properties 4)))
10759 (goto-char (setq lspos (match-beginning 0)))
10760 (setq level (org-reduced-level (funcall outline-level))
10761 category (org-get-category))
10762 (setq i llast llast level)
10763 ;; remove tag lists from same and sublevels
10764 (while (>= i level)
10765 (when (setq entry (assoc i tags-alist))
10766 (setq tags-alist (delete entry tags-alist)))
10767 (setq i (1- i)))
10768 ;; add the next tags
10769 (when tags
10770 (setq tags (org-split-string tags ":")
10771 tags-alist
10772 (cons (cons level tags) tags-alist)))
10773 ;; compile tags for current headline
10774 (setq tags-list
10775 (if org-use-tag-inheritance
10776 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10777 tags)
10778 org-scanner-tags tags-list)
10779 (when org-use-tag-inheritance
10780 (setcdr (car tags-alist)
10781 (mapcar (lambda (x)
10782 (setq x (copy-sequence x))
10783 (org-add-prop-inherited x))
10784 (cdar tags-alist))))
10785 (when (and tags org-use-tag-inheritance
10786 (or (not (eq t org-use-tag-inheritance))
10787 org-tags-exclude-from-inheritance))
10788 ;; selective inheritance, remove uninherited ones
10789 (setcdr (car tags-alist)
10790 (org-remove-uniherited-tags (cdar tags-alist))))
10791 (when (and (or (not todo-only)
10792 (and (member todo org-not-done-keywords)
10793 (or (not org-agenda-tags-todo-honor-ignore-options)
10794 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10795 (let ((case-fold-search t)) (eval matcher))
10797 (not (member org-archive-tag tags-list))
10798 ;; we have an archive tag, should we use this anyway?
10799 (or (not org-agenda-skip-archived-trees)
10800 (and (eq action 'agenda) org-agenda-archives-mode))))
10801 (unless (eq action 'sparse-tree) (org-agenda-skip))
10803 ;; select this headline
10805 (cond
10806 ((eq action 'sparse-tree)
10807 (and org-highlight-sparse-tree-matches
10808 (org-get-heading) (match-end 0)
10809 (org-highlight-new-match
10810 (match-beginning 0) (match-beginning 1)))
10811 (org-show-context 'tags-tree))
10812 ((eq action 'agenda)
10813 (setq txt (org-format-agenda-item
10815 (concat
10816 (if (eq org-tags-match-list-sublevels 'indented)
10817 (make-string (1- level) ?.) "")
10818 (org-get-heading))
10819 category
10820 tags-list
10822 priority (org-get-priority txt))
10823 (goto-char lspos)
10824 (setq marker (org-agenda-new-marker))
10825 (org-add-props txt props
10826 'org-marker marker 'org-hd-marker marker 'org-category category
10827 'todo-state todo
10828 'priority priority 'type "tagsmatch")
10829 (push txt rtn))
10830 ((functionp action)
10831 (setq org-map-continue-from nil)
10832 (save-excursion
10833 (setq rtn1 (funcall action))
10834 (push rtn1 rtn)))
10835 (t (error "Invalid action")))
10837 ;; if we are to skip sublevels, jump to end of subtree
10838 (unless org-tags-match-list-sublevels
10839 (org-end-of-subtree t)
10840 (backward-char 1))))
10841 ;; Get the correct position from where to continue
10842 (if org-map-continue-from
10843 (goto-char org-map-continue-from)
10844 (and (= (point) lspos) (end-of-line 1)))))
10845 (when (and (eq action 'sparse-tree)
10846 (not org-sparse-tree-open-archived-trees))
10847 (org-hide-archived-subtrees (point-min) (point-max)))
10848 (nreverse rtn)))
10850 (defun org-remove-uniherited-tags (tags)
10851 "Remove all tags that are not inherited from the list TAGS."
10852 (cond
10853 ((eq org-use-tag-inheritance t)
10854 (if org-tags-exclude-from-inheritance
10855 (org-delete-all org-tags-exclude-from-inheritance tags)
10856 tags))
10857 ((not org-use-tag-inheritance) nil)
10858 ((stringp org-use-tag-inheritance)
10859 (delq nil (mapcar
10860 (lambda (x)
10861 (if (and (string-match org-use-tag-inheritance x)
10862 (not (member x org-tags-exclude-from-inheritance)))
10863 x nil))
10864 tags)))
10865 ((listp org-use-tag-inheritance)
10866 (delq nil (mapcar
10867 (lambda (x)
10868 (if (member x org-use-tag-inheritance) x nil))
10869 tags)))))
10871 (defvar todo-only) ;; dynamically scoped
10873 (defun org-match-sparse-tree (&optional todo-only match)
10874 "Create a sparse tree according to tags string MATCH.
10875 MATCH can contain positive and negative selection of tags, like
10876 \"+WORK+URGENT-WITHBOSS\".
10877 If optional argument TODO-ONLY is non-nil, only select lines that are
10878 also TODO lines."
10879 (interactive "P")
10880 (org-prepare-agenda-buffers (list (current-buffer)))
10881 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10883 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10885 (defvar org-cached-props nil)
10886 (defun org-cached-entry-get (pom property)
10887 (if (or (eq t org-use-property-inheritance)
10888 (and (stringp org-use-property-inheritance)
10889 (string-match org-use-property-inheritance property))
10890 (and (listp org-use-property-inheritance)
10891 (member property org-use-property-inheritance)))
10892 ;; Caching is not possible, check it directly
10893 (org-entry-get pom property 'inherit)
10894 ;; Get all properties, so that we can do complicated checks easily
10895 (cdr (assoc property (or org-cached-props
10896 (setq org-cached-props
10897 (org-entry-properties pom)))))))
10899 (defun org-global-tags-completion-table (&optional files)
10900 "Return the list of all tags in all agenda buffer/files."
10901 (save-excursion
10902 (org-uniquify
10903 (delq nil
10904 (apply 'append
10905 (mapcar
10906 (lambda (file)
10907 (set-buffer (find-file-noselect file))
10908 (append (org-get-buffer-tags)
10909 (mapcar (lambda (x) (if (stringp (car-safe x))
10910 (list (car-safe x)) nil))
10911 org-tag-alist)))
10912 (if (and files (car files))
10913 files
10914 (org-agenda-files))))))))
10916 (defun org-make-tags-matcher (match)
10917 "Create the TAGS//TODO matcher form for the selection string MATCH."
10918 ;; todo-only is scoped dynamically into this function, and the function
10919 ;; may change it if the matcher asks for it.
10920 (unless match
10921 ;; Get a new match request, with completion
10922 (let ((org-last-tags-completion-table
10923 (org-global-tags-completion-table)))
10924 (setq match (org-completing-read-no-i
10925 "Match: " 'org-tags-completion-function nil nil nil
10926 'org-tags-history))))
10928 ;; Parse the string and create a lisp form
10929 (let ((match0 match)
10930 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10931 minus tag mm
10932 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10933 orterms term orlist re-p str-p level-p level-op time-p
10934 prop-p pn pv po cat-p gv rest)
10935 (if (string-match "/+" match)
10936 ;; match contains also a todo-matching request
10937 (progn
10938 (setq tagsmatch (substring match 0 (match-beginning 0))
10939 todomatch (substring match (match-end 0)))
10940 (if (string-match "^!" todomatch)
10941 (setq todo-only t todomatch (substring todomatch 1)))
10942 (if (string-match "^\\s-*$" todomatch)
10943 (setq todomatch nil)))
10944 ;; only matching tags
10945 (setq tagsmatch match todomatch nil))
10947 ;; Make the tags matcher
10948 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10949 (setq tagsmatcher t)
10950 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10951 (while (setq term (pop orterms))
10952 (while (and (equal (substring term -1) "\\") orterms)
10953 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10954 (while (string-match re term)
10955 (setq rest (substring term (match-end 0))
10956 minus (and (match-end 1)
10957 (equal (match-string 1 term) "-"))
10958 tag (match-string 2 term)
10959 re-p (equal (string-to-char tag) ?{)
10960 level-p (match-end 4)
10961 prop-p (match-end 5)
10962 mm (cond
10963 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10964 (level-p
10965 (setq level-op (org-op-to-function (match-string 3 term)))
10966 `(,level-op level ,(string-to-number
10967 (match-string 4 term))))
10968 (prop-p
10969 (setq pn (match-string 5 term)
10970 po (match-string 6 term)
10971 pv (match-string 7 term)
10972 cat-p (equal pn "CATEGORY")
10973 re-p (equal (string-to-char pv) ?{)
10974 str-p (equal (string-to-char pv) ?\")
10975 time-p (save-match-data
10976 (string-match "^\"[[<].*[]>]\"$" pv))
10977 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10978 (if time-p (setq pv (org-matcher-time pv)))
10979 (setq po (org-op-to-function po (if time-p 'time str-p)))
10980 (cond
10981 ((equal pn "CATEGORY")
10982 (setq gv '(get-text-property (point) 'org-category)))
10983 ((equal pn "TODO")
10984 (setq gv 'todo))
10986 (setq gv `(org-cached-entry-get nil ,pn))))
10987 (if re-p
10988 (if (eq po 'org<>)
10989 `(not (string-match ,pv (or ,gv "")))
10990 `(string-match ,pv (or ,gv "")))
10991 (if str-p
10992 `(,po (or ,gv "") ,pv)
10993 `(,po (string-to-number (or ,gv ""))
10994 ,(string-to-number pv) ))))
10995 (t `(member ,tag tags-list)))
10996 mm (if minus (list 'not mm) mm)
10997 term rest)
10998 (push mm tagsmatcher))
10999 (push (if (> (length tagsmatcher) 1)
11000 (cons 'and tagsmatcher)
11001 (car tagsmatcher))
11002 orlist)
11003 (setq tagsmatcher nil))
11004 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11005 (setq tagsmatcher
11006 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11007 ;; Make the todo matcher
11008 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11009 (setq todomatcher t)
11010 (setq orterms (org-split-string todomatch "|") orlist nil)
11011 (while (setq term (pop orterms))
11012 (while (string-match re term)
11013 (setq minus (and (match-end 1)
11014 (equal (match-string 1 term) "-"))
11015 kwd (match-string 2 term)
11016 re-p (equal (string-to-char kwd) ?{)
11017 term (substring term (match-end 0))
11018 mm (if re-p
11019 `(string-match ,(substring kwd 1 -1) todo)
11020 (list 'equal 'todo kwd))
11021 mm (if minus (list 'not mm) mm))
11022 (push mm todomatcher))
11023 (push (if (> (length todomatcher) 1)
11024 (cons 'and todomatcher)
11025 (car todomatcher))
11026 orlist)
11027 (setq todomatcher nil))
11028 (setq todomatcher (if (> (length orlist) 1)
11029 (cons 'or orlist) (car orlist))))
11031 ;; Return the string and lisp forms of the matcher
11032 (setq matcher (if todomatcher
11033 (list 'and tagsmatcher todomatcher)
11034 tagsmatcher))
11035 (cons match0 matcher)))
11037 (defun org-op-to-function (op &optional stringp)
11038 "Turn an operator into the appropriate function."
11039 (setq op
11040 (cond
11041 ((equal op "<" ) '(< string< org-time<))
11042 ((equal op ">" ) '(> org-string> org-time>))
11043 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11044 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11045 ((member op '("=" "==")) '(= string= org-time=))
11046 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11047 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11049 (defun org<> (a b) (not (= a b)))
11050 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11051 (defun org-string>= (a b) (not (string< a b)))
11052 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11053 (defun org-string<> (a b) (not (string= a b)))
11054 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11055 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11056 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11057 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11058 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11059 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11060 (defun org-2ft (s)
11061 "Convert S to a floating point time.
11062 If S is already a number, just return it. If it is a string, parse
11063 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11064 (cond
11065 ((numberp s) s)
11066 ((stringp s)
11067 (condition-case nil
11068 (float-time (apply 'encode-time (org-parse-time-string s)))
11069 (error 0.)))
11070 (t 0.)))
11072 (defun org-time-today ()
11073 "Time in seconds today at 0:00.
11074 Returns the float number of seconds since the beginning of the
11075 epoch to the beginning of today (00:00)."
11076 (float-time (apply 'encode-time
11077 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11079 (defun org-matcher-time (s)
11080 "Interpret a time comparison value."
11081 (save-match-data
11082 (cond
11083 ((string= s "<now>") (float-time))
11084 ((string= s "<today>") (org-time-today))
11085 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11086 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11087 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11088 (+ (org-time-today)
11089 (* (string-to-number (match-string 1 s))
11090 (cdr (assoc (match-string 2 s)
11091 '(("d" . 86400.0) ("w" . 604800.0)
11092 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11093 (t (org-2ft s)))))
11095 (defun org-match-any-p (re list)
11096 "Does re match any element of list?"
11097 (setq list (mapcar (lambda (x) (string-match re x)) list))
11098 (delq nil list))
11100 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11101 (defvar org-tags-overlay (org-make-overlay 1 1))
11102 (org-detach-overlay org-tags-overlay)
11104 (defun org-get-local-tags-at (&optional pos)
11105 "Get a list of tags defined in the current headline."
11106 (org-get-tags-at pos 'local))
11108 (defun org-get-local-tags ()
11109 "Get a list of tags defined in the current headline."
11110 (org-get-tags-at nil 'local))
11112 (defun org-get-tags-at (&optional pos local)
11113 "Get a list of all headline tags applicable at POS.
11114 POS defaults to point. If tags are inherited, the list contains
11115 the targets in the same sequence as the headlines appear, i.e.
11116 the tags of the current headline come last.
11117 When LOCAL is non-nil, only return tags from the current headline,
11118 ignore inherited ones."
11119 (interactive)
11120 (if (and org-trust-scanner-tags
11121 (or (not pos) (equal pos (point)))
11122 (not local))
11123 org-scanner-tags
11124 (let (tags ltags lastpos parent)
11125 (save-excursion
11126 (save-restriction
11127 (widen)
11128 (goto-char (or pos (point)))
11129 (save-match-data
11130 (catch 'done
11131 (condition-case nil
11132 (progn
11133 (org-back-to-heading t)
11134 (while (not (equal lastpos (point)))
11135 (setq lastpos (point))
11136 (when (looking-at
11137 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11138 (setq ltags (org-split-string
11139 (org-match-string-no-properties 1) ":"))
11140 (when parent
11141 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11142 (setq tags (append
11143 (if parent
11144 (org-remove-uniherited-tags ltags)
11145 ltags)
11146 tags)))
11147 (or org-use-tag-inheritance (throw 'done t))
11148 (if local (throw 'done t))
11149 (or (org-up-heading-safe) (error nil))
11150 (setq parent t)))
11151 (error nil)))))
11152 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11154 (defun org-add-prop-inherited (s)
11155 (add-text-properties 0 (length s) '(inherited t) s)
11158 (defun org-toggle-tag (tag &optional onoff)
11159 "Toggle the tag TAG for the current line.
11160 If ONOFF is `on' or `off', don't toggle but set to this state."
11161 (let (res current)
11162 (save-excursion
11163 (org-back-to-heading t)
11164 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11165 (point-at-eol) t)
11166 (progn
11167 (setq current (match-string 1))
11168 (replace-match ""))
11169 (setq current ""))
11170 (setq current (nreverse (org-split-string current ":")))
11171 (cond
11172 ((eq onoff 'on)
11173 (setq res t)
11174 (or (member tag current) (push tag current)))
11175 ((eq onoff 'off)
11176 (or (not (member tag current)) (setq current (delete tag current))))
11177 (t (if (member tag current)
11178 (setq current (delete tag current))
11179 (setq res t)
11180 (push tag current))))
11181 (end-of-line 1)
11182 (if current
11183 (progn
11184 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11185 (org-set-tags nil t))
11186 (delete-horizontal-space))
11187 (run-hooks 'org-after-tags-change-hook))
11188 res))
11190 (defun org-align-tags-here (to-col)
11191 ;; Assumes that this is a headline
11192 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11193 (beginning-of-line 1)
11194 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11195 (< pos (match-beginning 2)))
11196 (progn
11197 (setq tags-l (- (match-end 2) (match-beginning 2)))
11198 (goto-char (match-beginning 1))
11199 (insert " ")
11200 (delete-region (point) (1+ (match-beginning 2)))
11201 (setq ncol (max (1+ (current-column))
11202 (1+ col)
11203 (if (> to-col 0)
11204 to-col
11205 (- (abs to-col) tags-l))))
11206 (setq p (point))
11207 (insert (make-string (- ncol (current-column)) ?\ ))
11208 (setq ncol (current-column))
11209 (when indent-tabs-mode (tabify p (point-at-eol)))
11210 (org-move-to-column (min ncol col) t))
11211 (goto-char pos))))
11213 (defun org-set-tags-command (&optional arg just-align)
11214 "Call the set-tags command for the current entry."
11215 (interactive "P")
11216 (if (org-on-heading-p)
11217 (org-set-tags arg just-align)
11218 (save-excursion
11219 (org-back-to-heading t)
11220 (org-set-tags arg just-align))))
11222 (defun org-set-tags (&optional arg just-align)
11223 "Set the tags for the current headline.
11224 With prefix ARG, realign all tags in headings in the current buffer."
11225 (interactive "P")
11226 (let* ((re (concat "^" outline-regexp))
11227 (current (org-get-tags-string))
11228 (col (current-column))
11229 (org-setting-tags t)
11230 table current-tags inherited-tags ; computed below when needed
11231 tags p0 c0 c1 rpl)
11232 (if arg
11233 (save-excursion
11234 (goto-char (point-min))
11235 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11236 (while (re-search-forward re nil t)
11237 (org-set-tags nil t)
11238 (end-of-line 1)))
11239 (message "All tags realigned to column %d" org-tags-column))
11240 (if just-align
11241 (setq tags current)
11242 ;; Get a new set of tags from the user
11243 (save-excursion
11244 (setq table (append org-tag-persistent-alist
11245 (or org-tag-alist (org-get-buffer-tags)))
11246 org-last-tags-completion-table table
11247 current-tags (org-split-string current ":")
11248 inherited-tags (nreverse
11249 (nthcdr (length current-tags)
11250 (nreverse (org-get-tags-at))))
11251 tags
11252 (if (or (eq t org-use-fast-tag-selection)
11253 (and org-use-fast-tag-selection
11254 (delq nil (mapcar 'cdr table))))
11255 (org-fast-tag-selection
11256 current-tags inherited-tags table
11257 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11258 (let ((org-add-colon-after-tag-completion t))
11259 (org-trim
11260 (org-without-partial-completion
11261 (org-icompleting-read "Tags: " 'org-tags-completion-function
11262 nil nil current 'org-tags-history)))))))
11263 (while (string-match "[-+&]+" tags)
11264 ;; No boolean logic, just a list
11265 (setq tags (replace-match ":" t t tags))))
11267 (if org-tags-sort-function
11268 (setq tags (mapconcat 'identity
11269 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11270 org-tags-sort-function) ":")))
11272 (if (string-match "\\`[\t ]*\\'" tags)
11273 (setq tags "")
11274 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11275 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11277 ;; Insert new tags at the correct column
11278 (beginning-of-line 1)
11279 (cond
11280 ((and (equal current "") (equal tags "")))
11281 ((re-search-forward
11282 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11283 (point-at-eol) t)
11284 (if (equal tags "")
11285 (setq rpl "")
11286 (goto-char (match-beginning 0))
11287 (setq c0 (current-column) p0 (point)
11288 c1 (max (1+ c0) (if (> org-tags-column 0)
11289 org-tags-column
11290 (- (- org-tags-column) (length tags))))
11291 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11292 (replace-match rpl t t)
11293 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11294 tags)
11295 (t (error "Tags alignment failed")))
11296 (org-move-to-column col)
11297 (unless just-align
11298 (run-hooks 'org-after-tags-change-hook)))))
11300 (defun org-change-tag-in-region (beg end tag off)
11301 "Add or remove TAG for each entry in the region.
11302 This works in the agenda, and also in an org-mode buffer."
11303 (interactive
11304 (list (region-beginning) (region-end)
11305 (let ((org-last-tags-completion-table
11306 (if (org-mode-p)
11307 (org-get-buffer-tags)
11308 (org-global-tags-completion-table))))
11309 (org-icompleting-read
11310 "Tag: " 'org-tags-completion-function nil nil nil
11311 'org-tags-history))
11312 (progn
11313 (message "[s]et or [r]emove? ")
11314 (equal (read-char-exclusive) ?r))))
11315 (if (fboundp 'deactivate-mark) (deactivate-mark))
11316 (let ((agendap (equal major-mode 'org-agenda-mode))
11317 l1 l2 m buf pos newhead (cnt 0))
11318 (goto-char end)
11319 (setq l2 (1- (org-current-line)))
11320 (goto-char beg)
11321 (setq l1 (org-current-line))
11322 (loop for l from l1 to l2 do
11323 (org-goto-line l)
11324 (setq m (get-text-property (point) 'org-hd-marker))
11325 (when (or (and (org-mode-p) (org-on-heading-p))
11326 (and agendap m))
11327 (setq buf (if agendap (marker-buffer m) (current-buffer))
11328 pos (if agendap m (point)))
11329 (with-current-buffer buf
11330 (save-excursion
11331 (save-restriction
11332 (goto-char pos)
11333 (setq cnt (1+ cnt))
11334 (org-toggle-tag tag (if off 'off 'on))
11335 (setq newhead (org-get-heading)))))
11336 (and agendap (org-agenda-change-all-lines newhead m))))
11337 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11339 (defun org-tags-completion-function (string predicate &optional flag)
11340 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11341 (confirm (lambda (x) (stringp (car x)))))
11342 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11343 (setq s1 (match-string 1 string)
11344 s2 (match-string 2 string))
11345 (setq s1 "" s2 string))
11346 (cond
11347 ((eq flag nil)
11348 ;; try completion
11349 (setq rtn (try-completion s2 ctable confirm))
11350 (if (stringp rtn)
11351 (setq rtn
11352 (concat s1 s2 (substring rtn (length s2))
11353 (if (and org-add-colon-after-tag-completion
11354 (assoc rtn ctable))
11355 ":" ""))))
11356 rtn)
11357 ((eq flag t)
11358 ;; all-completions
11359 (all-completions s2 ctable confirm)
11361 ((eq flag 'lambda)
11362 ;; exact match?
11363 (assoc s2 ctable)))
11366 (defun org-fast-tag-insert (kwd tags face &optional end)
11367 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11368 (insert (format "%-12s" (concat kwd ":"))
11369 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11370 (or end "")))
11372 (defun org-fast-tag-show-exit (flag)
11373 (save-excursion
11374 (org-goto-line 3)
11375 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11376 (replace-match ""))
11377 (when flag
11378 (end-of-line 1)
11379 (org-move-to-column (- (window-width) 19) t)
11380 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11382 (defun org-set-current-tags-overlay (current prefix)
11383 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11384 (if (featurep 'xemacs)
11385 (org-overlay-display org-tags-overlay (concat prefix s)
11386 'secondary-selection)
11387 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11388 (org-overlay-display org-tags-overlay (concat prefix s)))))
11390 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11391 "Fast tag selection with single keys.
11392 CURRENT is the current list of tags in the headline, INHERITED is the
11393 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11394 possibly with grouping information. TODO-TABLE is a similar table with
11395 TODO keywords, should these have keys assigned to them.
11396 If the keys are nil, a-z are automatically assigned.
11397 Returns the new tags string, or nil to not change the current settings."
11398 (let* ((fulltable (append table todo-table))
11399 (maxlen (apply 'max (mapcar
11400 (lambda (x)
11401 (if (stringp (car x)) (string-width (car x)) 0))
11402 fulltable)))
11403 (buf (current-buffer))
11404 (expert (eq org-fast-tag-selection-single-key 'expert))
11405 (buffer-tags nil)
11406 (fwidth (+ maxlen 3 1 3))
11407 (ncol (/ (- (window-width) 4) fwidth))
11408 (i-face 'org-done)
11409 (c-face 'org-todo)
11410 tg cnt e c char c1 c2 ntable tbl rtn
11411 ov-start ov-end ov-prefix
11412 (exit-after-next org-fast-tag-selection-single-key)
11413 (done-keywords org-done-keywords)
11414 groups ingroup)
11415 (save-excursion
11416 (beginning-of-line 1)
11417 (if (looking-at
11418 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11419 (setq ov-start (match-beginning 1)
11420 ov-end (match-end 1)
11421 ov-prefix "")
11422 (setq ov-start (1- (point-at-eol))
11423 ov-end (1+ ov-start))
11424 (skip-chars-forward "^\n\r")
11425 (setq ov-prefix
11426 (concat
11427 (buffer-substring (1- (point)) (point))
11428 (if (> (current-column) org-tags-column)
11430 (make-string (- org-tags-column (current-column)) ?\ ))))))
11431 (org-move-overlay org-tags-overlay ov-start ov-end)
11432 (save-window-excursion
11433 (if expert
11434 (set-buffer (get-buffer-create " *Org tags*"))
11435 (delete-other-windows)
11436 (split-window-vertically)
11437 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11438 (erase-buffer)
11439 (org-set-local 'org-done-keywords done-keywords)
11440 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11441 (org-fast-tag-insert "Current" current c-face "\n\n")
11442 (org-fast-tag-show-exit exit-after-next)
11443 (org-set-current-tags-overlay current ov-prefix)
11444 (setq tbl fulltable char ?a cnt 0)
11445 (while (setq e (pop tbl))
11446 (cond
11447 ((equal e '(:startgroup))
11448 (push '() groups) (setq ingroup t)
11449 (when (not (= cnt 0))
11450 (setq cnt 0)
11451 (insert "\n"))
11452 (insert "{ "))
11453 ((equal e '(:endgroup))
11454 (setq ingroup nil cnt 0)
11455 (insert "}\n"))
11456 ((equal e '(:newline))
11457 (when (not (= cnt 0))
11458 (setq cnt 0)
11459 (insert "\n")
11460 (setq e (car tbl))
11461 (while (equal (car tbl) '(:newline))
11462 (insert "\n")
11463 (setq tbl (cdr tbl)))))
11465 (setq tg (copy-sequence (car e)) c2 nil)
11466 (if (cdr e)
11467 (setq c (cdr e))
11468 ;; automatically assign a character.
11469 (setq c1 (string-to-char
11470 (downcase (substring
11471 tg (if (= (string-to-char tg) ?@) 1 0)))))
11472 (if (or (rassoc c1 ntable) (rassoc c1 table))
11473 (while (or (rassoc char ntable) (rassoc char table))
11474 (setq char (1+ char)))
11475 (setq c2 c1))
11476 (setq c (or c2 char)))
11477 (if ingroup (push tg (car groups)))
11478 (setq tg (org-add-props tg nil 'face
11479 (cond
11480 ((not (assoc tg table))
11481 (org-get-todo-face tg))
11482 ((member tg current) c-face)
11483 ((member tg inherited) i-face)
11484 (t nil))))
11485 (if (and (= cnt 0) (not ingroup)) (insert " "))
11486 (insert "[" c "] " tg (make-string
11487 (- fwidth 4 (length tg)) ?\ ))
11488 (push (cons tg c) ntable)
11489 (when (= (setq cnt (1+ cnt)) ncol)
11490 (insert "\n")
11491 (if ingroup (insert " "))
11492 (setq cnt 0)))))
11493 (setq ntable (nreverse ntable))
11494 (insert "\n")
11495 (goto-char (point-min))
11496 (if (not expert) (org-fit-window-to-buffer))
11497 (setq rtn
11498 (catch 'exit
11499 (while t
11500 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11501 (if groups " [!] no groups" " [!]groups")
11502 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11503 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11504 (cond
11505 ((= c ?\r) (throw 'exit t))
11506 ((= c ?!)
11507 (setq groups (not groups))
11508 (goto-char (point-min))
11509 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11510 ((= c ?\C-c)
11511 (if (not expert)
11512 (org-fast-tag-show-exit
11513 (setq exit-after-next (not exit-after-next)))
11514 (setq expert nil)
11515 (delete-other-windows)
11516 (split-window-vertically)
11517 (org-switch-to-buffer-other-window " *Org tags*")
11518 (org-fit-window-to-buffer)))
11519 ((or (= c ?\C-g)
11520 (and (= c ?q) (not (rassoc c ntable))))
11521 (org-detach-overlay org-tags-overlay)
11522 (setq quit-flag t))
11523 ((= c ?\ )
11524 (setq current nil)
11525 (if exit-after-next (setq exit-after-next 'now)))
11526 ((= c ?\t)
11527 (condition-case nil
11528 (setq tg (org-icompleting-read
11529 "Tag: "
11530 (or buffer-tags
11531 (with-current-buffer buf
11532 (org-get-buffer-tags)))))
11533 (quit (setq tg "")))
11534 (when (string-match "\\S-" tg)
11535 (add-to-list 'buffer-tags (list tg))
11536 (if (member tg current)
11537 (setq current (delete tg current))
11538 (push tg current)))
11539 (if exit-after-next (setq exit-after-next 'now)))
11540 ((setq e (rassoc c todo-table) tg (car e))
11541 (with-current-buffer buf
11542 (save-excursion (org-todo tg)))
11543 (if exit-after-next (setq exit-after-next 'now)))
11544 ((setq e (rassoc c ntable) tg (car e))
11545 (if (member tg current)
11546 (setq current (delete tg current))
11547 (loop for g in groups do
11548 (if (member tg g)
11549 (mapc (lambda (x)
11550 (setq current (delete x current)))
11551 g)))
11552 (push tg current))
11553 (if exit-after-next (setq exit-after-next 'now))))
11555 ;; Create a sorted list
11556 (setq current
11557 (sort current
11558 (lambda (a b)
11559 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11560 (if (eq exit-after-next 'now) (throw 'exit t))
11561 (goto-char (point-min))
11562 (beginning-of-line 2)
11563 (delete-region (point) (point-at-eol))
11564 (org-fast-tag-insert "Current" current c-face)
11565 (org-set-current-tags-overlay current ov-prefix)
11566 (while (re-search-forward
11567 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11568 (setq tg (match-string 1))
11569 (add-text-properties
11570 (match-beginning 1) (match-end 1)
11571 (list 'face
11572 (cond
11573 ((member tg current) c-face)
11574 ((member tg inherited) i-face)
11575 (t (get-text-property (match-beginning 1) 'face))))))
11576 (goto-char (point-min)))))
11577 (org-detach-overlay org-tags-overlay)
11578 (if rtn
11579 (mapconcat 'identity current ":")
11580 nil))))
11582 (defun org-get-tags-string ()
11583 "Get the TAGS string in the current headline."
11584 (unless (org-on-heading-p t)
11585 (error "Not on a heading"))
11586 (save-excursion
11587 (beginning-of-line 1)
11588 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11589 (org-match-string-no-properties 1)
11590 "")))
11592 (defun org-get-tags ()
11593 "Get the list of tags specified in the current headline."
11594 (org-split-string (org-get-tags-string) ":"))
11596 (defun org-get-buffer-tags ()
11597 "Get a table of all tags used in the buffer, for completion."
11598 (let (tags)
11599 (save-excursion
11600 (goto-char (point-min))
11601 (while (re-search-forward
11602 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11603 (when (equal (char-after (point-at-bol 0)) ?*)
11604 (mapc (lambda (x) (add-to-list 'tags x))
11605 (org-split-string (org-match-string-no-properties 1) ":")))))
11606 (mapcar 'list tags)))
11608 ;;;; The mapping API
11610 ;;;###autoload
11611 (defun org-map-entries (func &optional match scope &rest skip)
11612 "Call FUNC at each headline selected by MATCH in SCOPE.
11614 FUNC is a function or a lisp form. The function will be called without
11615 arguments, with the cursor positioned at the beginning of the headline.
11616 The return values of all calls to the function will be collected and
11617 returned as a list.
11619 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11620 does not need to preserve point. After evaluation, the cursor will be
11621 moved to the end of the line (presumably of the headline of the
11622 processed entry) and search continues from there. Under some
11623 circumstances, this may not produce the wanted results. For example,
11624 if you have removed (e.g. archived) the current (sub)tree it could
11625 mean that the next entry will be skipped entirely. In such cases, you
11626 can specify the position from where search should continue by making
11627 FUNC set the variable `org-map-continue-from' to the desired buffer
11628 position.
11630 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11631 Only headlines that are matched by this query will be considered during
11632 the iteration. When MATCH is nil or t, all headlines will be
11633 visited by the iteration.
11635 SCOPE determines the scope of this command. It can be any of:
11637 nil The current buffer, respecting the restriction if any
11638 tree The subtree started with the entry at point
11639 file The current buffer, without restriction
11640 file-with-archives
11641 The current buffer, and any archives associated with it
11642 agenda All agenda files
11643 agenda-with-archives
11644 All agenda files with any archive files associated with them
11645 \(file1 file2 ...)
11646 If this is a list, all files in the list will be scanned
11648 The remaining args are treated as settings for the skipping facilities of
11649 the scanner. The following items can be given here:
11651 archive skip trees with the archive tag.
11652 comment skip trees with the COMMENT keyword
11653 function or Emacs Lisp form:
11654 will be used as value for `org-agenda-skip-function', so whenever
11655 the the function returns t, FUNC will not be called for that
11656 entry and search will continue from the point where the
11657 function leaves it.
11659 If your function needs to retrieve the tags including inherited tags
11660 at the *current* entry, you can use the value of the variable
11661 `org-scanner-tags' which will be much faster than getting the value
11662 with `org-get-tags-at'. If your function gets properties with
11663 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11664 to t around the call to `org-entry-properties' to get the same speedup.
11665 Note that if your function moves around to retrieve tags and properties at
11666 a *different* entry, you cannot use these techniques."
11667 (let* ((org-agenda-archives-mode nil) ; just to make sure
11668 (org-agenda-skip-archived-trees (memq 'archive skip))
11669 (org-agenda-skip-comment-trees (memq 'comment skip))
11670 (org-agenda-skip-function
11671 (car (org-delete-all '(comment archive) skip)))
11672 (org-tags-match-list-sublevels t)
11673 matcher file res
11674 org-todo-keywords-for-agenda
11675 org-done-keywords-for-agenda
11676 org-todo-keyword-alist-for-agenda
11677 org-tag-alist-for-agenda)
11679 (cond
11680 ((eq match t) (setq matcher t))
11681 ((eq match nil) (setq matcher t))
11682 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11684 (save-excursion
11685 (save-restriction
11686 (when (eq scope 'tree)
11687 (org-back-to-heading t)
11688 (org-narrow-to-subtree)
11689 (setq scope nil))
11691 (if (not scope)
11692 (progn
11693 (org-prepare-agenda-buffers
11694 (list (buffer-file-name (current-buffer))))
11695 (setq res (org-scan-tags func matcher)))
11696 ;; Get the right scope
11697 (cond
11698 ((and scope (listp scope) (symbolp (car scope)))
11699 (setq scope (eval scope)))
11700 ((eq scope 'agenda)
11701 (setq scope (org-agenda-files t)))
11702 ((eq scope 'agenda-with-archives)
11703 (setq scope (org-agenda-files t))
11704 (setq scope (org-add-archive-files scope)))
11705 ((eq scope 'file)
11706 (setq scope (list (buffer-file-name))))
11707 ((eq scope 'file-with-archives)
11708 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11709 (org-prepare-agenda-buffers scope)
11710 (while (setq file (pop scope))
11711 (with-current-buffer (org-find-base-buffer-visiting file)
11712 (save-excursion
11713 (save-restriction
11714 (widen)
11715 (goto-char (point-min))
11716 (setq res (append res (org-scan-tags func matcher))))))))))
11717 res))
11719 ;;;; Properties
11721 ;;; Setting and retrieving properties
11723 (defconst org-special-properties
11724 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11725 "TIMESTAMP" "TIMESTAMP_IA")
11726 "The special properties valid in Org-mode.
11728 These are properties that are not defined in the property drawer,
11729 but in some other way.")
11731 (defconst org-default-properties
11732 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11733 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11734 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11735 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11736 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11737 "CLOCK_MODELINE_TOTAL")
11738 "Some properties that are used by Org-mode for various purposes.
11739 Being in this list makes sure that they are offered for completion.")
11741 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11742 "Regular expression matching the first line of a property drawer.")
11744 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11745 "Regular expression matching the first line of a property drawer.")
11747 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11748 "Regular expression matching the first line of a property drawer.")
11750 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11751 "Regular expression matching the first line of a property drawer.")
11753 (defconst org-property-drawer-re
11754 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11755 org-property-end-re "\\)\n?")
11756 "Matches an entire property drawer.")
11758 (defconst org-clock-drawer-re
11759 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11760 org-property-end-re "\\)\n?")
11761 "Matches an entire clock drawer.")
11763 (defun org-property-action ()
11764 "Do an action on properties."
11765 (interactive)
11766 (let (c)
11767 (org-at-property-p)
11768 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11769 (setq c (read-char-exclusive))
11770 (cond
11771 ((equal c ?s)
11772 (call-interactively 'org-set-property))
11773 ((equal c ?d)
11774 (call-interactively 'org-delete-property))
11775 ((equal c ?D)
11776 (call-interactively 'org-delete-property-globally))
11777 ((equal c ?c)
11778 (call-interactively 'org-compute-property-at-point))
11779 (t (error "No such property action %c" c)))))
11781 (defun org-set-effort (&optional value)
11782 "Set the effort property of the current entry.
11783 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
11784 allowed value."
11785 (interactive "P")
11786 (if (equal value 0) (setq value 10))
11787 (let* ((completion-ignore-case t)
11788 (prop org-effort-property)
11789 (cur (org-entry-get nil prop))
11790 (allowed (org-property-get-allowed-values nil prop 'table))
11791 (existing (mapcar 'list (org-property-values prop)))
11792 (val (cond
11793 ((stringp value) value)
11794 ((and allowed (integerp value))
11795 (or (car (nth (1- value) allowed))
11796 (car (org-last allowed))))
11797 (allowed
11798 (org-completing-read "Value: " allowed nil 'req-match))
11800 (let (org-completion-use-ido org-completion-use-iswitchb)
11801 (org-completing-read
11802 (concat "Value " (if (and cur (string-match "\\S-" cur))
11803 (concat "[" cur "]") "")
11804 ": ")
11805 existing nil nil "" nil cur))))))
11806 (unless (equal (org-entry-get nil prop) val)
11807 (org-entry-put nil prop val))
11808 (message "%s is now %s" prop val)))
11810 (defun org-at-property-p ()
11811 "Is the cursor in a property line?"
11812 ;; FIXME: Does not check if we are actually in the drawer.
11813 ;; FIXME: also returns true on any drawers.....
11814 ;; This is used by C-c C-c for property action.
11815 (save-excursion
11816 (beginning-of-line 1)
11817 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11819 (defun org-get-property-block (&optional beg end force)
11820 "Return the (beg . end) range of the body of the property drawer.
11821 BEG and END can be beginning and end of subtree, if not given
11822 they will be found.
11823 If the drawer does not exist and FORCE is non-nil, create the drawer."
11824 (catch 'exit
11825 (save-excursion
11826 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11827 (end (or end (progn (outline-next-heading) (point)))))
11828 (goto-char beg)
11829 (if (re-search-forward org-property-start-re end t)
11830 (setq beg (1+ (match-end 0)))
11831 (if force
11832 (save-excursion
11833 (org-insert-property-drawer)
11834 (setq end (progn (outline-next-heading) (point))))
11835 (throw 'exit nil))
11836 (goto-char beg)
11837 (if (re-search-forward org-property-start-re end t)
11838 (setq beg (1+ (match-end 0)))))
11839 (if (re-search-forward org-property-end-re end t)
11840 (setq end (match-beginning 0))
11841 (or force (throw 'exit nil))
11842 (goto-char beg)
11843 (setq end beg)
11844 (org-indent-line-function)
11845 (insert ":END:\n"))
11846 (cons beg end)))))
11848 (defun org-entry-properties (&optional pom which)
11849 "Get all properties of the entry at point-or-marker POM.
11850 This includes the TODO keyword, the tags, time strings for deadline,
11851 scheduled, and clocking, and any additional properties defined in the
11852 entry. The return value is an alist, keys may occur multiple times
11853 if the property key was used several times.
11854 POM may also be nil, in which case the current entry is used.
11855 If WHICH is nil or `all', get all properties. If WHICH is
11856 `special' or `standard', only get that subclass."
11857 (setq which (or which 'all))
11858 (org-with-point-at pom
11859 (let ((clockstr (substring org-clock-string 0 -1))
11860 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11861 beg end range props sum-props key value string clocksum)
11862 (save-excursion
11863 (when (condition-case nil
11864 (and (org-mode-p) (org-back-to-heading t))
11865 (error nil))
11866 (setq beg (point))
11867 (setq sum-props (get-text-property (point) 'org-summaries))
11868 (setq clocksum (get-text-property (point) :org-clock-minutes))
11869 (outline-next-heading)
11870 (setq end (point))
11871 (when (memq which '(all special))
11872 ;; Get the special properties, like TODO and tags
11873 (goto-char beg)
11874 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11875 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11876 (when (looking-at org-priority-regexp)
11877 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11878 (when (and (setq value (org-get-tags-string))
11879 (string-match "\\S-" value))
11880 (push (cons "TAGS" value) props))
11881 (when (setq value (org-get-tags-at))
11882 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11883 props))
11884 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11885 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11886 string (if (equal key clockstr)
11887 (org-no-properties
11888 (org-trim
11889 (buffer-substring
11890 (match-beginning 3) (goto-char (point-at-eol)))))
11891 (substring (org-match-string-no-properties 3) 1 -1)))
11892 (unless key
11893 (if (= (char-after (match-beginning 3)) ?\[)
11894 (setq key "TIMESTAMP_IA")
11895 (setq key "TIMESTAMP")))
11896 (when (or (equal key clockstr) (not (assoc key props)))
11897 (push (cons key string) props)))
11901 (when (memq which '(all standard))
11902 ;; Get the standard properties, like :PROP: ...
11903 (setq range (org-get-property-block beg end))
11904 (when range
11905 (goto-char (car range))
11906 (while (re-search-forward
11907 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11908 (cdr range) t)
11909 (setq key (org-match-string-no-properties 1)
11910 value (org-trim (or (org-match-string-no-properties 2) "")))
11911 (unless (member key excluded)
11912 (push (cons key (or value "")) props)))))
11913 (if clocksum
11914 (push (cons "CLOCKSUM"
11915 (org-columns-number-to-string (/ (float clocksum) 60.)
11916 'add_times))
11917 props))
11918 (unless (assoc "CATEGORY" props)
11919 (setq value (or (org-get-category)
11920 (progn (org-refresh-category-properties)
11921 (org-get-category))))
11922 (push (cons "CATEGORY" value) props))
11923 (append sum-props (nreverse props)))))))
11925 (defun org-entry-get (pom property &optional inherit)
11926 "Get value of PROPERTY for entry at point-or-marker POM.
11927 If INHERIT is non-nil and the entry does not have the property,
11928 then also check higher levels of the hierarchy.
11929 If INHERIT is the symbol `selective', use inheritance only if the setting
11930 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11931 If the property is present but empty, the return value is the empty string.
11932 If the property is not present at all, nil is returned."
11933 (org-with-point-at pom
11934 (if (and inherit (if (eq inherit 'selective)
11935 (org-property-inherit-p property)
11937 (org-entry-get-with-inheritance property)
11938 (if (member property org-special-properties)
11939 ;; We need a special property. Use brute force, get all properties.
11940 (cdr (assoc property (org-entry-properties nil 'special)))
11941 (let ((range (org-get-property-block)))
11942 (if (and range
11943 (goto-char (car range))
11944 (re-search-forward
11945 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11946 (cdr range) t))
11947 ;; Found the property, return it.
11948 (if (match-end 1)
11949 (org-match-string-no-properties 1)
11950 "")))))))
11952 (defun org-property-or-variable-value (var &optional inherit)
11953 "Check if there is a property fixing the value of VAR.
11954 If yes, return this value. If not, return the current value of the variable."
11955 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11956 (if (and prop (stringp prop) (string-match "\\S-" prop))
11957 (read prop)
11958 (symbol-value var))))
11960 (defun org-entry-delete (pom property)
11961 "Delete the property PROPERTY from entry at point-or-marker POM."
11962 (org-with-point-at pom
11963 (if (member property org-special-properties)
11964 nil ; cannot delete these properties.
11965 (let ((range (org-get-property-block)))
11966 (if (and range
11967 (goto-char (car range))
11968 (re-search-forward
11969 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11970 (cdr range) t))
11971 (progn
11972 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11974 nil)))))
11976 ;; Multi-values properties are properties that contain multiple values
11977 ;; These values are assumed to be single words, separated by whitespace.
11978 (defun org-entry-add-to-multivalued-property (pom property value)
11979 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11980 (let* ((old (org-entry-get pom property))
11981 (values (and old (org-split-string old "[ \t]"))))
11982 (setq value (org-entry-protect-space value))
11983 (unless (member value values)
11984 (setq values (cons value values))
11985 (org-entry-put pom property
11986 (mapconcat 'identity values " ")))))
11988 (defun org-entry-remove-from-multivalued-property (pom property value)
11989 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11990 (let* ((old (org-entry-get pom property))
11991 (values (and old (org-split-string old "[ \t]"))))
11992 (setq value (org-entry-protect-space value))
11993 (when (member value values)
11994 (setq values (delete value values))
11995 (org-entry-put pom property
11996 (mapconcat 'identity values " ")))))
11998 (defun org-entry-member-in-multivalued-property (pom property value)
11999 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12000 (let* ((old (org-entry-get pom property))
12001 (values (and old (org-split-string old "[ \t]"))))
12002 (setq value (org-entry-protect-space value))
12003 (member value values)))
12005 (defun org-entry-get-multivalued-property (pom property)
12006 "Return a list of values in a multivalued property."
12007 (let* ((value (org-entry-get pom property))
12008 (values (and value (org-split-string value "[ \t]"))))
12009 (mapcar 'org-entry-restore-space values)))
12011 (defun org-entry-put-multivalued-property (pom property &rest values)
12012 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12013 VALUES should be a list of strings. Spaces will be protected."
12014 (org-entry-put pom property
12015 (mapconcat 'org-entry-protect-space values " "))
12016 (let* ((value (org-entry-get pom property))
12017 (values (and value (org-split-string value "[ \t]"))))
12018 (mapcar 'org-entry-restore-space values)))
12020 (defun org-entry-protect-space (s)
12021 "Protect spaces and newline in string S."
12022 (while (string-match " " s)
12023 (setq s (replace-match "%20" t t s)))
12024 (while (string-match "\n" s)
12025 (setq s (replace-match "%0A" t t s)))
12028 (defun org-entry-restore-space (s)
12029 "Restore spaces and newline in string S."
12030 (while (string-match "%20" s)
12031 (setq s (replace-match " " t t s)))
12032 (while (string-match "%0A" s)
12033 (setq s (replace-match "\n" t t s)))
12036 (defvar org-entry-property-inherited-from (make-marker)
12037 "Marker pointing to the entry from where a property was inherited.
12038 Each call to `org-entry-get-with-inheritance' will set this marker to the
12039 location of the entry where the inheritance search matched. If there was
12040 no match, the marker will point nowhere.
12041 Note that also `org-entry-get' calls this function, if the INHERIT flag
12042 is set.")
12044 (defun org-entry-get-with-inheritance (property)
12045 "Get entry property, and search higher levels if not present."
12046 (move-marker org-entry-property-inherited-from nil)
12047 (let (tmp)
12048 (save-excursion
12049 (save-restriction
12050 (widen)
12051 (catch 'ex
12052 (while t
12053 (when (setq tmp (org-entry-get nil property))
12054 (org-back-to-heading t)
12055 (move-marker org-entry-property-inherited-from (point))
12056 (throw 'ex tmp))
12057 (or (org-up-heading-safe) (throw 'ex nil)))))
12058 (or tmp
12059 (cdr (assoc property org-file-properties))
12060 (cdr (assoc property org-global-properties))
12061 (cdr (assoc property org-global-properties-fixed))))))
12063 (defun org-entry-put (pom property value)
12064 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12065 (org-with-point-at pom
12066 (org-back-to-heading t)
12067 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12068 range)
12069 (cond
12070 ((equal property "TODO")
12071 (when (and (stringp value) (string-match "\\S-" value)
12072 (not (member value org-todo-keywords-1)))
12073 (error "\"%s\" is not a valid TODO state" value))
12074 (if (or (not value)
12075 (not (string-match "\\S-" value)))
12076 (setq value 'none))
12077 (org-todo value)
12078 (org-set-tags nil 'align))
12079 ((equal property "PRIORITY")
12080 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12081 (string-to-char value) ?\ ))
12082 (org-set-tags nil 'align))
12083 ((equal property "SCHEDULED")
12084 (if (re-search-forward org-scheduled-time-regexp end t)
12085 (cond
12086 ((eq value 'earlier) (org-timestamp-change -1 'day))
12087 ((eq value 'later) (org-timestamp-change 1 'day))
12088 (t (call-interactively 'org-schedule)))
12089 (call-interactively 'org-schedule)))
12090 ((equal property "DEADLINE")
12091 (if (re-search-forward org-deadline-time-regexp end t)
12092 (cond
12093 ((eq value 'earlier) (org-timestamp-change -1 'day))
12094 ((eq value 'later) (org-timestamp-change 1 'day))
12095 (t (call-interactively 'org-deadline)))
12096 (call-interactively 'org-deadline)))
12097 ((member property org-special-properties)
12098 (error "The %s property can not yet be set with `org-entry-put'"
12099 property))
12100 (t ; a non-special property
12101 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12102 (setq range (org-get-property-block beg end 'force))
12103 (goto-char (car range))
12104 (if (re-search-forward
12105 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12106 (progn
12107 (delete-region (match-beginning 1) (match-end 1))
12108 (goto-char (match-beginning 1)))
12109 (goto-char (cdr range))
12110 (insert "\n")
12111 (backward-char 1)
12112 (org-indent-line-function)
12113 (insert ":" property ":"))
12114 (and value (insert " " value))
12115 (org-indent-line-function)))))))
12117 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12118 "Get all property keys in the current buffer.
12119 With INCLUDE-SPECIALS, also list the special properties that reflect things
12120 like tags and TODO state.
12121 With INCLUDE-DEFAULTS, also include properties that has special meaning
12122 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12123 With INCLUDE-COLUMNS, also include property names given in COLUMN
12124 formats in the current buffer."
12125 (let (rtn range cfmt s p)
12126 (save-excursion
12127 (save-restriction
12128 (widen)
12129 (goto-char (point-min))
12130 (while (re-search-forward org-property-start-re nil t)
12131 (setq range (org-get-property-block))
12132 (goto-char (car range))
12133 (while (re-search-forward
12134 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12135 (cdr range) t)
12136 (add-to-list 'rtn (org-match-string-no-properties 1)))
12137 (outline-next-heading))))
12139 (when include-specials
12140 (setq rtn (append org-special-properties rtn)))
12142 (when include-defaults
12143 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12144 (add-to-list 'rtn org-effort-property))
12146 (when include-columns
12147 (save-excursion
12148 (save-restriction
12149 (widen)
12150 (goto-char (point-min))
12151 (while (re-search-forward
12152 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12153 nil t)
12154 (setq cfmt (match-string 2) s 0)
12155 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12156 cfmt s)
12157 (setq s (match-end 0)
12158 p (match-string 1 cfmt))
12159 (unless (or (equal p "ITEM")
12160 (member p org-special-properties))
12161 (add-to-list 'rtn (match-string 1 cfmt))))))))
12163 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12165 (defun org-property-values (key)
12166 "Return a list of all values of property KEY."
12167 (save-excursion
12168 (save-restriction
12169 (widen)
12170 (goto-char (point-min))
12171 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12172 values)
12173 (while (re-search-forward re nil t)
12174 (add-to-list 'values (org-trim (match-string 1))))
12175 (delete "" values)))))
12177 (defun org-insert-property-drawer ()
12178 "Insert a property drawer into the current entry."
12179 (interactive)
12180 (org-back-to-heading t)
12181 (looking-at outline-regexp)
12182 (let ((indent (if org-adapt-indentation
12183 (- (match-end 0)(match-beginning 0))
12185 (beg (point))
12186 (re (concat "^[ \t]*" org-keyword-time-regexp))
12187 end hiddenp)
12188 (outline-next-heading)
12189 (setq end (point))
12190 (goto-char beg)
12191 (while (re-search-forward re end t))
12192 (setq hiddenp (org-invisible-p))
12193 (end-of-line 1)
12194 (and (equal (char-after) ?\n) (forward-char 1))
12195 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12196 (if (member (match-string 1) '("CLOCK:" ":END:"))
12197 ;; just skip this line
12198 (beginning-of-line 2)
12199 ;; Drawer start, find the end
12200 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12201 (beginning-of-line 1)))
12202 (org-skip-over-state-notes)
12203 (skip-chars-backward " \t\n\r")
12204 (if (eq (char-before) ?*) (forward-char 1))
12205 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12206 (beginning-of-line 0)
12207 (org-indent-to-column indent)
12208 (beginning-of-line 2)
12209 (org-indent-to-column indent)
12210 (beginning-of-line 0)
12211 (if hiddenp
12212 (save-excursion
12213 (org-back-to-heading t)
12214 (hide-entry))
12215 (org-flag-drawer t))))
12217 (defun org-set-property (property value)
12218 "In the current entry, set PROPERTY to VALUE.
12219 When called interactively, this will prompt for a property name, offering
12220 completion on existing and default properties. And then it will prompt
12221 for a value, offering completion either on allowed values (via an inherited
12222 xxx_ALL property) or on existing values in other instances of this property
12223 in the current file."
12224 (interactive
12225 (let* ((completion-ignore-case t)
12226 (keys (org-buffer-property-keys nil t t))
12227 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12228 (prop (if (member prop0 keys)
12229 prop0
12230 (or (cdr (assoc (downcase prop0)
12231 (mapcar (lambda (x) (cons (downcase x) x))
12232 keys)))
12233 prop0)))
12234 (cur (org-entry-get nil prop))
12235 (allowed (org-property-get-allowed-values nil prop 'table))
12236 (existing (mapcar 'list (org-property-values prop)))
12237 (val (if allowed
12238 (org-completing-read "Value: " allowed nil 'req-match)
12239 (let (org-completion-use-ido org-completion-use-iswitchb)
12240 (org-completing-read
12241 (concat "Value " (if (and cur (string-match "\\S-" cur))
12242 (concat "[" cur "]") "")
12243 ": ")
12244 existing nil nil "" nil cur)))))
12245 (list prop (if (equal val "") cur val))))
12246 (unless (equal (org-entry-get nil property) value)
12247 (org-entry-put nil property value)))
12249 (defun org-delete-property (property)
12250 "In the current entry, delete PROPERTY."
12251 (interactive
12252 (let* ((completion-ignore-case t)
12253 (prop (org-icompleting-read
12254 "Property: " (org-entry-properties nil 'standard))))
12255 (list prop)))
12256 (message "Property %s %s" property
12257 (if (org-entry-delete nil property)
12258 "deleted"
12259 "was not present in the entry")))
12261 (defun org-delete-property-globally (property)
12262 "Remove PROPERTY globally, from all entries."
12263 (interactive
12264 (let* ((completion-ignore-case t)
12265 (prop (org-icompleting-read
12266 "Globally remove property: "
12267 (mapcar 'list (org-buffer-property-keys)))))
12268 (list prop)))
12269 (save-excursion
12270 (save-restriction
12271 (widen)
12272 (goto-char (point-min))
12273 (let ((cnt 0))
12274 (while (re-search-forward
12275 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12276 nil t)
12277 (setq cnt (1+ cnt))
12278 (replace-match ""))
12279 (message "Property \"%s\" removed from %d entries" property cnt)))))
12281 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12283 (defun org-compute-property-at-point ()
12284 "Compute the property at point.
12285 This looks for an enclosing column format, extracts the operator and
12286 then applies it to the property in the column format's scope."
12287 (interactive)
12288 (unless (org-at-property-p)
12289 (error "Not at a property"))
12290 (let ((prop (org-match-string-no-properties 2)))
12291 (org-columns-get-format-and-top-level)
12292 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12293 (error "No operator defined for property %s" prop))
12294 (org-columns-compute prop)))
12296 (defun org-property-get-allowed-values (pom property &optional table)
12297 "Get allowed values for the property PROPERTY.
12298 When TABLE is non-nil, return an alist that can directly be used for
12299 completion."
12300 (let (vals)
12301 (cond
12302 ((equal property "TODO")
12303 (setq vals (org-with-point-at pom
12304 (append org-todo-keywords-1 '("")))))
12305 ((equal property "PRIORITY")
12306 (let ((n org-lowest-priority))
12307 (while (>= n org-highest-priority)
12308 (push (char-to-string n) vals)
12309 (setq n (1- n)))))
12310 ((member property org-special-properties))
12312 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12314 (when (and vals (string-match "\\S-" vals))
12315 (setq vals (car (read-from-string (concat "(" vals ")"))))
12316 (setq vals (mapcar (lambda (x)
12317 (cond ((stringp x) x)
12318 ((numberp x) (number-to-string x))
12319 ((symbolp x) (symbol-name x))
12320 (t "???")))
12321 vals)))))
12322 (if table (mapcar 'list vals) vals)))
12324 (defun org-property-previous-allowed-value (&optional previous)
12325 "Switch to the next allowed value for this property."
12326 (interactive)
12327 (org-property-next-allowed-value t))
12329 (defun org-property-next-allowed-value (&optional previous)
12330 "Switch to the next allowed value for this property."
12331 (interactive)
12332 (unless (org-at-property-p)
12333 (error "Not at a property"))
12334 (let* ((key (match-string 2))
12335 (value (match-string 3))
12336 (allowed (or (org-property-get-allowed-values (point) key)
12337 (and (member value '("[ ]" "[-]" "[X]"))
12338 '("[ ]" "[X]"))))
12339 nval)
12340 (unless allowed
12341 (error "Allowed values for this property have not been defined"))
12342 (if previous (setq allowed (reverse allowed)))
12343 (if (member value allowed)
12344 (setq nval (car (cdr (member value allowed)))))
12345 (setq nval (or nval (car allowed)))
12346 (if (equal nval value)
12347 (error "Only one allowed value for this property"))
12348 (org-at-property-p)
12349 (replace-match (concat " :" key ": " nval) t t)
12350 (org-indent-line-function)
12351 (beginning-of-line 1)
12352 (skip-chars-forward " \t")))
12354 (defun org-find-entry-with-id (ident)
12355 "Locate the entry that contains the ID property with exact value IDENT.
12356 IDENT can be a string, a symbol or a number, this function will search for
12357 the string representation of it.
12358 Return the position where this entry starts, or nil if there is no such entry."
12359 (interactive "sID: ")
12360 (let ((id (cond
12361 ((stringp ident) ident)
12362 ((symbol-name ident) (symbol-name ident))
12363 ((numberp ident) (number-to-string ident))
12364 (t (error "IDENT %s must be a string, symbol or number" ident))))
12365 (case-fold-search nil))
12366 (save-excursion
12367 (save-restriction
12368 (widen)
12369 (goto-char (point-min))
12370 (when (re-search-forward
12371 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12372 nil t)
12373 (org-back-to-heading t)
12374 (point))))))
12376 ;;;; Timestamps
12378 (defvar org-last-changed-timestamp nil)
12379 (defvar org-last-inserted-timestamp nil
12380 "The last time stamp inserted with `org-insert-time-stamp'.")
12381 (defvar org-time-was-given) ; dynamically scoped parameter
12382 (defvar org-end-time-was-given) ; dynamically scoped parameter
12383 (defvar org-ts-what) ; dynamically scoped parameter
12385 (defun org-time-stamp (arg &optional inactive)
12386 "Prompt for a date/time and insert a time stamp.
12387 If the user specifies a time like HH:MM, or if this command is called
12388 with a prefix argument, the time stamp will contain date and time.
12389 Otherwise, only the date will be included. All parts of a date not
12390 specified by the user will be filled in from the current date/time.
12391 So if you press just return without typing anything, the time stamp
12392 will represent the current date/time. If there is already a timestamp
12393 at the cursor, it will be modified."
12394 (interactive "P")
12395 (let* ((ts nil)
12396 (default-time
12397 ;; Default time is either today, or, when entering a range,
12398 ;; the range start.
12399 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12400 (save-excursion
12401 (re-search-backward
12402 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12403 (- (point) 20) t)))
12404 (apply 'encode-time (org-parse-time-string (match-string 1)))
12405 (current-time)))
12406 (default-input (and ts (org-get-compact-tod ts)))
12407 org-time-was-given org-end-time-was-given time)
12408 (cond
12409 ((and (org-at-timestamp-p t)
12410 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12411 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12412 (insert "--")
12413 (setq time (let ((this-command this-command))
12414 (org-read-date arg 'totime nil nil
12415 default-time default-input)))
12416 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12417 ((org-at-timestamp-p t)
12418 (setq time (let ((this-command this-command))
12419 (org-read-date arg 'totime nil nil default-time default-input)))
12420 (when (org-at-timestamp-p t) ; just to get the match data
12421 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12422 (replace-match "")
12423 (setq org-last-changed-timestamp
12424 (org-insert-time-stamp
12425 time (or org-time-was-given arg)
12426 inactive nil nil (list org-end-time-was-given))))
12427 (message "Timestamp updated"))
12429 (setq time (let ((this-command this-command))
12430 (org-read-date arg 'totime nil nil default-time default-input)))
12431 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12432 nil nil (list org-end-time-was-given))))))
12434 ;; FIXME: can we use this for something else, like computing time differences?
12435 (defun org-get-compact-tod (s)
12436 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12437 (let* ((t1 (match-string 1 s))
12438 (h1 (string-to-number (match-string 2 s)))
12439 (m1 (string-to-number (match-string 3 s)))
12440 (t2 (and (match-end 4) (match-string 5 s)))
12441 (h2 (and t2 (string-to-number (match-string 6 s))))
12442 (m2 (and t2 (string-to-number (match-string 7 s))))
12443 dh dm)
12444 (if (not t2)
12446 (setq dh (- h2 h1) dm (- m2 m1))
12447 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12448 (concat t1 "+" (number-to-string dh)
12449 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12451 (defun org-time-stamp-inactive (&optional arg)
12452 "Insert an inactive time stamp.
12453 An inactive time stamp is enclosed in square brackets instead of angle
12454 brackets. It is inactive in the sense that it does not trigger agenda entries,
12455 does not link to the calendar and cannot be changed with the S-cursor keys.
12456 So these are more for recording a certain time/date."
12457 (interactive "P")
12458 (org-time-stamp arg 'inactive))
12460 (defvar org-date-ovl (org-make-overlay 1 1))
12461 (org-overlay-put org-date-ovl 'face 'org-warning)
12462 (org-detach-overlay org-date-ovl)
12464 (defvar org-ans1) ; dynamically scoped parameter
12465 (defvar org-ans2) ; dynamically scoped parameter
12467 (defvar org-plain-time-of-day-regexp) ; defined below
12469 (defvar org-overriding-default-time nil) ; dynamically scoped
12470 (defvar org-read-date-overlay nil)
12471 (defvar org-dcst nil) ; dynamically scoped
12472 (defvar org-read-date-history nil)
12473 (defvar org-read-date-final-answer nil)
12475 (defun org-read-date (&optional with-time to-time from-string prompt
12476 default-time default-input)
12477 "Read a date, possibly a time, and make things smooth for the user.
12478 The prompt will suggest to enter an ISO date, but you can also enter anything
12479 which will at least partially be understood by `parse-time-string'.
12480 Unrecognized parts of the date will default to the current day, month, year,
12481 hour and minute. If this command is called to replace a timestamp at point,
12482 of to enter the second timestamp of a range, the default time is taken from the
12483 existing stamp. For example,
12484 3-2-5 --> 2003-02-05
12485 feb 15 --> currentyear-02-15
12486 sep 12 9 --> 2009-09-12
12487 12:45 --> today 12:45
12488 22 sept 0:34 --> currentyear-09-22 0:34
12489 12 --> currentyear-currentmonth-12
12490 Fri --> nearest Friday (today or later)
12491 etc.
12493 Furthermore you can specify a relative date by giving, as the *first* thing
12494 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12495 change in days weeks, months, years.
12496 With a single plus or minus, the date is relative to today. With a double
12497 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12498 +4d --> four days from today
12499 +4 --> same as above
12500 +2w --> two weeks from today
12501 ++5 --> five days from default date
12503 The function understands only English month and weekday abbreviations,
12504 but this can be configured with the variables `parse-time-months' and
12505 `parse-time-weekdays'.
12507 While prompting, a calendar is popped up - you can also select the
12508 date with the mouse (button 1). The calendar shows a period of three
12509 months. To scroll it to other months, use the keys `>' and `<'.
12510 If you don't like the calendar, turn it off with
12511 \(setq org-read-date-popup-calendar nil)
12513 With optional argument TO-TIME, the date will immediately be converted
12514 to an internal time.
12515 With an optional argument WITH-TIME, the prompt will suggest to also
12516 insert a time. Note that when WITH-TIME is not set, you can still
12517 enter a time, and this function will inform the calling routine about
12518 this change. The calling routine may then choose to change the format
12519 used to insert the time stamp into the buffer to include the time.
12520 With optional argument FROM-STRING, read from this string instead from
12521 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12522 the time/date that is used for everything that is not specified by the
12523 user."
12524 (require 'parse-time)
12525 (let* ((org-time-stamp-rounding-minutes
12526 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12527 (org-dcst org-display-custom-times)
12528 (ct (org-current-time))
12529 (def (or org-overriding-default-time default-time ct))
12530 (defdecode (decode-time def))
12531 (dummy (progn
12532 (when (< (nth 2 defdecode) org-extend-today-until)
12533 (setcar (nthcdr 2 defdecode) -1)
12534 (setcar (nthcdr 1 defdecode) 59)
12535 (setq def (apply 'encode-time defdecode)
12536 defdecode (decode-time def)))))
12537 (calendar-frame-setup nil)
12538 (calendar-move-hook nil)
12539 (calendar-view-diary-initially-flag nil)
12540 (view-diary-entries-initially nil)
12541 (calendar-view-holidays-initially-flag nil)
12542 (view-calendar-holidays-initially nil)
12543 (timestr (format-time-string
12544 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12545 (prompt (concat (if prompt (concat prompt " ") "")
12546 (format "Date+time [%s]: " timestr)))
12547 ans (org-ans0 "") org-ans1 org-ans2 final)
12549 (cond
12550 (from-string (setq ans from-string))
12551 (org-read-date-popup-calendar
12552 (save-excursion
12553 (save-window-excursion
12554 (calendar)
12555 (calendar-forward-day (- (time-to-days def)
12556 (calendar-absolute-from-gregorian
12557 (calendar-current-date))))
12558 (org-eval-in-calendar nil t)
12559 (let* ((old-map (current-local-map))
12560 (map (copy-keymap calendar-mode-map))
12561 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12562 (org-defkey map (kbd "RET") 'org-calendar-select)
12563 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12564 'org-calendar-select-mouse)
12565 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12566 'org-calendar-select-mouse)
12567 (org-defkey minibuffer-local-map [(meta shift left)]
12568 (lambda () (interactive)
12569 (org-eval-in-calendar '(calendar-backward-month 1))))
12570 (org-defkey minibuffer-local-map [(meta shift right)]
12571 (lambda () (interactive)
12572 (org-eval-in-calendar '(calendar-forward-month 1))))
12573 (org-defkey minibuffer-local-map [(meta shift up)]
12574 (lambda () (interactive)
12575 (org-eval-in-calendar '(calendar-backward-year 1))))
12576 (org-defkey minibuffer-local-map [(meta shift down)]
12577 (lambda () (interactive)
12578 (org-eval-in-calendar '(calendar-forward-year 1))))
12579 (org-defkey minibuffer-local-map [?\e (shift left)]
12580 (lambda () (interactive)
12581 (org-eval-in-calendar '(calendar-backward-month 1))))
12582 (org-defkey minibuffer-local-map [?\e (shift right)]
12583 (lambda () (interactive)
12584 (org-eval-in-calendar '(calendar-forward-month 1))))
12585 (org-defkey minibuffer-local-map [?\e (shift up)]
12586 (lambda () (interactive)
12587 (org-eval-in-calendar '(calendar-backward-year 1))))
12588 (org-defkey minibuffer-local-map [?\e (shift down)]
12589 (lambda () (interactive)
12590 (org-eval-in-calendar '(calendar-forward-year 1))))
12591 (org-defkey minibuffer-local-map [(shift up)]
12592 (lambda () (interactive)
12593 (org-eval-in-calendar '(calendar-backward-week 1))))
12594 (org-defkey minibuffer-local-map [(shift down)]
12595 (lambda () (interactive)
12596 (org-eval-in-calendar '(calendar-forward-week 1))))
12597 (org-defkey minibuffer-local-map [(shift left)]
12598 (lambda () (interactive)
12599 (org-eval-in-calendar '(calendar-backward-day 1))))
12600 (org-defkey minibuffer-local-map [(shift right)]
12601 (lambda () (interactive)
12602 (org-eval-in-calendar '(calendar-forward-day 1))))
12603 (org-defkey minibuffer-local-map ">"
12604 (lambda () (interactive)
12605 (org-eval-in-calendar '(scroll-calendar-left 1))))
12606 (org-defkey minibuffer-local-map "<"
12607 (lambda () (interactive)
12608 (org-eval-in-calendar '(scroll-calendar-right 1))))
12609 (run-hooks 'org-read-date-minibuffer-setup-hook)
12610 (unwind-protect
12611 (progn
12612 (use-local-map map)
12613 (add-hook 'post-command-hook 'org-read-date-display)
12614 (setq org-ans0 (read-string prompt default-input
12615 'org-read-date-history nil))
12616 ;; org-ans0: from prompt
12617 ;; org-ans1: from mouse click
12618 ;; org-ans2: from calendar motion
12619 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12620 (remove-hook 'post-command-hook 'org-read-date-display)
12621 (use-local-map old-map)
12622 (when org-read-date-overlay
12623 (org-delete-overlay org-read-date-overlay)
12624 (setq org-read-date-overlay nil)))))))
12626 (t ; Naked prompt only
12627 (unwind-protect
12628 (setq ans (read-string prompt default-input
12629 'org-read-date-history timestr))
12630 (when org-read-date-overlay
12631 (org-delete-overlay org-read-date-overlay)
12632 (setq org-read-date-overlay nil)))))
12634 (setq final (org-read-date-analyze ans def defdecode))
12635 (setq org-read-date-final-answer ans)
12637 (if to-time
12638 (apply 'encode-time final)
12639 (if (and (boundp 'org-time-was-given) org-time-was-given)
12640 (format "%04d-%02d-%02d %02d:%02d"
12641 (nth 5 final) (nth 4 final) (nth 3 final)
12642 (nth 2 final) (nth 1 final))
12643 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12645 (defvar def)
12646 (defvar defdecode)
12647 (defvar with-time)
12648 (defun org-read-date-display ()
12649 "Display the current date prompt interpretation in the minibuffer."
12650 (when org-read-date-display-live
12651 (when org-read-date-overlay
12652 (org-delete-overlay org-read-date-overlay))
12653 (let ((p (point)))
12654 (end-of-line 1)
12655 (while (not (equal (buffer-substring
12656 (max (point-min) (- (point) 4)) (point))
12657 " "))
12658 (insert " "))
12659 (goto-char p))
12660 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12661 " " (or org-ans1 org-ans2)))
12662 (org-end-time-was-given nil)
12663 (f (org-read-date-analyze ans def defdecode))
12664 (fmts (if org-dcst
12665 org-time-stamp-custom-formats
12666 org-time-stamp-formats))
12667 (fmt (if (or with-time
12668 (and (boundp 'org-time-was-given) org-time-was-given))
12669 (cdr fmts)
12670 (car fmts)))
12671 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12672 (when (and org-end-time-was-given
12673 (string-match org-plain-time-of-day-regexp txt))
12674 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12675 org-end-time-was-given
12676 (substring txt (match-end 0)))))
12677 (setq org-read-date-overlay
12678 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12679 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12681 (defun org-read-date-analyze (ans def defdecode)
12682 "Analyse the combined answer of the date prompt."
12683 ;; FIXME: cleanup and comment
12684 (let (delta deltan deltaw deltadef year month day
12685 hour minute second wday pm h2 m2 tl wday1
12686 iso-year iso-weekday iso-week iso-year iso-date)
12688 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12689 (setq ans "+0"))
12691 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12692 (setq ans (replace-match "" t t ans)
12693 deltan (car delta)
12694 deltaw (nth 1 delta)
12695 deltadef (nth 2 delta)))
12697 ;; Check if there is an iso week date in there
12698 ;; If yes, sore the info and postpone interpreting it until the rest
12699 ;; of the parsing is done
12700 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12701 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12702 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12703 iso-week (string-to-number (match-string 2 ans)))
12704 (setq ans (replace-match "" t t ans)))
12706 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12707 (when (string-match
12708 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12709 (setq year (if (match-end 2)
12710 (string-to-number (match-string 2 ans))
12711 (string-to-number (format-time-string "%Y")))
12712 month (string-to-number (match-string 3 ans))
12713 day (string-to-number (match-string 4 ans)))
12714 (if (< year 100) (setq year (+ 2000 year)))
12715 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12716 t nil ans)))
12717 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12718 ;; If there is a time with am/pm, and *no* time without it, we convert
12719 ;; so that matching will be successful.
12720 (loop for i from 1 to 2 do ; twice, for end time as well
12721 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12722 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12723 (setq hour (string-to-number (match-string 1 ans))
12724 minute (if (match-end 3)
12725 (string-to-number (match-string 3 ans))
12727 pm (equal ?p
12728 (string-to-char (downcase (match-string 4 ans)))))
12729 (if (and (= hour 12) (not pm))
12730 (setq hour 0)
12731 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12732 (setq ans (replace-match (format "%02d:%02d" hour minute)
12733 t t ans))))
12735 ;; Check if a time range is given as a duration
12736 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12737 (setq hour (string-to-number (match-string 1 ans))
12738 h2 (+ hour (string-to-number (match-string 3 ans)))
12739 minute (string-to-number (match-string 2 ans))
12740 m2 (+ minute (if (match-end 5) (string-to-number
12741 (match-string 5 ans))0)))
12742 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12743 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12744 t t ans)))
12746 ;; Check if there is a time range
12747 (when (boundp 'org-end-time-was-given)
12748 (setq org-time-was-given nil)
12749 (when (and (string-match org-plain-time-of-day-regexp ans)
12750 (match-end 8))
12751 (setq org-end-time-was-given (match-string 8 ans))
12752 (setq ans (concat (substring ans 0 (match-beginning 7))
12753 (substring ans (match-end 7))))))
12755 (setq tl (parse-time-string ans)
12756 day (or (nth 3 tl) (nth 3 defdecode))
12757 month (or (nth 4 tl)
12758 (if (and org-read-date-prefer-future
12759 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12760 (1+ (nth 4 defdecode))
12761 (nth 4 defdecode)))
12762 year (or (nth 5 tl)
12763 (if (and org-read-date-prefer-future
12764 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12765 (1+ (nth 5 defdecode))
12766 (nth 5 defdecode)))
12767 hour (or (nth 2 tl) (nth 2 defdecode))
12768 minute (or (nth 1 tl) (nth 1 defdecode))
12769 second (or (nth 0 tl) 0)
12770 wday (nth 6 tl))
12772 ;; Special date definitions below
12773 (cond
12774 (iso-week
12775 ;; There was an iso week
12776 (setq year (or iso-year year)
12777 day (or iso-weekday wday 1)
12778 wday nil ; to make sure that the trigger below does not match
12779 iso-date (calendar-gregorian-from-absolute
12780 (calendar-absolute-from-iso
12781 (list iso-week day year))))
12782 ; FIXME: Should we also push ISO weeks into the future?
12783 ; (when (and org-read-date-prefer-future
12784 ; (not iso-year)
12785 ; (< (calendar-absolute-from-gregorian iso-date)
12786 ; (time-to-days (current-time))))
12787 ; (setq year (1+ year)
12788 ; iso-date (calendar-gregorian-from-absolute
12789 ; (calendar-absolute-from-iso
12790 ; (list iso-week day year)))))
12791 (setq month (car iso-date)
12792 year (nth 2 iso-date)
12793 day (nth 1 iso-date)))
12794 (deltan
12795 (unless deltadef
12796 (let ((now (decode-time (current-time))))
12797 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12798 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12799 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12800 ((equal deltaw "m") (setq month (+ month deltan)))
12801 ((equal deltaw "y") (setq year (+ year deltan)))))
12802 ((and wday (not (nth 3 tl)))
12803 ;; Weekday was given, but no day, so pick that day in the week
12804 ;; on or after the derived date.
12805 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12806 (unless (equal wday wday1)
12807 (setq day (+ day (% (- wday wday1 -7) 7))))))
12808 (if (and (boundp 'org-time-was-given)
12809 (nth 2 tl))
12810 (setq org-time-was-given t))
12811 (if (< year 100) (setq year (+ 2000 year)))
12812 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12813 (list second minute hour day month year)))
12815 (defvar parse-time-weekdays)
12817 (defun org-read-date-get-relative (s today default)
12818 "Check string S for special relative date string.
12819 TODAY and DEFAULT are internal times, for today and for a default.
12820 Return shift list (N what def-flag)
12821 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12822 N is the number of WHATs to shift.
12823 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12824 the DEFAULT date rather than TODAY."
12825 (when (and
12826 (string-match
12827 (concat
12828 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12829 "\\([0-9]+\\)?"
12830 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12831 "\\([ \t]\\|$\\)") s)
12832 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12833 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12834 (string-to-char (substring (match-string 1 s) -1))
12835 ?+))
12836 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12837 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12838 (what (if (match-end 3) (match-string 3 s) "d"))
12839 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12840 (date (if rel default today))
12841 (wday (nth 6 (decode-time date)))
12842 delta)
12843 (if wday1
12844 (progn
12845 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12846 (if (= dir ?-) (setq delta (- delta 7)))
12847 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12848 (list delta "d" rel))
12849 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12851 (defun org-eval-in-calendar (form &optional keepdate)
12852 "Eval FORM in the calendar window and return to current window.
12853 Also, store the cursor date in variable org-ans2."
12854 (let ((sf (selected-frame))
12855 (sw (selected-window)))
12856 (select-window (get-buffer-window "*Calendar*" t))
12857 (eval form)
12858 (when (and (not keepdate) (calendar-cursor-to-date))
12859 (let* ((date (calendar-cursor-to-date))
12860 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12861 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12862 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12863 (select-window sw)
12864 (org-select-frame-set-input-focus sf)))
12866 (defun org-calendar-select ()
12867 "Return to `org-read-date' with the date currently selected.
12868 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12869 (interactive)
12870 (when (calendar-cursor-to-date)
12871 (let* ((date (calendar-cursor-to-date))
12872 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12873 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12874 (if (active-minibuffer-window) (exit-minibuffer))))
12876 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12877 "Insert a date stamp for the date given by the internal TIME.
12878 WITH-HM means, use the stamp format that includes the time of the day.
12879 INACTIVE means use square brackets instead of angular ones, so that the
12880 stamp will not contribute to the agenda.
12881 PRE and POST are optional strings to be inserted before and after the
12882 stamp.
12883 The command returns the inserted time stamp."
12884 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12885 stamp)
12886 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12887 (insert-before-markers (or pre ""))
12888 (insert-before-markers (setq stamp (format-time-string fmt time)))
12889 (when (listp extra)
12890 (setq extra (car extra))
12891 (if (and (stringp extra)
12892 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12893 (setq extra (format "-%02d:%02d"
12894 (string-to-number (match-string 1 extra))
12895 (string-to-number (match-string 2 extra))))
12896 (setq extra nil)))
12897 (when extra
12898 (backward-char 1)
12899 (insert-before-markers extra)
12900 (forward-char 1))
12901 (insert-before-markers (or post ""))
12902 (setq org-last-inserted-timestamp stamp)))
12904 (defun org-toggle-time-stamp-overlays ()
12905 "Toggle the use of custom time stamp formats."
12906 (interactive)
12907 (setq org-display-custom-times (not org-display-custom-times))
12908 (unless org-display-custom-times
12909 (let ((p (point-min)) (bmp (buffer-modified-p)))
12910 (while (setq p (next-single-property-change p 'display))
12911 (if (and (get-text-property p 'display)
12912 (eq (get-text-property p 'face) 'org-date))
12913 (remove-text-properties
12914 p (setq p (next-single-property-change p 'display))
12915 '(display t))))
12916 (set-buffer-modified-p bmp)))
12917 (if (featurep 'xemacs)
12918 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12919 (org-restart-font-lock)
12920 (setq org-table-may-need-update t)
12921 (if org-display-custom-times
12922 (message "Time stamps are overlayed with custom format")
12923 (message "Time stamp overlays removed")))
12925 (defun org-display-custom-time (beg end)
12926 "Overlay modified time stamp format over timestamp between BEG and END."
12927 (let* ((ts (buffer-substring beg end))
12928 t1 w1 with-hm tf time str w2 (off 0))
12929 (save-match-data
12930 (setq t1 (org-parse-time-string ts t))
12931 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12932 (setq off (- (match-end 0) (match-beginning 0)))))
12933 (setq end (- end off))
12934 (setq w1 (- end beg)
12935 with-hm (and (nth 1 t1) (nth 2 t1))
12936 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12937 time (org-fix-decoded-time t1)
12938 str (org-add-props
12939 (format-time-string
12940 (substring tf 1 -1) (apply 'encode-time time))
12941 nil 'mouse-face 'highlight)
12942 w2 (length str))
12943 (if (not (= w2 w1))
12944 (add-text-properties (1+ beg) (+ 2 beg)
12945 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12946 (if (featurep 'xemacs)
12947 (progn
12948 (put-text-property beg end 'invisible t)
12949 (put-text-property beg end 'end-glyph (make-glyph str)))
12950 (put-text-property beg end 'display str))))
12952 (defun org-translate-time (string)
12953 "Translate all timestamps in STRING to custom format.
12954 But do this only if the variable `org-display-custom-times' is set."
12955 (when org-display-custom-times
12956 (save-match-data
12957 (let* ((start 0)
12958 (re org-ts-regexp-both)
12959 t1 with-hm inactive tf time str beg end)
12960 (while (setq start (string-match re string start))
12961 (setq beg (match-beginning 0)
12962 end (match-end 0)
12963 t1 (save-match-data
12964 (org-parse-time-string (substring string beg end) t))
12965 with-hm (and (nth 1 t1) (nth 2 t1))
12966 inactive (equal (substring string beg (1+ beg)) "[")
12967 tf (funcall (if with-hm 'cdr 'car)
12968 org-time-stamp-custom-formats)
12969 time (org-fix-decoded-time t1)
12970 str (format-time-string
12971 (concat
12972 (if inactive "[" "<") (substring tf 1 -1)
12973 (if inactive "]" ">"))
12974 (apply 'encode-time time))
12975 string (replace-match str t t string)
12976 start (+ start (length str)))))))
12977 string)
12979 (defun org-fix-decoded-time (time)
12980 "Set 0 instead of nil for the first 6 elements of time.
12981 Don't touch the rest."
12982 (let ((n 0))
12983 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12985 (defun org-days-to-time (timestamp-string)
12986 "Difference between TIMESTAMP-STRING and now in days."
12987 (- (time-to-days (org-time-string-to-time timestamp-string))
12988 (time-to-days (current-time))))
12990 (defun org-deadline-close (timestamp-string &optional ndays)
12991 "Is the time in TIMESTAMP-STRING close to the current date?"
12992 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12993 (and (< (org-days-to-time timestamp-string) ndays)
12994 (not (org-entry-is-done-p))))
12996 (defun org-get-wdays (ts)
12997 "Get the deadline lead time appropriate for timestring TS."
12998 (cond
12999 ((<= org-deadline-warning-days 0)
13000 ;; 0 or negative, enforce this value no matter what
13001 (- org-deadline-warning-days))
13002 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13003 ;; lead time is specified.
13004 (floor (* (string-to-number (match-string 1 ts))
13005 (cdr (assoc (match-string 2 ts)
13006 '(("d" . 1) ("w" . 7)
13007 ("m" . 30.4) ("y" . 365.25)))))))
13008 ;; go for the default.
13009 (t org-deadline-warning-days)))
13011 (defun org-calendar-select-mouse (ev)
13012 "Return to `org-read-date' with the date currently selected.
13013 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13014 (interactive "e")
13015 (mouse-set-point ev)
13016 (when (calendar-cursor-to-date)
13017 (let* ((date (calendar-cursor-to-date))
13018 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13019 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13020 (if (active-minibuffer-window) (exit-minibuffer))))
13022 (defun org-check-deadlines (ndays)
13023 "Check if there are any deadlines due or past due.
13024 A deadline is considered due if it happens within `org-deadline-warning-days'
13025 days from today's date. If the deadline appears in an entry marked DONE,
13026 it is not shown. The prefix arg NDAYS can be used to test that many
13027 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13028 (interactive "P")
13029 (let* ((org-warn-days
13030 (cond
13031 ((equal ndays '(4)) 100000)
13032 (ndays (prefix-numeric-value ndays))
13033 (t (abs org-deadline-warning-days))))
13034 (case-fold-search nil)
13035 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13036 (callback
13037 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13039 (message "%d deadlines past-due or due within %d days"
13040 (org-occur regexp nil callback)
13041 org-warn-days)))
13043 (defun org-check-before-date (date)
13044 "Check if there are deadlines or scheduled entries before DATE."
13045 (interactive (list (org-read-date)))
13046 (let ((case-fold-search nil)
13047 (regexp (concat "\\<\\(" org-deadline-string
13048 "\\|" org-scheduled-string
13049 "\\) *<\\([^>]+\\)>"))
13050 (callback
13051 (lambda () (time-less-p
13052 (org-time-string-to-time (match-string 2))
13053 (org-time-string-to-time date)))))
13054 (message "%d entries before %s"
13055 (org-occur regexp nil callback) date)))
13057 (defun org-check-after-date (date)
13058 "Check if there are deadlines or scheduled entries after DATE."
13059 (interactive (list (org-read-date)))
13060 (let ((case-fold-search nil)
13061 (regexp (concat "\\<\\(" org-deadline-string
13062 "\\|" org-scheduled-string
13063 "\\) *<\\([^>]+\\)>"))
13064 (callback
13065 (lambda () (not
13066 (time-less-p
13067 (org-time-string-to-time (match-string 2))
13068 (org-time-string-to-time date))))))
13069 (message "%d entries after %s"
13070 (org-occur regexp nil callback) date)))
13072 (defun org-evaluate-time-range (&optional to-buffer)
13073 "Evaluate a time range by computing the difference between start and end.
13074 Normally the result is just printed in the echo area, but with prefix arg
13075 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13076 If the time range is actually in a table, the result is inserted into the
13077 next column.
13078 For time difference computation, a year is assumed to be exactly 365
13079 days in order to avoid rounding problems."
13080 (interactive "P")
13082 (org-clock-update-time-maybe)
13083 (save-excursion
13084 (unless (org-at-date-range-p t)
13085 (goto-char (point-at-bol))
13086 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13087 (if (not (org-at-date-range-p t))
13088 (error "Not at a time-stamp range, and none found in current line")))
13089 (let* ((ts1 (match-string 1))
13090 (ts2 (match-string 2))
13091 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13092 (match-end (match-end 0))
13093 (time1 (org-time-string-to-time ts1))
13094 (time2 (org-time-string-to-time ts2))
13095 (t1 (org-float-time time1))
13096 (t2 (org-float-time time2))
13097 (diff (abs (- t2 t1)))
13098 (negative (< (- t2 t1) 0))
13099 ;; (ys (floor (* 365 24 60 60)))
13100 (ds (* 24 60 60))
13101 (hs (* 60 60))
13102 (fy "%dy %dd %02d:%02d")
13103 (fy1 "%dy %dd")
13104 (fd "%dd %02d:%02d")
13105 (fd1 "%dd")
13106 (fh "%02d:%02d")
13107 y d h m align)
13108 (if havetime
13109 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13111 d (floor (/ diff ds)) diff (mod diff ds)
13112 h (floor (/ diff hs)) diff (mod diff hs)
13113 m (floor (/ diff 60)))
13114 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13116 d (floor (+ (/ diff ds) 0.5))
13117 h 0 m 0))
13118 (if (not to-buffer)
13119 (message "%s" (org-make-tdiff-string y d h m))
13120 (if (org-at-table-p)
13121 (progn
13122 (goto-char match-end)
13123 (setq align t)
13124 (and (looking-at " *|") (goto-char (match-end 0))))
13125 (goto-char match-end))
13126 (if (looking-at
13127 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13128 (replace-match ""))
13129 (if negative (insert " -"))
13130 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13131 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13132 (insert " " (format fh h m))))
13133 (if align (org-table-align))
13134 (message "Time difference inserted")))))
13136 (defun org-make-tdiff-string (y d h m)
13137 (let ((fmt "")
13138 (l nil))
13139 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13140 l (push y l)))
13141 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13142 l (push d l)))
13143 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13144 l (push h l)))
13145 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13146 l (push m l)))
13147 (apply 'format fmt (nreverse l))))
13149 (defun org-time-string-to-time (s)
13150 (apply 'encode-time (org-parse-time-string s)))
13151 (defun org-time-string-to-seconds (s)
13152 (org-float-time (org-time-string-to-time s)))
13154 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13155 "Convert a time stamp to an absolute day number.
13156 If there is a specifyer for a cyclic time stamp, get the closest date to
13157 DAYNR.
13158 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13159 the variable date is bound by the calendar when this is called."
13160 (cond
13161 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13162 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13163 daynr
13164 (+ daynr 1000)))
13165 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13166 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13167 (time-to-days (current-time))) (match-string 0 s)
13168 prefer show-all))
13169 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13171 (defun org-days-to-iso-week (days)
13172 "Return the iso week number."
13173 (require 'cal-iso)
13174 (car (calendar-iso-from-absolute days)))
13176 (defun org-small-year-to-year (year)
13177 "Convert 2-digit years into 4-digit years.
13178 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13179 The year 2000 cannot be abbreviated. Any year larger than 99
13180 is returned unchanged."
13181 (if (< year 38)
13182 (setq year (+ 2000 year))
13183 (if (< year 100)
13184 (setq year (+ 1900 year))))
13185 year)
13187 (defun org-time-from-absolute (d)
13188 "Return the time corresponding to date D.
13189 D may be an absolute day number, or a calendar-type list (month day year)."
13190 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13191 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13193 (defun org-calendar-holiday ()
13194 "List of holidays, for Diary display in Org-mode."
13195 (require 'holidays)
13196 (let ((hl (funcall
13197 (if (fboundp 'calendar-check-holidays)
13198 'calendar-check-holidays 'check-calendar-holidays) date)))
13199 (if hl (mapconcat 'identity hl "; "))))
13201 (defun org-diary-sexp-entry (sexp entry date)
13202 "Process a SEXP diary ENTRY for DATE."
13203 (require 'diary-lib)
13204 (let ((result (if calendar-debug-sexp
13205 (let ((stack-trace-on-error t))
13206 (eval (car (read-from-string sexp))))
13207 (condition-case nil
13208 (eval (car (read-from-string sexp)))
13209 (error
13210 (beep)
13211 (message "Bad sexp at line %d in %s: %s"
13212 (org-current-line)
13213 (buffer-file-name) sexp)
13214 (sleep-for 2))))))
13215 (cond ((stringp result) result)
13216 ((and (consp result)
13217 (stringp (cdr result))) (cdr result))
13218 (result entry)
13219 (t nil))))
13221 (defun org-diary-to-ical-string (frombuf)
13222 "Get iCalendar entries from diary entries in buffer FROMBUF.
13223 This uses the icalendar.el library."
13224 (let* ((tmpdir (if (featurep 'xemacs)
13225 (temp-directory)
13226 temporary-file-directory))
13227 (tmpfile (make-temp-name
13228 (expand-file-name "orgics" tmpdir)))
13229 buf rtn b e)
13230 (save-excursion
13231 (set-buffer frombuf)
13232 (icalendar-export-region (point-min) (point-max) tmpfile)
13233 (setq buf (find-buffer-visiting tmpfile))
13234 (set-buffer buf)
13235 (goto-char (point-min))
13236 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13237 (setq b (match-beginning 0)))
13238 (goto-char (point-max))
13239 (if (re-search-backward "^END:VEVENT" nil t)
13240 (setq e (match-end 0)))
13241 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13242 (kill-buffer buf)
13243 (delete-file tmpfile)
13244 rtn))
13246 (defun org-closest-date (start current change prefer show-all)
13247 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13248 When PREFER is `past' return a date that is either CURRENT or past.
13249 When PREFER is `future', return a date that is either CURRENT or future.
13250 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13251 ;; Make the proper lists from the dates
13252 (catch 'exit
13253 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13254 dn dw sday cday n1 n2 n0
13255 d m y y1 y2 date1 date2 nmonths nm ny m2)
13257 (setq start (org-date-to-gregorian start)
13258 current (org-date-to-gregorian
13259 (if show-all
13260 current
13261 (time-to-days (current-time))))
13262 sday (calendar-absolute-from-gregorian start)
13263 cday (calendar-absolute-from-gregorian current))
13265 (if (<= cday sday) (throw 'exit sday))
13267 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13268 (setq dn (string-to-number (match-string 1 change))
13269 dw (cdr (assoc (match-string 2 change) a1)))
13270 (error "Invalid change specifyer: %s" change))
13271 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13272 (cond
13273 ((eq dw 'day)
13274 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13275 n2 (+ n1 dn)))
13276 ((eq dw 'year)
13277 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13278 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13279 (setq date1 (list m d y1)
13280 n1 (calendar-absolute-from-gregorian date1)
13281 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13282 n2 (calendar-absolute-from-gregorian date2)))
13283 ((eq dw 'month)
13284 ;; approx number of month between the two dates
13285 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13286 ;; How often does dn fit in there?
13287 (setq d (nth 1 start) m (car start) y (nth 2 start)
13288 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13289 m (+ m nm)
13290 ny (floor (/ m 12))
13291 y (+ y ny)
13292 m (- m (* ny 12)))
13293 (while (> m 12) (setq m (- m 12) y (1+ y)))
13294 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13295 (setq m2 (+ m dn) y2 y)
13296 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13297 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13298 (while (<= n2 cday)
13299 (setq n1 n2 m m2 y y2)
13300 (setq m2 (+ m dn) y2 y)
13301 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13302 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13303 ;; Make sure n1 is the earlier date
13304 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13305 (if show-all
13306 (cond
13307 ((eq prefer 'past) (if (= cday n2) n2 n1))
13308 ((eq prefer 'future) (if (= cday n1) n1 n2))
13309 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13310 (cond
13311 ((eq prefer 'past) (if (= cday n2) n2 n1))
13312 ((eq prefer 'future) (if (= cday n1) n1 n2))
13313 (t (if (= cday n1) n1 n2)))))))
13315 (defun org-date-to-gregorian (date)
13316 "Turn any specification of DATE into a gregorian date for the calendar."
13317 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13318 ((and (listp date) (= (length date) 3)) date)
13319 ((stringp date)
13320 (setq date (org-parse-time-string date))
13321 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13322 ((listp date)
13323 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13325 (defun org-parse-time-string (s &optional nodefault)
13326 "Parse the standard Org-mode time string.
13327 This should be a lot faster than the normal `parse-time-string'.
13328 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13329 hour and minute fields will be nil if not given."
13330 (if (string-match org-ts-regexp0 s)
13331 (list 0
13332 (if (or (match-beginning 8) (not nodefault))
13333 (string-to-number (or (match-string 8 s) "0")))
13334 (if (or (match-beginning 7) (not nodefault))
13335 (string-to-number (or (match-string 7 s) "0")))
13336 (string-to-number (match-string 4 s))
13337 (string-to-number (match-string 3 s))
13338 (string-to-number (match-string 2 s))
13339 nil nil nil)
13340 (error "Not a standard Org-mode time string: %s" s)))
13342 (defun org-timestamp-up (&optional arg)
13343 "Increase the date item at the cursor by one.
13344 If the cursor is on the year, change the year. If it is on the month or
13345 the day, change that.
13346 With prefix ARG, change by that many units."
13347 (interactive "p")
13348 (org-timestamp-change (prefix-numeric-value arg)))
13350 (defun org-timestamp-down (&optional arg)
13351 "Decrease the date item at the cursor by one.
13352 If the cursor is on the year, change the year. If it is on the month or
13353 the day, change that.
13354 With prefix ARG, change by that many units."
13355 (interactive "p")
13356 (org-timestamp-change (- (prefix-numeric-value arg))))
13358 (defun org-timestamp-up-day (&optional arg)
13359 "Increase the date in the time stamp by one day.
13360 With prefix ARG, change that many days."
13361 (interactive "p")
13362 (if (and (not (org-at-timestamp-p t))
13363 (org-on-heading-p))
13364 (org-todo 'up)
13365 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13367 (defun org-timestamp-down-day (&optional arg)
13368 "Decrease the date in the time stamp by one day.
13369 With prefix ARG, change that many days."
13370 (interactive "p")
13371 (if (and (not (org-at-timestamp-p t))
13372 (org-on-heading-p))
13373 (org-todo 'down)
13374 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13376 (defun org-at-timestamp-p (&optional inactive-ok)
13377 "Determine if the cursor is in or at a timestamp."
13378 (interactive)
13379 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13380 (pos (point))
13381 (ans (or (looking-at tsr)
13382 (save-excursion
13383 (skip-chars-backward "^[<\n\r\t")
13384 (if (> (point) (point-min)) (backward-char 1))
13385 (and (looking-at tsr)
13386 (> (- (match-end 0) pos) -1))))))
13387 (and ans
13388 (boundp 'org-ts-what)
13389 (setq org-ts-what
13390 (cond
13391 ((= pos (match-beginning 0)) 'bracket)
13392 ((= pos (1- (match-end 0))) 'bracket)
13393 ((org-pos-in-match-range pos 2) 'year)
13394 ((org-pos-in-match-range pos 3) 'month)
13395 ((org-pos-in-match-range pos 7) 'hour)
13396 ((org-pos-in-match-range pos 8) 'minute)
13397 ((or (org-pos-in-match-range pos 4)
13398 (org-pos-in-match-range pos 5)) 'day)
13399 ((and (> pos (or (match-end 8) (match-end 5)))
13400 (< pos (match-end 0)))
13401 (- pos (or (match-end 8) (match-end 5))))
13402 (t 'day))))
13403 ans))
13405 (defun org-toggle-timestamp-type ()
13406 "Toggle the type (<active> or [inactive]) of a time stamp."
13407 (interactive)
13408 (when (org-at-timestamp-p t)
13409 (let ((beg (match-beginning 0)) (end (match-end 0))
13410 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13411 (save-excursion
13412 (goto-char beg)
13413 (while (re-search-forward "[][<>]" end t)
13414 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13415 t t)))
13416 (message "Timestamp is now %sactive"
13417 (if (equal (char-after beg) ?<) "" "in")))))
13419 (defun org-timestamp-change (n &optional what)
13420 "Change the date in the time stamp at point.
13421 The date will be changed by N times WHAT. WHAT can be `day', `month',
13422 `year', `minute', `second'. If WHAT is not given, the cursor position
13423 in the timestamp determines what will be changed."
13424 (let ((pos (point))
13425 with-hm inactive
13426 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13427 org-ts-what
13428 extra rem
13429 ts time time0)
13430 (if (not (org-at-timestamp-p t))
13431 (error "Not at a timestamp"))
13432 (if (and (not what) (eq org-ts-what 'bracket))
13433 (org-toggle-timestamp-type)
13434 (if (and (not what) (not (eq org-ts-what 'day))
13435 org-display-custom-times
13436 (get-text-property (point) 'display)
13437 (not (get-text-property (1- (point)) 'display)))
13438 (setq org-ts-what 'day))
13439 (setq org-ts-what (or what org-ts-what)
13440 inactive (= (char-after (match-beginning 0)) ?\[)
13441 ts (match-string 0))
13442 (replace-match "")
13443 (if (string-match
13444 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13446 (setq extra (match-string 1 ts)))
13447 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13448 (setq with-hm t))
13449 (setq time0 (org-parse-time-string ts))
13450 (when (and (eq org-ts-what 'minute)
13451 (eq current-prefix-arg nil))
13452 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13453 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13454 (setcar (cdr time0) (+ (nth 1 time0)
13455 (if (> n 0) (- rem) (- dm rem))))))
13456 (setq time
13457 (encode-time (or (car time0) 0)
13458 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13459 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13460 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13461 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13462 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13463 (nthcdr 6 time0)))
13464 (when (and (member org-ts-what '(hour minute))
13465 extra
13466 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13467 (setq extra (org-modify-ts-extra
13468 extra
13469 (if (eq org-ts-what 'hour) 2 5)
13470 n dm)))
13471 (when (integerp org-ts-what)
13472 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13473 (if (eq what 'calendar)
13474 (let ((cal-date (org-get-date-from-calendar)))
13475 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13476 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13477 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13478 (setcar time0 (or (car time0) 0))
13479 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13480 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13481 (setq time (apply 'encode-time time0))))
13482 (setq org-last-changed-timestamp
13483 (org-insert-time-stamp time with-hm inactive nil nil extra))
13484 (org-clock-update-time-maybe)
13485 (goto-char pos)
13486 ;; Try to recenter the calendar window, if any
13487 (if (and org-calendar-follow-timestamp-change
13488 (get-buffer-window "*Calendar*" t)
13489 (memq org-ts-what '(day month year)))
13490 (org-recenter-calendar (time-to-days time))))))
13492 (defun org-modify-ts-extra (s pos n dm)
13493 "Change the different parts of the lead-time and repeat fields in timestamp."
13494 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13495 ng h m new rem)
13496 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13497 (cond
13498 ((or (org-pos-in-match-range pos 2)
13499 (org-pos-in-match-range pos 3))
13500 (setq m (string-to-number (match-string 3 s))
13501 h (string-to-number (match-string 2 s)))
13502 (if (org-pos-in-match-range pos 2)
13503 (setq h (+ h n))
13504 (setq n (* dm (org-no-warnings (signum n))))
13505 (when (not (= 0 (setq rem (% m dm))))
13506 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13507 (setq m (+ m n)))
13508 (if (< m 0) (setq m (+ m 60) h (1- h)))
13509 (if (> m 59) (setq m (- m 60) h (1+ h)))
13510 (setq h (min 24 (max 0 h)))
13511 (setq ng 1 new (format "-%02d:%02d" h m)))
13512 ((org-pos-in-match-range pos 6)
13513 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13514 ((org-pos-in-match-range pos 5)
13515 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13517 ((org-pos-in-match-range pos 9)
13518 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13519 ((org-pos-in-match-range pos 8)
13520 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13522 (when ng
13523 (setq s (concat
13524 (substring s 0 (match-beginning ng))
13526 (substring s (match-end ng))))))
13529 (defun org-recenter-calendar (date)
13530 "If the calendar is visible, recenter it to DATE."
13531 (let* ((win (selected-window))
13532 (cwin (get-buffer-window "*Calendar*" t))
13533 (calendar-move-hook nil))
13534 (when cwin
13535 (select-window cwin)
13536 (calendar-goto-date (if (listp date) date
13537 (calendar-gregorian-from-absolute date)))
13538 (select-window win))))
13540 (defun org-goto-calendar (&optional arg)
13541 "Go to the Emacs calendar at the current date.
13542 If there is a time stamp in the current line, go to that date.
13543 A prefix ARG can be used to force the current date."
13544 (interactive "P")
13545 (let ((tsr org-ts-regexp) diff
13546 (calendar-move-hook nil)
13547 (calendar-view-holidays-initially-flag nil)
13548 (view-calendar-holidays-initially nil)
13549 (calendar-view-diary-initially-flag nil)
13550 (view-diary-entries-initially nil))
13551 (if (or (org-at-timestamp-p)
13552 (save-excursion
13553 (beginning-of-line 1)
13554 (looking-at (concat ".*" tsr))))
13555 (let ((d1 (time-to-days (current-time)))
13556 (d2 (time-to-days
13557 (org-time-string-to-time (match-string 1)))))
13558 (setq diff (- d2 d1))))
13559 (calendar)
13560 (calendar-goto-today)
13561 (if (and diff (not arg)) (calendar-forward-day diff))))
13563 (defun org-get-date-from-calendar ()
13564 "Return a list (month day year) of date at point in calendar."
13565 (with-current-buffer "*Calendar*"
13566 (save-match-data
13567 (calendar-cursor-to-date))))
13569 (defun org-date-from-calendar ()
13570 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13571 If there is already a time stamp at the cursor position, update it."
13572 (interactive)
13573 (if (org-at-timestamp-p t)
13574 (org-timestamp-change 0 'calendar)
13575 (let ((cal-date (org-get-date-from-calendar)))
13576 (org-insert-time-stamp
13577 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13579 (defun org-minutes-to-hh:mm-string (m)
13580 "Compute H:MM from a number of minutes."
13581 (let ((h (/ m 60)))
13582 (setq m (- m (* 60 h)))
13583 (format org-time-clocksum-format h m)))
13585 (defun org-hh:mm-string-to-minutes (s)
13586 "Convert a string H:MM to a number of minutes.
13587 If the string is just a number, interprete it as minutes.
13588 In fact, the first hh:mm or number in the string will be taken,
13589 there can be extra stuff in the string.
13590 If no number is found, the return value is 0."
13591 (cond
13592 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13593 (+ (* (string-to-number (match-string 1 s)) 60)
13594 (string-to-number (match-string 2 s))))
13595 ((string-match "\\([0-9]+\\)" s)
13596 (string-to-number (match-string 1 s)))
13597 (t 0)))
13599 ;;;; Files
13601 (defun org-save-all-org-buffers ()
13602 "Save all Org-mode buffers without user confirmation."
13603 (interactive)
13604 (message "Saving all Org-mode buffers...")
13605 (save-some-buffers t 'org-mode-p)
13606 (when (featurep 'org-id) (org-id-locations-save))
13607 (message "Saving all Org-mode buffers... done"))
13609 (defun org-revert-all-org-buffers ()
13610 "Revert all Org-mode buffers.
13611 Prompt for confirmation when there are unsaved changes.
13612 Be sure you know what you are doing before letting this function
13613 overwrite your changes.
13615 This function is useful in a setup where one tracks org files
13616 with a version control system, to revert on one machine after pulling
13617 changes from another. I believe the procedure must be like this:
13619 1. M-x org-save-all-org-buffers
13620 2. Pull changes from the other machine, resolve conflicts
13621 3. M-x org-revert-all-org-buffers"
13622 (interactive)
13623 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13624 (error "Abort"))
13625 (save-excursion
13626 (save-window-excursion
13627 (mapc
13628 (lambda (b)
13629 (when (and (with-current-buffer b (org-mode-p))
13630 (with-current-buffer b buffer-file-name))
13631 (switch-to-buffer b)
13632 (revert-buffer t 'no-confirm)))
13633 (buffer-list))
13634 (when (and (featurep 'org-id) org-id-track-globally)
13635 (org-id-locations-load)))))
13637 ;;;; Agenda files
13639 ;;;###autoload
13640 (defun org-iswitchb (&optional arg)
13641 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13642 With a prefix argument, restrict available to files.
13643 With two prefix arguments, restrict available buffers to agenda files."
13644 (interactive "P")
13645 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13646 ((equal arg '(16)) (org-buffer-list 'agenda))
13647 (t (org-buffer-list)))))
13648 (switch-to-buffer
13649 (org-icompleting-read "Org buffer: "
13650 (mapcar 'list (mapcar 'buffer-name blist))
13651 nil t))))
13653 ;;;###autoload
13654 (defalias 'org-ido-switchb 'org-iswitchb)
13656 (defun org-buffer-list (&optional predicate exclude-tmp)
13657 "Return a list of Org buffers.
13658 PREDICATE can be `export', `files' or `agenda'.
13660 export restrict the list to Export buffers.
13661 files restrict the list to buffers visiting Org files.
13662 agenda restrict the list to buffers visiting agenda files.
13664 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13665 (let* ((bfn nil)
13666 (agenda-files (and (eq predicate 'agenda)
13667 (mapcar 'file-truename (org-agenda-files t))))
13668 (filter
13669 (cond
13670 ((eq predicate 'files)
13671 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13672 ((eq predicate 'export)
13673 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13674 ((eq predicate 'agenda)
13675 (lambda (b)
13676 (with-current-buffer b
13677 (and (eq major-mode 'org-mode)
13678 (setq bfn (buffer-file-name b))
13679 (member (file-truename bfn) agenda-files)))))
13680 (t (lambda (b) (with-current-buffer b
13681 (or (eq major-mode 'org-mode)
13682 (string-match "\*Org .*Export"
13683 (buffer-name b)))))))))
13684 (delq nil
13685 (mapcar
13686 (lambda(b)
13687 (if (and (funcall filter b)
13688 (or (not exclude-tmp)
13689 (not (string-match "tmp" (buffer-name b)))))
13691 nil))
13692 (buffer-list)))))
13694 (defun org-agenda-files (&optional unrestricted archives)
13695 "Get the list of agenda files.
13696 Optional UNRESTRICTED means return the full list even if a restriction
13697 is currently in place.
13698 When ARCHIVES is t, include all archive files hat are really being
13699 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13700 `org-agenda-archives-mode' is t."
13701 (let ((files
13702 (cond
13703 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13704 ((stringp org-agenda-files) (org-read-agenda-file-list))
13705 ((listp org-agenda-files) org-agenda-files)
13706 (t (error "Invalid value of `org-agenda-files'")))))
13707 (setq files (apply 'append
13708 (mapcar (lambda (f)
13709 (if (file-directory-p f)
13710 (directory-files
13711 f t org-agenda-file-regexp)
13712 (list f)))
13713 files)))
13714 (when org-agenda-skip-unavailable-files
13715 (setq files (delq nil
13716 (mapcar (function
13717 (lambda (file)
13718 (and (file-readable-p file) file)))
13719 files))))
13720 (when (or (eq archives t)
13721 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13722 (setq files (org-add-archive-files files)))
13723 files))
13725 (defun org-edit-agenda-file-list ()
13726 "Edit the list of agenda files.
13727 Depending on setup, this either uses customize to edit the variable
13728 `org-agenda-files', or it visits the file that is holding the list. In the
13729 latter case, the buffer is set up in a way that saving it automatically kills
13730 the buffer and restores the previous window configuration."
13731 (interactive)
13732 (if (stringp org-agenda-files)
13733 (let ((cw (current-window-configuration)))
13734 (find-file org-agenda-files)
13735 (org-set-local 'org-window-configuration cw)
13736 (org-add-hook 'after-save-hook
13737 (lambda ()
13738 (set-window-configuration
13739 (prog1 org-window-configuration
13740 (kill-buffer (current-buffer))))
13741 (org-install-agenda-files-menu)
13742 (message "New agenda file list installed"))
13743 nil 'local)
13744 (message "%s" (substitute-command-keys
13745 "Edit list and finish with \\[save-buffer]")))
13746 (customize-variable 'org-agenda-files)))
13748 (defun org-store-new-agenda-file-list (list)
13749 "Set new value for the agenda file list and save it correctly."
13750 (if (stringp org-agenda-files)
13751 (let ((f org-agenda-files) b)
13752 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13753 (with-temp-file f
13754 (insert (mapconcat 'identity list "\n") "\n")))
13755 (let ((org-mode-hook nil) (org-inhibit-startup t)
13756 (org-insert-mode-line-in-empty-file nil))
13757 (setq org-agenda-files list)
13758 (customize-save-variable 'org-agenda-files org-agenda-files))))
13760 (defun org-read-agenda-file-list ()
13761 "Read the list of agenda files from a file."
13762 (when (file-directory-p org-agenda-files)
13763 (error "`org-agenda-files' cannot be a single directory"))
13764 (when (stringp org-agenda-files)
13765 (with-temp-buffer
13766 (insert-file-contents org-agenda-files)
13767 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13770 ;;;###autoload
13771 (defun org-cycle-agenda-files ()
13772 "Cycle through the files in `org-agenda-files'.
13773 If the current buffer visits an agenda file, find the next one in the list.
13774 If the current buffer does not, find the first agenda file."
13775 (interactive)
13776 (let* ((fs (org-agenda-files t))
13777 (files (append fs (list (car fs))))
13778 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13779 file)
13780 (unless files (error "No agenda files"))
13781 (catch 'exit
13782 (while (setq file (pop files))
13783 (if (equal (file-truename file) tcf)
13784 (when (car files)
13785 (find-file (car files))
13786 (throw 'exit t))))
13787 (find-file (car fs)))
13788 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13790 (defun org-agenda-file-to-front (&optional to-end)
13791 "Move/add the current file to the top of the agenda file list.
13792 If the file is not present in the list, it is added to the front. If it is
13793 present, it is moved there. With optional argument TO-END, add/move to the
13794 end of the list."
13795 (interactive "P")
13796 (let ((org-agenda-skip-unavailable-files nil)
13797 (file-alist (mapcar (lambda (x)
13798 (cons (file-truename x) x))
13799 (org-agenda-files t)))
13800 (ctf (file-truename buffer-file-name))
13801 x had)
13802 (setq x (assoc ctf file-alist) had x)
13804 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13805 (if to-end
13806 (setq file-alist (append (delq x file-alist) (list x)))
13807 (setq file-alist (cons x (delq x file-alist))))
13808 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13809 (org-install-agenda-files-menu)
13810 (message "File %s to %s of agenda file list"
13811 (if had "moved" "added") (if to-end "end" "front"))))
13813 (defun org-remove-file (&optional file)
13814 "Remove current file from the list of files in variable `org-agenda-files'.
13815 These are the files which are being checked for agenda entries.
13816 Optional argument FILE means, use this file instead of the current."
13817 (interactive)
13818 (let* ((org-agenda-skip-unavailable-files nil)
13819 (file (or file buffer-file-name))
13820 (true-file (file-truename file))
13821 (afile (abbreviate-file-name file))
13822 (files (delq nil (mapcar
13823 (lambda (x)
13824 (if (equal true-file
13825 (file-truename x))
13826 nil x))
13827 (org-agenda-files t)))))
13828 (if (not (= (length files) (length (org-agenda-files t))))
13829 (progn
13830 (org-store-new-agenda-file-list files)
13831 (org-install-agenda-files-menu)
13832 (message "Removed file: %s" afile))
13833 (message "File was not in list: %s (not removed)" afile))))
13835 (defun org-file-menu-entry (file)
13836 (vector file (list 'find-file file) t))
13838 (defun org-check-agenda-file (file)
13839 "Make sure FILE exists. If not, ask user what to do."
13840 (when (not (file-exists-p file))
13841 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
13842 (abbreviate-file-name file))
13843 (let ((r (downcase (read-char-exclusive))))
13844 (cond
13845 ((equal r ?r)
13846 (org-remove-file file)
13847 (throw 'nextfile t))
13848 (t (error "Abort"))))))
13850 (defun org-get-agenda-file-buffer (file)
13851 "Get a buffer visiting FILE. If the buffer needs to be created, add
13852 it to the list of buffers which might be released later."
13853 (let ((buf (org-find-base-buffer-visiting file)))
13854 (if buf
13855 buf ; just return it
13856 ;; Make a new buffer and remember it
13857 (setq buf (find-file-noselect file))
13858 (if buf (push buf org-agenda-new-buffers))
13859 buf)))
13861 (defun org-release-buffers (blist)
13862 "Release all buffers in list, asking the user for confirmation when needed.
13863 When a buffer is unmodified, it is just killed. When modified, it is saved
13864 \(if the user agrees) and then killed."
13865 (let (buf file)
13866 (while (setq buf (pop blist))
13867 (setq file (buffer-file-name buf))
13868 (when (and (buffer-modified-p buf)
13869 file
13870 (y-or-n-p (format "Save file %s? " file)))
13871 (with-current-buffer buf (save-buffer)))
13872 (kill-buffer buf))))
13874 (defun org-prepare-agenda-buffers (files)
13875 "Create buffers for all agenda files, protect archived trees and comments."
13876 (interactive)
13877 (let ((pa '(:org-archived t))
13878 (pc '(:org-comment t))
13879 (pall '(:org-archived t :org-comment t))
13880 (inhibit-read-only t)
13881 (rea (concat ":" org-archive-tag ":"))
13882 bmp file re)
13883 (save-excursion
13884 (save-restriction
13885 (while (setq file (pop files))
13886 (catch 'nextfile
13887 (if (bufferp file)
13888 (set-buffer file)
13889 (org-check-agenda-file file)
13890 (set-buffer (org-get-agenda-file-buffer file)))
13891 (widen)
13892 (setq bmp (buffer-modified-p))
13893 (org-refresh-category-properties)
13894 (setq org-todo-keywords-for-agenda
13895 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13896 (setq org-done-keywords-for-agenda
13897 (append org-done-keywords-for-agenda org-done-keywords))
13898 (setq org-todo-keyword-alist-for-agenda
13899 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13900 (setq org-tag-alist-for-agenda
13901 (append org-tag-alist-for-agenda org-tag-alist))
13903 (save-excursion
13904 (remove-text-properties (point-min) (point-max) pall)
13905 (when org-agenda-skip-archived-trees
13906 (goto-char (point-min))
13907 (while (re-search-forward rea nil t)
13908 (if (org-on-heading-p t)
13909 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13910 (goto-char (point-min))
13911 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13912 (while (re-search-forward re nil t)
13913 (add-text-properties
13914 (match-beginning 0) (org-end-of-subtree t) pc)))
13915 (set-buffer-modified-p bmp)))))
13916 (setq org-todo-keyword-alist-for-agenda
13917 (org-uniquify org-todo-keyword-alist-for-agenda)
13918 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13920 ;;;; Embedded LaTeX
13922 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13923 "Keymap for the minor `org-cdlatex-mode'.")
13925 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13926 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13927 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13928 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13929 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13931 (defvar org-cdlatex-texmathp-advice-is-done nil
13932 "Flag remembering if we have applied the advice to texmathp already.")
13934 (define-minor-mode org-cdlatex-mode
13935 "Toggle the minor `org-cdlatex-mode'.
13936 This mode supports entering LaTeX environment and math in LaTeX fragments
13937 in Org-mode.
13938 \\{org-cdlatex-mode-map}"
13939 nil " OCDL" nil
13940 (when org-cdlatex-mode (require 'cdlatex))
13941 (unless org-cdlatex-texmathp-advice-is-done
13942 (setq org-cdlatex-texmathp-advice-is-done t)
13943 (defadvice texmathp (around org-math-always-on activate)
13944 "Always return t in org-mode buffers.
13945 This is because we want to insert math symbols without dollars even outside
13946 the LaTeX math segments. If Orgmode thinks that point is actually inside
13947 an embedded LaTeX fragment, let texmathp do its job.
13948 \\[org-cdlatex-mode-map]"
13949 (interactive)
13950 (let (p)
13951 (cond
13952 ((not (org-mode-p)) ad-do-it)
13953 ((eq this-command 'cdlatex-math-symbol)
13954 (setq ad-return-value t
13955 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13957 (let ((p (org-inside-LaTeX-fragment-p)))
13958 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13959 (setq ad-return-value t
13960 texmathp-why '("Org-mode embedded math" . 0))
13961 (if p ad-do-it)))))))))
13963 (defun turn-on-org-cdlatex ()
13964 "Unconditionally turn on `org-cdlatex-mode'."
13965 (org-cdlatex-mode 1))
13967 (defun org-inside-LaTeX-fragment-p ()
13968 "Test if point is inside a LaTeX fragment.
13969 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13970 sequence appearing also before point.
13971 Even though the matchers for math are configurable, this function assumes
13972 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13973 delimiters are skipped when they have been removed by customization.
13974 The return value is nil, or a cons cell with the delimiter and
13975 and the position of this delimiter.
13977 This function does a reasonably good job, but can locally be fooled by
13978 for example currency specifications. For example it will assume being in
13979 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13980 fragments that are properly closed, but during editing, we have to live
13981 with the uncertainty caused by missing closing delimiters. This function
13982 looks only before point, not after."
13983 (catch 'exit
13984 (let ((pos (point))
13985 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13986 (lim (progn
13987 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13988 (point)))
13989 dd-on str (start 0) m re)
13990 (goto-char pos)
13991 (when dodollar
13992 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13993 re (nth 1 (assoc "$" org-latex-regexps)))
13994 (while (string-match re str start)
13995 (cond
13996 ((= (match-end 0) (length str))
13997 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13998 ((= (match-end 0) (- (length str) 5))
13999 (throw 'exit nil))
14000 (t (setq start (match-end 0))))))
14001 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14002 (goto-char pos)
14003 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14004 (and (match-beginning 2) (throw 'exit nil))
14005 ;; count $$
14006 (while (re-search-backward "\\$\\$" lim t)
14007 (setq dd-on (not dd-on)))
14008 (goto-char pos)
14009 (if dd-on (cons "$$" m))))))
14012 (defun org-try-cdlatex-tab ()
14013 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14014 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14015 - inside a LaTeX fragment, or
14016 - after the first word in a line, where an abbreviation expansion could
14017 insert a LaTeX environment."
14018 (when org-cdlatex-mode
14019 (cond
14020 ((save-excursion
14021 (skip-chars-backward "a-zA-Z0-9*")
14022 (skip-chars-backward " \t")
14023 (bolp))
14024 (cdlatex-tab) t)
14025 ((org-inside-LaTeX-fragment-p)
14026 (cdlatex-tab) t)
14027 (t nil))))
14029 (defun org-cdlatex-underscore-caret (&optional arg)
14030 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14031 Revert to the normal definition outside of these fragments."
14032 (interactive "P")
14033 (if (org-inside-LaTeX-fragment-p)
14034 (call-interactively 'cdlatex-sub-superscript)
14035 (let (org-cdlatex-mode)
14036 (call-interactively (key-binding (vector last-input-event))))))
14038 (defun org-cdlatex-math-modify (&optional arg)
14039 "Execute `cdlatex-math-modify' in LaTeX fragments.
14040 Revert to the normal definition outside of these fragments."
14041 (interactive "P")
14042 (if (org-inside-LaTeX-fragment-p)
14043 (call-interactively 'cdlatex-math-modify)
14044 (let (org-cdlatex-mode)
14045 (call-interactively (key-binding (vector last-input-event))))))
14047 (defvar org-latex-fragment-image-overlays nil
14048 "List of overlays carrying the images of latex fragments.")
14049 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14051 (defun org-remove-latex-fragment-image-overlays ()
14052 "Remove all overlays with LaTeX fragment images in current buffer."
14053 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14054 (setq org-latex-fragment-image-overlays nil))
14056 (defun org-preview-latex-fragment (&optional subtree)
14057 "Preview the LaTeX fragment at point, or all locally or globally.
14058 If the cursor is in a LaTeX fragment, create the image and overlay
14059 it over the source code. If there is no fragment at point, display
14060 all fragments in the current text, from one headline to the next. With
14061 prefix SUBTREE, display all fragments in the current subtree. With a
14062 double prefix `C-u C-u', or when the cursor is before the first headline,
14063 display all fragments in the buffer.
14064 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14065 (interactive "P")
14066 (org-remove-latex-fragment-image-overlays)
14067 (save-excursion
14068 (save-restriction
14069 (let (beg end at msg)
14070 (cond
14071 ((or (equal subtree '(16))
14072 (not (save-excursion
14073 (re-search-backward (concat "^" outline-regexp) nil t))))
14074 (setq beg (point-min) end (point-max)
14075 msg "Creating images for buffer...%s"))
14076 ((equal subtree '(4))
14077 (org-back-to-heading)
14078 (setq beg (point) end (org-end-of-subtree t)
14079 msg "Creating images for subtree...%s"))
14081 (if (setq at (org-inside-LaTeX-fragment-p))
14082 (goto-char (max (point-min) (- (cdr at) 2)))
14083 (org-back-to-heading))
14084 (setq beg (point) end (progn (outline-next-heading) (point))
14085 msg (if at "Creating image...%s"
14086 "Creating images for entry...%s"))))
14087 (message msg "")
14088 (narrow-to-region beg end)
14089 (goto-char beg)
14090 (org-format-latex
14091 (concat "ltxpng/" (file-name-sans-extension
14092 (file-name-nondirectory
14093 buffer-file-name)))
14094 default-directory 'overlays msg at 'forbuffer)
14095 (message msg "done. Use `C-c C-c' to remove images.")))))
14097 (defvar org-latex-regexps
14098 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14099 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14100 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14101 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14102 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14103 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14104 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14105 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14106 "Regular expressions for matching embedded LaTeX.")
14108 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14109 "Replace LaTeX fragments with links to an image, and produce images."
14110 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14111 (let* ((prefixnodir (file-name-nondirectory prefix))
14112 (absprefix (expand-file-name prefix dir))
14113 (todir (file-name-directory absprefix))
14114 (opt org-format-latex-options)
14115 (matchers (plist-get opt :matchers))
14116 (re-list org-latex-regexps)
14117 (cnt 0) txt link beg end re e checkdir
14118 executables-checked
14119 m n block linkfile movefile ov)
14120 ;; Check if there are old images files with this prefix, and remove them
14121 (when (file-directory-p todir)
14122 (mapc 'delete-file
14123 (directory-files
14124 todir 'full
14125 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14126 ;; Check the different regular expressions
14127 (while (setq e (pop re-list))
14128 (setq m (car e) re (nth 1 e) n (nth 2 e)
14129 block (if (nth 3 e) "\n\n" ""))
14130 (when (member m matchers)
14131 (goto-char (point-min))
14132 (while (re-search-forward re nil t)
14133 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14134 (not (get-text-property (match-beginning n)
14135 'org-protected))
14136 (or (not overlays)
14137 (not (eq (get-char-property (match-beginning n)
14138 'org-overlay-type)
14139 'org-latex-overlay))))
14140 (setq txt (match-string n)
14141 beg (match-beginning n) end (match-end n)
14142 cnt (1+ cnt)
14143 linkfile (format "%s_%04d.png" prefix cnt)
14144 movefile (format "%s_%04d.png" absprefix cnt)
14145 link (concat block "[[file:" linkfile "]]" block))
14146 (if msg (message msg cnt))
14147 (goto-char beg)
14148 (unless checkdir ; make sure the directory exists
14149 (setq checkdir t)
14150 (or (file-directory-p todir) (make-directory todir)))
14152 (unless executables-checked
14153 (org-check-external-command
14154 "latex" "needed to convert LaTeX fragments to images")
14155 (org-check-external-command
14156 "dvipng" "needed to convert LaTeX fragments to images")
14157 (setq executables-checked t))
14159 (org-create-formula-image
14160 txt movefile opt forbuffer)
14161 (if overlays
14162 (progn
14163 (mapc (lambda (o)
14164 (if (eq (org-overlay-get o 'org-overlay-type)
14165 'org-latex-overlay)
14166 (org-delete-overlay o)))
14167 (org-overlays-in beg end))
14168 (setq ov (org-make-overlay beg end))
14169 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14170 (if (featurep 'xemacs)
14171 (progn
14172 (org-overlay-put ov 'invisible t)
14173 (org-overlay-put
14174 ov 'end-glyph
14175 (make-glyph (vector 'png :file movefile))))
14176 (org-overlay-put
14177 ov 'display
14178 (list 'image :type 'png :file movefile :ascent 'center)))
14179 (push ov org-latex-fragment-image-overlays)
14180 (goto-char end))
14181 (delete-region beg end)
14182 (insert link))))))))
14184 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14185 ;; This function borrows from Ganesh Swami's latex2png.el
14186 (defun org-create-formula-image (string tofile options buffer)
14187 (require 'org-latex)
14188 (let* ((tmpdir (if (featurep 'xemacs)
14189 (temp-directory)
14190 temporary-file-directory))
14191 (texfilebase (make-temp-name
14192 (expand-file-name "orgtex" tmpdir)))
14193 (texfile (concat texfilebase ".tex"))
14194 (dvifile (concat texfilebase ".dvi"))
14195 (pngfile (concat texfilebase ".png"))
14196 (fnh (if (featurep 'xemacs)
14197 (font-height (get-face-font 'default))
14198 (face-attribute 'default :height nil)))
14199 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14200 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14201 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14202 "Black"))
14203 (bg (or (plist-get options (if buffer :background :html-background))
14204 "Transparent")))
14205 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14206 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14207 (with-temp-file texfile
14208 (insert org-format-latex-header
14209 (if org-export-latex-packages-alist
14210 (concat "\n"
14211 (mapconcat (lambda(p)
14212 (if (equal "" (car p))
14213 (format "\\usepackage{%s}" (cadr p))
14214 (format "\\usepackage[%s]{%s}"
14215 (car p) (cadr p))))
14216 org-export-latex-packages-alist "\n"))
14218 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14219 (let ((dir default-directory))
14220 (condition-case nil
14221 (progn
14222 (cd tmpdir)
14223 (call-process "latex" nil nil nil texfile))
14224 (error nil))
14225 (cd dir))
14226 (if (not (file-exists-p dvifile))
14227 (progn (message "Failed to create dvi file from %s" texfile) nil)
14228 (condition-case nil
14229 (call-process "dvipng" nil nil nil
14230 "-fg" fg "-bg" bg
14231 "-D" dpi
14232 ;;"-x" scale "-y" scale
14233 "-T" "tight"
14234 "-o" pngfile
14235 dvifile)
14236 (error nil))
14237 (if (not (file-exists-p pngfile))
14238 (progn (message "Failed to create png file from %s" texfile) nil)
14239 ;; Use the requested file name and clean up
14240 (copy-file pngfile tofile 'replace)
14241 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14242 (delete-file (concat texfilebase e)))
14243 pngfile))))
14245 (defun org-dvipng-color (attr)
14246 "Return an rgb color specification for dvipng."
14247 (apply 'format "rgb %s %s %s"
14248 (mapcar 'org-normalize-color
14249 (color-values (face-attribute 'default attr nil)))))
14251 (defun org-normalize-color (value)
14252 "Return string to be used as color value for an RGB component."
14253 (format "%g" (/ value 65535.0)))
14255 ;;;; Key bindings
14257 ;; Make `C-c C-x' a prefix key
14258 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14260 ;; TAB key with modifiers
14261 (org-defkey org-mode-map "\C-i" 'org-cycle)
14262 (org-defkey org-mode-map [(tab)] 'org-cycle)
14263 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14264 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14265 (org-defkey org-mode-map "\M-\t" 'org-complete)
14266 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14267 ;; The following line is necessary under Suse GNU/Linux
14268 (unless (featurep 'xemacs)
14269 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14270 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14271 (define-key org-mode-map [backtab] 'org-shifttab)
14273 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14274 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14275 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14277 ;; Cursor keys with modifiers
14278 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14279 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14280 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14281 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14283 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14284 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14285 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14286 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14288 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14289 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14290 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14291 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14293 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14294 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14296 ;;; Extra keys for tty access.
14297 ;; We only set them when really needed because otherwise the
14298 ;; menus don't show the simple keys
14300 (when (or org-use-extra-keys
14301 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14302 (not window-system))
14303 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14304 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14305 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14306 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14307 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14308 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14309 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14310 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14311 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14312 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14313 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14314 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14315 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14316 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14317 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14318 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14319 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14320 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14321 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14322 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14323 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14324 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14325 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14326 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14327 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14328 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14329 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14330 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14332 ;; All the other keys
14334 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14335 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14336 (if (boundp 'narrow-map)
14337 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14338 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14339 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14340 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14341 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14342 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14343 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14344 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14345 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14346 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14347 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14348 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14349 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14350 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14351 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14352 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14353 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14354 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14355 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14356 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14357 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14358 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14359 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14360 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14361 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14362 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14363 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14364 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14365 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14366 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14367 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14368 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14369 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14370 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14371 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14372 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14373 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14374 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14375 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14376 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14377 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14378 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14379 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14380 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14381 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14382 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14383 (org-defkey org-mode-map "\C-c^" 'org-sort)
14384 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14385 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14386 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14387 (org-defkey org-mode-map "\C-m" 'org-return)
14388 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14389 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14390 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14391 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14392 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14393 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14394 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14395 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14396 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14397 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14398 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14399 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14400 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14401 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14402 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14403 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14404 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14405 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14406 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14407 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14408 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14410 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14411 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14412 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14413 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14415 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14416 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14417 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14418 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14419 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14420 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14421 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14422 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14423 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14424 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14425 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14426 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14427 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14428 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14429 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14431 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14432 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14433 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14434 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14436 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14438 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14440 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14441 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14443 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14446 (when (featurep 'xemacs)
14447 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14450 (defvar org-self-insert-command-undo-counter 0)
14452 (defvar org-table-auto-blank-field) ; defined in org-table.el
14453 (defun org-self-insert-command (N)
14454 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14455 If the cursor is in a table looking at whitespace, the whitespace is
14456 overwritten, and the table is not marked as requiring realignment."
14457 (interactive "p")
14458 (if (and
14459 (org-table-p)
14460 (progn
14461 ;; check if we blank the field, and if that triggers align
14462 (and (featurep 'org-table) org-table-auto-blank-field
14463 (member last-command
14464 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14465 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14466 ;; got extra space, this field does not determine column width
14467 (let (org-table-may-need-update) (org-table-blank-field))
14468 ;; no extra space, this field may determine column width
14469 (org-table-blank-field)))
14471 (eq N 1)
14472 (looking-at "[^|\n]* |"))
14473 (let (org-table-may-need-update)
14474 (goto-char (1- (match-end 0)))
14475 (delete-backward-char 1)
14476 (goto-char (match-beginning 0))
14477 (self-insert-command N))
14478 (setq org-table-may-need-update t)
14479 (self-insert-command N)
14480 (org-fix-tags-on-the-fly)
14481 (if org-self-insert-cluster-for-undo
14482 (if (not (eq last-command 'org-self-insert-command))
14483 (setq org-self-insert-command-undo-counter 1)
14484 (if (>= org-self-insert-command-undo-counter 20)
14485 (setq org-self-insert-command-undo-counter 1)
14486 (and (> org-self-insert-command-undo-counter 0)
14487 buffer-undo-list
14488 (not (cadr buffer-undo-list)) ; remove nil entry
14489 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14490 (setq org-self-insert-command-undo-counter
14491 (1+ org-self-insert-command-undo-counter)))))))
14493 (defun org-fix-tags-on-the-fly ()
14494 (when (and (equal (char-after (point-at-bol)) ?*)
14495 (org-on-heading-p))
14496 (org-align-tags-here org-tags-column)))
14498 (defun org-delete-backward-char (N)
14499 "Like `delete-backward-char', insert whitespace at field end in tables.
14500 When deleting backwards, in tables this function will insert whitespace in
14501 front of the next \"|\" separator, to keep the table aligned. The table will
14502 still be marked for re-alignment if the field did fill the entire column,
14503 because, in this case the deletion might narrow the column."
14504 (interactive "p")
14505 (if (and (org-table-p)
14506 (eq N 1)
14507 (string-match "|" (buffer-substring (point-at-bol) (point)))
14508 (looking-at ".*?|"))
14509 (let ((pos (point))
14510 (noalign (looking-at "[^|\n\r]* |"))
14511 (c org-table-may-need-update))
14512 (backward-delete-char N)
14513 (skip-chars-forward "^|")
14514 (insert " ")
14515 (goto-char (1- pos))
14516 ;; noalign: if there were two spaces at the end, this field
14517 ;; does not determine the width of the column.
14518 (if noalign (setq org-table-may-need-update c)))
14519 (backward-delete-char N)
14520 (org-fix-tags-on-the-fly)))
14522 (defun org-delete-char (N)
14523 "Like `delete-char', but insert whitespace at field end in tables.
14524 When deleting characters, in tables this function will insert whitespace in
14525 front of the next \"|\" separator, to keep the table aligned. The table will
14526 still be marked for re-alignment if the field did fill the entire column,
14527 because, in this case the deletion might narrow the column."
14528 (interactive "p")
14529 (if (and (org-table-p)
14530 (not (bolp))
14531 (not (= (char-after) ?|))
14532 (eq N 1))
14533 (if (looking-at ".*?|")
14534 (let ((pos (point))
14535 (noalign (looking-at "[^|\n\r]* |"))
14536 (c org-table-may-need-update))
14537 (replace-match (concat
14538 (substring (match-string 0) 1 -1)
14539 " |"))
14540 (goto-char pos)
14541 ;; noalign: if there were two spaces at the end, this field
14542 ;; does not determine the width of the column.
14543 (if noalign (setq org-table-may-need-update c)))
14544 (delete-char N))
14545 (delete-char N)
14546 (org-fix-tags-on-the-fly)))
14548 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14549 (put 'org-self-insert-command 'delete-selection t)
14550 (put 'orgtbl-self-insert-command 'delete-selection t)
14551 (put 'org-delete-char 'delete-selection 'supersede)
14552 (put 'org-delete-backward-char 'delete-selection 'supersede)
14553 (put 'org-yank 'delete-selection 'yank)
14555 ;; Make `flyspell-mode' delay after some commands
14556 (put 'org-self-insert-command 'flyspell-delayed t)
14557 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14558 (put 'org-delete-char 'flyspell-delayed t)
14559 (put 'org-delete-backward-char 'flyspell-delayed t)
14561 ;; Make pabbrev-mode expand after org-mode commands
14562 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14563 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14565 ;; How to do this: Measure non-white length of current string
14566 ;; If equal to column width, we should realign.
14568 (defun org-remap (map &rest commands)
14569 "In MAP, remap the functions given in COMMANDS.
14570 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14571 (let (new old)
14572 (while commands
14573 (setq old (pop commands) new (pop commands))
14574 (if (fboundp 'command-remapping)
14575 (org-defkey map (vector 'remap old) new)
14576 (substitute-key-definition old new map global-map)))))
14578 (when (eq org-enable-table-editor 'optimized)
14579 ;; If the user wants maximum table support, we need to hijack
14580 ;; some standard editing functions
14581 (org-remap org-mode-map
14582 'self-insert-command 'org-self-insert-command
14583 'delete-char 'org-delete-char
14584 'delete-backward-char 'org-delete-backward-char)
14585 (org-defkey org-mode-map "|" 'org-force-self-insert))
14587 (defvar org-ctrl-c-ctrl-c-hook nil
14588 "Hook for functions attaching themselves to `C-c C-c'.
14589 This can be used to add additional functionality to the C-c C-c key which
14590 executes context-dependent commands.
14591 Each function will be called with no arguments. The function must check
14592 if the context is appropriate for it to act. If yes, it should do its
14593 thing and then return a non-nil value. If the context is wrong,
14594 just do nothing and return nil.")
14596 (defvar org-tab-first-hook nil
14597 "Hook for functions to attach themselves to TAB.
14598 See `org-ctrl-c-ctrl-c-hook' for more information.
14599 This hook runs as the first action when TAB is pressed, even before
14600 `org-cycle' messes around with the `outline-regexp' to cater for
14601 inline tasks and plain list item folding.
14602 If any function in this hook returns t, not other actions like table
14603 field motion visibility cycling will be done.")
14605 (defvar org-tab-after-check-for-table-hook nil
14606 "Hook for functions to attach themselves to TAB.
14607 See `org-ctrl-c-ctrl-c-hook' for more information.
14608 This hook runs after it has been established that the cursor is not in a
14609 table, but before checking if the cursor is in a headline or if global cycling
14610 should be done.
14611 If any function in this hook returns t, not other actions like visibility
14612 cycling will be done.")
14614 (defvar org-tab-after-check-for-cycling-hook nil
14615 "Hook for functions to attach themselves to TAB.
14616 See `org-ctrl-c-ctrl-c-hook' for more information.
14617 This hook runs after it has been established that not table field motion and
14618 not visibility should be done because of current context. This is probably
14619 the place where a package like yasnippets can hook in.")
14621 (defvar org-metaleft-hook nil
14622 "Hook for functions attaching themselves to `M-left'.
14623 See `org-ctrl-c-ctrl-c-hook' for more information.")
14624 (defvar org-metaright-hook nil
14625 "Hook for functions attaching themselves to `M-right'.
14626 See `org-ctrl-c-ctrl-c-hook' for more information.")
14627 (defvar org-metaup-hook nil
14628 "Hook for functions attaching themselves to `M-up'.
14629 See `org-ctrl-c-ctrl-c-hook' for more information.")
14630 (defvar org-metadown-hook nil
14631 "Hook for functions attaching themselves to `M-down'.
14632 See `org-ctrl-c-ctrl-c-hook' for more information.")
14633 (defvar org-shiftmetaleft-hook nil
14634 "Hook for functions attaching themselves to `M-S-left'.
14635 See `org-ctrl-c-ctrl-c-hook' for more information.")
14636 (defvar org-shiftmetaright-hook nil
14637 "Hook for functions attaching themselves to `M-S-right'.
14638 See `org-ctrl-c-ctrl-c-hook' for more information.")
14639 (defvar org-shiftmetaup-hook nil
14640 "Hook for functions attaching themselves to `M-S-up'.
14641 See `org-ctrl-c-ctrl-c-hook' for more information.")
14642 (defvar org-shiftmetadown-hook nil
14643 "Hook for functions attaching themselves to `M-S-down'.
14644 See `org-ctrl-c-ctrl-c-hook' for more information.")
14645 (defvar org-metareturn-hook nil
14646 "Hook for functions attaching themselves to `M-RET'.
14647 See `org-ctrl-c-ctrl-c-hook' for more information.")
14649 (defun org-modifier-cursor-error ()
14650 "Throw an error, a modified cursor command was applied in wrong context."
14651 (error "This command is active in special context like tables, headlines or items"))
14653 (defun org-shiftselect-error ()
14654 "Throw an error because Shift-Cursor command was applied in wrong context."
14655 (if (and (boundp 'shift-select-mode) shift-select-mode)
14656 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14657 (error "This command works only in special context like headlines or timestamps.")))
14659 (defun org-call-for-shift-select (cmd)
14660 (let ((this-command-keys-shift-translated t))
14661 (call-interactively cmd)))
14663 (defun org-shifttab (&optional arg)
14664 "Global visibility cycling or move to previous table field.
14665 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14666 on context.
14667 See the individual commands for more information."
14668 (interactive "P")
14669 (cond
14670 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14671 ((integerp arg)
14672 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
14673 (message "Content view to level: %d" arg)
14674 (org-content (prefix-numeric-value arg2))
14675 (setq org-cycle-global-status 'overview)))
14676 (t (call-interactively 'org-global-cycle))))
14678 (defun org-shiftmetaleft ()
14679 "Promote subtree or delete table column.
14680 Calls `org-promote-subtree', `org-outdent-item',
14681 or `org-table-delete-column', depending on context.
14682 See the individual commands for more information."
14683 (interactive)
14684 (cond
14685 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14686 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14687 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14688 ((org-at-item-p) (call-interactively 'org-outdent-item))
14689 (t (org-modifier-cursor-error))))
14691 (defun org-shiftmetaright ()
14692 "Demote subtree or insert table column.
14693 Calls `org-demote-subtree', `org-indent-item',
14694 or `org-table-insert-column', depending on context.
14695 See the individual commands for more information."
14696 (interactive)
14697 (cond
14698 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14699 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14700 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14701 ((org-at-item-p) (call-interactively 'org-indent-item))
14702 (t (org-modifier-cursor-error))))
14704 (defun org-shiftmetaup (&optional arg)
14705 "Move subtree up or kill table row.
14706 Calls `org-move-subtree-up' or `org-table-kill-row' or
14707 `org-move-item-up' depending on context. See the individual commands
14708 for more information."
14709 (interactive "P")
14710 (cond
14711 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14712 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14713 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14714 ((org-at-item-p) (call-interactively 'org-move-item-up))
14715 (t (org-modifier-cursor-error))))
14717 (defun org-shiftmetadown (&optional arg)
14718 "Move subtree down or insert table row.
14719 Calls `org-move-subtree-down' or `org-table-insert-row' or
14720 `org-move-item-down', depending on context. See the individual
14721 commands for more information."
14722 (interactive "P")
14723 (cond
14724 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14725 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14726 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14727 ((org-at-item-p) (call-interactively 'org-move-item-down))
14728 (t (org-modifier-cursor-error))))
14730 (defun org-metaleft (&optional arg)
14731 "Promote heading or move table column to left.
14732 Calls `org-do-promote' or `org-table-move-column', depending on context.
14733 With no specific context, calls the Emacs default `backward-word'.
14734 See the individual commands for more information."
14735 (interactive "P")
14736 (cond
14737 ((run-hook-with-args-until-success 'org-metaleft-hook))
14738 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14739 ((or (org-on-heading-p)
14740 (and (org-region-active-p)
14741 (save-excursion
14742 (goto-char (region-beginning))
14743 (org-on-heading-p))))
14744 (call-interactively 'org-do-promote))
14745 ((or (org-at-item-p)
14746 (and (org-region-active-p)
14747 (save-excursion
14748 (goto-char (region-beginning))
14749 (org-at-item-p))))
14750 (call-interactively 'org-outdent-item))
14751 (t (call-interactively 'backward-word))))
14753 (defun org-metaright (&optional arg)
14754 "Demote subtree or move table column to right.
14755 Calls `org-do-demote' or `org-table-move-column', depending on context.
14756 With no specific context, calls the Emacs default `forward-word'.
14757 See the individual commands for more information."
14758 (interactive "P")
14759 (cond
14760 ((run-hook-with-args-until-success 'org-metaright-hook))
14761 ((org-at-table-p) (call-interactively 'org-table-move-column))
14762 ((or (org-on-heading-p)
14763 (and (org-region-active-p)
14764 (save-excursion
14765 (goto-char (region-beginning))
14766 (org-on-heading-p))))
14767 (call-interactively 'org-do-demote))
14768 ((or (org-at-item-p)
14769 (and (org-region-active-p)
14770 (save-excursion
14771 (goto-char (region-beginning))
14772 (org-at-item-p))))
14773 (call-interactively 'org-indent-item))
14774 (t (call-interactively 'forward-word))))
14776 (defun org-metaup (&optional arg)
14777 "Move subtree up or move table row up.
14778 Calls `org-move-subtree-up' or `org-table-move-row' or
14779 `org-move-item-up', depending on context. See the individual commands
14780 for more information."
14781 (interactive "P")
14782 (cond
14783 ((run-hook-with-args-until-success 'org-metaup-hook))
14784 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14785 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14786 ((org-at-item-p) (call-interactively 'org-move-item-up))
14787 (t (transpose-lines 1) (beginning-of-line -1))))
14789 (defun org-metadown (&optional arg)
14790 "Move subtree down or move table row down.
14791 Calls `org-move-subtree-down' or `org-table-move-row' or
14792 `org-move-item-down', depending on context. See the individual
14793 commands for more information."
14794 (interactive "P")
14795 (cond
14796 ((run-hook-with-args-until-success 'org-metadown-hook))
14797 ((org-at-table-p) (call-interactively 'org-table-move-row))
14798 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14799 ((org-at-item-p) (call-interactively 'org-move-item-down))
14800 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14802 (defun org-shiftup (&optional arg)
14803 "Increase item in timestamp or increase priority of current headline.
14804 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14805 depending on context. See the individual commands for more information."
14806 (interactive "P")
14807 (cond
14808 ((and org-support-shift-select (org-region-active-p))
14809 (org-call-for-shift-select 'previous-line))
14810 ((org-at-timestamp-p t)
14811 (call-interactively (if org-edit-timestamp-down-means-later
14812 'org-timestamp-down 'org-timestamp-up)))
14813 ((and (not (eq org-support-shift-select 'always))
14814 org-enable-priority-commands
14815 (org-on-heading-p))
14816 (call-interactively 'org-priority-up))
14817 ((and (not org-support-shift-select) (org-at-item-p))
14818 (call-interactively 'org-previous-item))
14819 ((org-clocktable-try-shift 'up arg))
14820 (org-support-shift-select
14821 (org-call-for-shift-select 'previous-line))
14822 (t (org-shiftselect-error))))
14824 (defun org-shiftdown (&optional arg)
14825 "Decrease item in timestamp or decrease priority of current headline.
14826 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14827 depending on context. See the individual commands for more information."
14828 (interactive "P")
14829 (cond
14830 ((and org-support-shift-select (org-region-active-p))
14831 (org-call-for-shift-select 'next-line))
14832 ((org-at-timestamp-p t)
14833 (call-interactively (if org-edit-timestamp-down-means-later
14834 'org-timestamp-up 'org-timestamp-down)))
14835 ((and (not (eq org-support-shift-select 'always))
14836 org-enable-priority-commands
14837 (org-on-heading-p))
14838 (call-interactively 'org-priority-down))
14839 ((and (not org-support-shift-select) (org-at-item-p))
14840 (call-interactively 'org-next-item))
14841 ((org-clocktable-try-shift 'down arg))
14842 (org-support-shift-select
14843 (org-call-for-shift-select 'next-line))
14844 (t (org-shiftselect-error))))
14846 (defun org-shiftright (&optional arg)
14847 "Cycle the thing at point or in the current line, depending on context.
14848 Depending on context, this does one of the following:
14850 - switch a timestamp at point one day into the future
14851 - on a headline, switch to the next TODO keyword.
14852 - on an item, switch entire list to the next bullet type
14853 - on a property line, switch to the next allowed value
14854 - on a clocktable definition line, move time block into the future"
14855 (interactive "P")
14856 (cond
14857 ((and org-support-shift-select (org-region-active-p))
14858 (org-call-for-shift-select 'forward-char))
14859 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14860 ((and (not (eq org-support-shift-select 'always))
14861 (org-on-heading-p))
14862 (let ((org-inhibit-logging
14863 (not org-treat-S-cursor-todo-selection-as-state-change))
14864 (org-inhibit-blocking
14865 (not org-treat-S-cursor-todo-selection-as-state-change)))
14866 (org-call-with-arg 'org-todo 'right)))
14867 ((or (and org-support-shift-select
14868 (not (eq org-support-shift-select 'always))
14869 (org-at-item-bullet-p))
14870 (and (not org-support-shift-select) (org-at-item-p)))
14871 (org-call-with-arg 'org-cycle-list-bullet nil))
14872 ((and (not (eq org-support-shift-select 'always))
14873 (org-at-property-p))
14874 (call-interactively 'org-property-next-allowed-value))
14875 ((org-clocktable-try-shift 'right arg))
14876 (org-support-shift-select
14877 (org-call-for-shift-select 'forward-char))
14878 (t (org-shiftselect-error))))
14880 (defun org-shiftleft (&optional arg)
14881 "Cycle the thing at point or in the current line, depending on context.
14882 Depending on context, this does one of the following:
14884 - switch a timestamp at point one day into the past
14885 - on a headline, switch to the previous TODO keyword.
14886 - on an item, switch entire list to the previous bullet type
14887 - on a property line, switch to the previous allowed value
14888 - on a clocktable definition line, move time block into the past"
14889 (interactive "P")
14890 (cond
14891 ((and org-support-shift-select (org-region-active-p))
14892 (org-call-for-shift-select 'backward-char))
14893 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14894 ((and (not (eq org-support-shift-select 'always))
14895 (org-on-heading-p))
14896 (let ((org-inhibit-logging
14897 (not org-treat-S-cursor-todo-selection-as-state-change))
14898 (org-inhibit-blocking
14899 (not org-treat-S-cursor-todo-selection-as-state-change)))
14900 (org-call-with-arg 'org-todo 'left)))
14901 ((or (and org-support-shift-select
14902 (not (eq org-support-shift-select 'always))
14903 (org-at-item-bullet-p))
14904 (and (not org-support-shift-select) (org-at-item-p)))
14905 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14906 ((and (not (eq org-support-shift-select 'always))
14907 (org-at-property-p))
14908 (call-interactively 'org-property-previous-allowed-value))
14909 ((org-clocktable-try-shift 'left arg))
14910 (org-support-shift-select
14911 (org-call-for-shift-select 'backward-char))
14912 (t (org-shiftselect-error))))
14914 (defun org-shiftcontrolright ()
14915 "Switch to next TODO set."
14916 (interactive)
14917 (cond
14918 ((and org-support-shift-select (org-region-active-p))
14919 (org-call-for-shift-select 'forward-word))
14920 ((and (not (eq org-support-shift-select 'always))
14921 (org-on-heading-p))
14922 (org-call-with-arg 'org-todo 'nextset))
14923 (org-support-shift-select
14924 (org-call-for-shift-select 'forward-word))
14925 (t (org-shiftselect-error))))
14927 (defun org-shiftcontrolleft ()
14928 "Switch to previous TODO set."
14929 (interactive)
14930 (cond
14931 ((and org-support-shift-select (org-region-active-p))
14932 (org-call-for-shift-select 'backward-word))
14933 ((and (not (eq org-support-shift-select 'always))
14934 (org-on-heading-p))
14935 (org-call-with-arg 'org-todo 'previousset))
14936 (org-support-shift-select
14937 (org-call-for-shift-select 'backward-word))
14938 (t (org-shiftselect-error))))
14940 (defun org-ctrl-c-ret ()
14941 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14942 (interactive)
14943 (cond
14944 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14945 (t (call-interactively 'org-insert-heading))))
14947 (defun org-copy-special ()
14948 "Copy region in table or copy current subtree.
14949 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14950 See the individual commands for more information."
14951 (interactive)
14952 (call-interactively
14953 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14955 (defun org-cut-special ()
14956 "Cut region in table or cut current subtree.
14957 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14958 See the individual commands for more information."
14959 (interactive)
14960 (call-interactively
14961 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14963 (defun org-paste-special (arg)
14964 "Paste rectangular region into table, or past subtree relative to level.
14965 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14966 See the individual commands for more information."
14967 (interactive "P")
14968 (if (org-at-table-p)
14969 (org-table-paste-rectangle)
14970 (org-paste-subtree arg)))
14972 (defun org-edit-special ()
14973 "Call a special editor for the stuff at point.
14974 When at a table, call the formula editor with `org-table-edit-formulas'.
14975 When at the first line of an src example, call `org-edit-src-code'.
14976 When in an #+include line, visit the include file. Otherwise call
14977 `ffap' to visit the file at point."
14978 (interactive)
14979 (cond
14980 ((org-at-table-p)
14981 (call-interactively 'org-table-edit-formulas))
14982 ((save-excursion
14983 (beginning-of-line 1)
14984 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14985 (find-file (org-trim (match-string 1))))
14986 ((org-edit-src-code))
14987 ((org-edit-fixed-width-region))
14988 (t (call-interactively 'ffap))))
14991 (defun org-ctrl-c-ctrl-c (&optional arg)
14992 "Set tags in headline, or update according to changed information at point.
14994 This command does many different things, depending on context:
14996 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14997 this is what we do.
14999 - If the cursor is on a statistics cookie, update it.
15001 - If the cursor is in a headline, prompt for tags and insert them
15002 into the current line, aligned to `org-tags-column'. When called
15003 with prefix arg, realign all tags in the current buffer.
15005 - If the cursor is in one of the special #+KEYWORD lines, this
15006 triggers scanning the buffer for these lines and updating the
15007 information.
15009 - If the cursor is inside a table, realign the table. This command
15010 works even if the automatic table editor has been turned off.
15012 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15013 the entire table.
15015 - If the cursor is at a footnote reference or definition, jump to
15016 the corresponding definition or references, respectively.
15018 - If the cursor is a the beginning of a dynamic block, update it.
15020 - If the cursor is inside a table created by the table.el package,
15021 activate that table.
15023 - If the current buffer is a remember buffer, close note and file
15024 it. A prefix argument of 1 files to the default location
15025 without further interaction. A prefix argument of 2 files to
15026 the currently clocking task.
15028 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15029 links in this buffer.
15031 - If the cursor is on a numbered item in a plain list, renumber the
15032 ordered list.
15034 - If the cursor is on a checkbox, toggle it."
15035 (interactive "P")
15036 (let ((org-enable-table-editor t))
15037 (cond
15038 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15039 org-occur-highlights
15040 org-latex-fragment-image-overlays)
15041 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15042 (org-remove-occur-highlights)
15043 (org-remove-latex-fragment-image-overlays)
15044 (message "Temporary highlights/overlays removed from current buffer"))
15045 ((and (local-variable-p 'org-finish-function (current-buffer))
15046 (fboundp org-finish-function))
15047 (funcall org-finish-function))
15048 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15049 ((org-at-property-p)
15050 (call-interactively 'org-property-action))
15051 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15052 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15053 (or (org-on-heading-p) (org-at-item-p)))
15054 (call-interactively 'org-update-statistics-cookies))
15055 ((org-on-heading-p) (call-interactively 'org-set-tags))
15056 ((org-at-table.el-p)
15057 (require 'table)
15058 (beginning-of-line 1)
15059 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15060 (call-interactively 'table-recognize-table))
15061 ((org-at-table-p)
15062 (org-table-maybe-eval-formula)
15063 (if arg
15064 (call-interactively 'org-table-recalculate)
15065 (org-table-maybe-recalculate-line))
15066 (call-interactively 'org-table-align))
15067 ((or (org-footnote-at-reference-p)
15068 (org-footnote-at-definition-p))
15069 (call-interactively 'org-footnote-action))
15070 ((org-at-item-checkbox-p)
15071 (call-interactively 'org-toggle-checkbox))
15072 ((org-at-item-p)
15073 (if arg
15074 (call-interactively 'org-toggle-checkbox)
15075 (call-interactively 'org-maybe-renumber-ordered-list)))
15076 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15077 ;; Dynamic block
15078 (beginning-of-line 1)
15079 (save-excursion (org-update-dblock)))
15080 ((save-excursion
15081 (beginning-of-line 1)
15082 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15083 (cond
15084 ((equal (match-string 1) "TBLFM")
15085 ;; Recalculate the table before this line
15086 (save-excursion
15087 (beginning-of-line 1)
15088 (skip-chars-backward " \r\n\t")
15089 (if (org-at-table-p)
15090 (org-call-with-arg 'org-table-recalculate t))))
15092 ; (org-set-regexps-and-options)
15093 ; (org-restart-font-lock)
15094 (let ((org-inhibit-startup t)) (org-mode-restart))
15095 (message "Local setup has been refreshed"))))
15096 ((org-clock-update-time-maybe))
15097 (t (error "C-c C-c can do nothing useful at this location.")))))
15099 (defun org-mode-restart ()
15100 "Restart Org-mode, to scan again for special lines.
15101 Also updates the keyword regular expressions."
15102 (interactive)
15103 (org-mode)
15104 (message "Org-mode restarted"))
15106 (defun org-kill-note-or-show-branches ()
15107 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15108 (interactive)
15109 (if (not org-finish-function)
15110 (call-interactively 'show-branches)
15111 (let ((org-note-abort t))
15112 (funcall org-finish-function))))
15114 (defun org-return (&optional indent)
15115 "Goto next table row or insert a newline.
15116 Calls `org-table-next-row' or `newline', depending on context.
15117 See the individual commands for more information."
15118 (interactive)
15119 (cond
15120 ((bobp) (if indent (newline-and-indent) (newline)))
15121 ((org-at-table-p)
15122 (org-table-justify-field-maybe)
15123 (call-interactively 'org-table-next-row))
15124 ((and org-return-follows-link
15125 (eq (get-text-property (point) 'face) 'org-link))
15126 (call-interactively 'org-open-at-point))
15127 ((and (org-at-heading-p)
15128 (looking-at
15129 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15130 (org-show-entry)
15131 (end-of-line 1)
15132 (newline))
15133 (t (if indent (newline-and-indent) (newline)))))
15135 (defun org-return-indent ()
15136 "Goto next table row or insert a newline and indent.
15137 Calls `org-table-next-row' or `newline-and-indent', depending on
15138 context. See the individual commands for more information."
15139 (interactive)
15140 (org-return t))
15142 (defun org-ctrl-c-star ()
15143 "Compute table, or change heading status of lines.
15144 Calls `org-table-recalculate' or `org-toggle-heading',
15145 depending on context."
15146 (interactive)
15147 (cond
15148 ((org-at-table-p)
15149 (call-interactively 'org-table-recalculate))
15151 ;; Convert all lines in region to list items
15152 (call-interactively 'org-toggle-heading))))
15154 (defun org-ctrl-c-minus ()
15155 "Insert separator line in table or modify bullet status of line.
15156 Also turns a plain line or a region of lines into list items.
15157 Calls `org-table-insert-hline', `org-toggle-item', or
15158 `org-cycle-list-bullet', depending on context."
15159 (interactive)
15160 (cond
15161 ((org-at-table-p)
15162 (call-interactively 'org-table-insert-hline))
15163 ((org-region-active-p)
15164 (call-interactively 'org-toggle-item))
15165 ((org-in-item-p)
15166 (call-interactively 'org-cycle-list-bullet))
15168 (call-interactively 'org-toggle-item))))
15170 (defun org-toggle-item ()
15171 "Convert headings or normal lines to items, items to normal lines.
15172 If there is no active region, only the current line is considered.
15174 If the first line in the region is a headline, convert all headlines to items.
15176 If the first line in the region is an item, convert all items to normal lines.
15178 If the first line is normal text, add an item bullet to each line."
15179 (interactive)
15180 (let (l2 l beg end)
15181 (if (org-region-active-p)
15182 (setq beg (region-beginning) end (region-end))
15183 (setq beg (point-at-bol)
15184 end (min (1+ (point-at-eol)) (point-max))))
15185 (save-excursion
15186 (goto-char end)
15187 (setq l2 (org-current-line))
15188 (goto-char beg)
15189 (beginning-of-line 1)
15190 (setq l (1- (org-current-line)))
15191 (if (org-at-item-p)
15192 ;; We already have items, de-itemize
15193 (while (< (setq l (1+ l)) l2)
15194 (when (org-at-item-p)
15195 (goto-char (match-beginning 2))
15196 (delete-region (match-beginning 2) (match-end 2))
15197 (and (looking-at "[ \t]+") (replace-match "")))
15198 (beginning-of-line 2))
15199 (if (org-on-heading-p)
15200 ;; Headings, convert to items
15201 (while (< (setq l (1+ l)) l2)
15202 (if (looking-at org-outline-regexp)
15203 (replace-match "- " t t))
15204 (beginning-of-line 2))
15205 ;; normal lines, turn them into items
15206 (while (< (setq l (1+ l)) l2)
15207 (unless (org-at-item-p)
15208 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15209 (replace-match "\\1- \\2")))
15210 (beginning-of-line 2)))))))
15212 (defun org-toggle-heading (&optional nstars)
15213 "Convert headings to normal text, or items or text to headings.
15214 If there is no active region, only the current line is considered.
15216 If the first line is a heading, remove the stars from all headlines
15217 in the region.
15219 If the first line is a plain list item, turn all plain list items
15220 into headings.
15222 If the first line is a normal line, turn each and every line in the
15223 region into a heading.
15225 When converting a line into a heading, the number of stars is chosen
15226 such that the lines become children of the current entry. However,
15227 when a prefix argument is given, its value determines the number of
15228 stars to add."
15229 (interactive "P")
15230 (let (l2 l itemp beg end)
15231 (if (org-region-active-p)
15232 (setq beg (region-beginning) end (region-end))
15233 (setq beg (point-at-bol)
15234 end (min (1+ (point-at-eol)) (point-max))))
15235 (save-excursion
15236 (goto-char end)
15237 (setq l2 (org-current-line))
15238 (goto-char beg)
15239 (beginning-of-line 1)
15240 (setq l (1- (org-current-line)))
15241 (if (org-on-heading-p)
15242 ;; We already have headlines, de-star them
15243 (while (< (setq l (1+ l)) l2)
15244 (when (org-on-heading-p t)
15245 (and (looking-at outline-regexp) (replace-match "")))
15246 (beginning-of-line 2))
15247 (setq itemp (org-at-item-p))
15248 (let* ((stars
15249 (if nstars
15250 (make-string (prefix-numeric-value current-prefix-arg)
15252 (save-excursion
15253 (if (re-search-backward org-complex-heading-regexp nil t)
15254 (match-string 1) ""))))
15255 (add-stars (cond (nstars "")
15256 ((equal stars "") "*")
15257 (org-odd-levels-only "**")
15258 (t "*")))
15259 (rpl (concat stars add-stars " ")))
15260 (while (< (setq l (1+ l)) l2)
15261 (if itemp
15262 (and (org-at-item-p) (replace-match rpl t t))
15263 (unless (org-on-heading-p)
15264 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15265 (replace-match (concat rpl (match-string 2))))))
15266 (beginning-of-line 2)))))))
15268 (defun org-meta-return (&optional arg)
15269 "Insert a new heading or wrap a region in a table.
15270 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15271 See the individual commands for more information."
15272 (interactive "P")
15273 (cond
15274 ((run-hook-with-args-until-success 'org-metareturn-hook))
15275 ((org-at-table-p)
15276 (call-interactively 'org-table-wrap-region))
15277 (t (call-interactively 'org-insert-heading))))
15279 ;;; Menu entries
15281 ;; Define the Org-mode menus
15282 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15283 '("Tbl"
15284 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15285 ["Next Field" org-cycle (org-at-table-p)]
15286 ["Previous Field" org-shifttab (org-at-table-p)]
15287 ["Next Row" org-return (org-at-table-p)]
15288 "--"
15289 ["Blank Field" org-table-blank-field (org-at-table-p)]
15290 ["Edit Field" org-table-edit-field (org-at-table-p)]
15291 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15292 "--"
15293 ("Column"
15294 ["Move Column Left" org-metaleft (org-at-table-p)]
15295 ["Move Column Right" org-metaright (org-at-table-p)]
15296 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15297 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15298 ("Row"
15299 ["Move Row Up" org-metaup (org-at-table-p)]
15300 ["Move Row Down" org-metadown (org-at-table-p)]
15301 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15302 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15303 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15304 "--"
15305 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15306 ("Rectangle"
15307 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15308 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15309 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15310 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15311 "--"
15312 ("Calculate"
15313 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15314 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15315 ["Edit Formulas" org-edit-special (org-at-table-p)]
15316 "--"
15317 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15318 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15319 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15320 "--"
15321 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15322 "--"
15323 ["Sum Column/Rectangle" org-table-sum
15324 (or (org-at-table-p) (org-region-active-p))]
15325 ["Which Column?" org-table-current-column (org-at-table-p)])
15326 ["Debug Formulas"
15327 org-table-toggle-formula-debugger
15328 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15329 ["Show Col/Row Numbers"
15330 org-table-toggle-coordinate-overlays
15331 :style toggle
15332 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15333 "--"
15334 ["Create" org-table-create (and (not (org-at-table-p))
15335 org-enable-table-editor)]
15336 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15337 ["Import from File" org-table-import (not (org-at-table-p))]
15338 ["Export to File" org-table-export (org-at-table-p)]
15339 "--"
15340 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15342 (easy-menu-define org-org-menu org-mode-map "Org menu"
15343 '("Org"
15344 ("Show/Hide"
15345 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15346 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15347 ["Sparse Tree..." org-sparse-tree t]
15348 ["Reveal Context" org-reveal t]
15349 ["Show All" show-all t]
15350 "--"
15351 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15352 "--"
15353 ["New Heading" org-insert-heading t]
15354 ("Navigate Headings"
15355 ["Up" outline-up-heading t]
15356 ["Next" outline-next-visible-heading t]
15357 ["Previous" outline-previous-visible-heading t]
15358 ["Next Same Level" outline-forward-same-level t]
15359 ["Previous Same Level" outline-backward-same-level t]
15360 "--"
15361 ["Jump" org-goto t])
15362 ("Edit Structure"
15363 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15364 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15365 "--"
15366 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15367 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15368 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15369 "--"
15370 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15371 "--"
15372 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15373 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15374 ["Demote Heading" org-metaright (not (org-at-table-p))]
15375 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15376 "--"
15377 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15378 "--"
15379 ["Convert to odd levels" org-convert-to-odd-levels t]
15380 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15381 ("Editing"
15382 ["Emphasis..." org-emphasize t]
15383 ["Edit Source Example" org-edit-special t]
15384 "--"
15385 ["Footnote new/jump" org-footnote-action t]
15386 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15387 ("Archive"
15388 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15389 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15390 ; :active t :keys "C-u C-c C-x C-a"]
15391 ["Sparse trees open ARCHIVE trees"
15392 (setq org-sparse-tree-open-archived-trees
15393 (not org-sparse-tree-open-archived-trees))
15394 :style toggle :selected org-sparse-tree-open-archived-trees]
15395 ["Cycling opens ARCHIVE trees"
15396 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15397 :style toggle :selected org-cycle-open-archived-trees]
15398 "--"
15399 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15400 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15401 ; ["Check and Move Children" (org-archive-subtree '(4))
15402 ; :active t :keys "C-u C-c C-x C-s"]
15404 "--"
15405 ("Hyperlinks"
15406 ["Store Link (Global)" org-store-link t]
15407 ["Find existing link to here" org-occur-link-in-agenda-files t]
15408 ["Insert Link" org-insert-link t]
15409 ["Follow Link" org-open-at-point t]
15410 "--"
15411 ["Next link" org-next-link t]
15412 ["Previous link" org-previous-link t]
15413 "--"
15414 ["Descriptive Links"
15415 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15416 :style radio
15417 :selected (member '(org-link) buffer-invisibility-spec)]
15418 ["Literal Links"
15419 (progn
15420 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15421 :style radio
15422 :selected (not (member '(org-link) buffer-invisibility-spec))])
15423 "--"
15424 ("TODO Lists"
15425 ["TODO/DONE/-" org-todo t]
15426 ("Select keyword"
15427 ["Next keyword" org-shiftright (org-on-heading-p)]
15428 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15429 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15430 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15431 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15432 ["Show TODO Tree" org-show-todo-tree t]
15433 ["Global TODO list" org-todo-list t]
15434 "--"
15435 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15436 :selected org-enforce-todo-dependencies :style toggle :active t]
15437 "Settings for tree at point"
15438 ["Do Children sequentially" org-toggle-ordered-property :style radio
15439 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15440 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15441 ["Do Children parallel" org-toggle-ordered-property :style radio
15442 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15443 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15444 "--"
15445 ["Set Priority" org-priority t]
15446 ["Priority Up" org-shiftup t]
15447 ["Priority Down" org-shiftdown t]
15448 "--"
15449 ["Get news from all feeds" org-feed-update-all t]
15450 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15451 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15452 ("TAGS and Properties"
15453 ["Set Tags" org-set-tags-command t]
15454 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15455 "--"
15456 ["Set property" org-set-property t]
15457 ["Column view of properties" org-columns t]
15458 ["Insert Column View DBlock" org-insert-columns-dblock t])
15459 ("Dates and Scheduling"
15460 ["Timestamp" org-time-stamp t]
15461 ["Timestamp (inactive)" org-time-stamp-inactive t]
15462 ("Change Date"
15463 ["1 Day Later" org-shiftright t]
15464 ["1 Day Earlier" org-shiftleft t]
15465 ["1 ... Later" org-shiftup t]
15466 ["1 ... Earlier" org-shiftdown t])
15467 ["Compute Time Range" org-evaluate-time-range t]
15468 ["Schedule Item" org-schedule t]
15469 ["Deadline" org-deadline t]
15470 "--"
15471 ["Custom time format" org-toggle-time-stamp-overlays
15472 :style radio :selected org-display-custom-times]
15473 "--"
15474 ["Goto Calendar" org-goto-calendar t]
15475 ["Date from Calendar" org-date-from-calendar t]
15476 "--"
15477 ["Start/Restart Timer" org-timer-start t]
15478 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15479 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15480 ["Insert Timer String" org-timer t]
15481 ["Insert Timer Item" org-timer-item t])
15482 ("Logging work"
15483 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15484 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15485 ["Clock out" org-clock-out t]
15486 ["Clock cancel" org-clock-cancel t]
15487 "--"
15488 ["Mark as default task" org-clock-mark-default-task t]
15489 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15490 ["Goto running clock" org-clock-goto t]
15491 "--"
15492 ["Display times" org-clock-display t]
15493 ["Create clock table" org-clock-report t]
15494 "--"
15495 ["Record DONE time"
15496 (progn (setq org-log-done (not org-log-done))
15497 (message "Switching to %s will %s record a timestamp"
15498 (car org-done-keywords)
15499 (if org-log-done "automatically" "not")))
15500 :style toggle :selected org-log-done])
15501 "--"
15502 ["Agenda Command..." org-agenda t]
15503 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15504 ("File List for Agenda")
15505 ("Special views current file"
15506 ["TODO Tree" org-show-todo-tree t]
15507 ["Check Deadlines" org-check-deadlines t]
15508 ["Timeline" org-timeline t]
15509 ["Tags/Property tree" org-match-sparse-tree t])
15510 "--"
15511 ["Export/Publish..." org-export t]
15512 ("LaTeX"
15513 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15514 :selected org-cdlatex-mode]
15515 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15516 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15517 ["Modify math symbol" org-cdlatex-math-modify
15518 (org-inside-LaTeX-fragment-p)]
15519 ["Insert citation" org-reftex-citation t]
15520 "--"
15521 ["Export LaTeX fragments as images"
15522 (if (featurep 'org-exp)
15523 (setq org-export-with-LaTeX-fragments
15524 (not org-export-with-LaTeX-fragments))
15525 (require 'org-exp))
15526 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15527 org-export-with-LaTeX-fragments)])
15528 "--"
15529 ("MobileOrg"
15530 ["Push Files and Views" org-mobile-push t]
15531 ["Get Captured and Flagged" org-mobile-pull t]
15532 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
15533 "--"
15534 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
15535 "--"
15536 ("Documentation"
15537 ["Show Version" org-version t]
15538 ["Info Documentation" org-info t])
15539 ("Customize"
15540 ["Browse Org Group" org-customize t]
15541 "--"
15542 ["Expand This Menu" org-create-customize-menu
15543 (fboundp 'customize-menu-create)])
15544 ["Send bug report" org-submit-bug-report t]
15545 "--"
15546 ("Refresh/Reload"
15547 ["Refresh setup current buffer" org-mode-restart t]
15548 ["Reload Org (after update)" org-reload t]
15549 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15552 (defun org-info (&optional node)
15553 "Read documentation for Org-mode in the info system.
15554 With optional NODE, go directly to that node."
15555 (interactive)
15556 (info (format "(org)%s" (or node ""))))
15558 ;;;###autoload
15559 (defun org-submit-bug-report ()
15560 "Submit a bug report on Org-mode via mail.
15562 Don't hesitate to report any problems or inaccurate documentation.
15564 If you don't have setup sending mail from (X)Emacs, please copy the
15565 output buffer into your mail program, as it gives us important
15566 information about your Org-mode version and configuration."
15567 (interactive)
15568 (require 'reporter)
15569 (org-load-modules-maybe)
15570 (org-require-autoloaded-modules)
15571 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
15572 (reporter-submit-bug-report
15573 "emacs-orgmode@gnu.org"
15574 (org-version)
15575 (let (list)
15576 (save-window-excursion
15577 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
15578 (delete-other-windows)
15579 (erase-buffer)
15580 (insert "You are about to submit a bug report to the Org-mode mailing list.
15582 We would like to add your full Org-mode and Outline configuration to the
15583 bug report. This greatly simplifies the work of the maintainer and
15584 other experts on the mailing list.
15586 HOWEVER, some variables you have customized may contain private
15587 information. The names of customers, colleagues, or friends, might
15588 appear in the form of file names, tags, todo states, or search strings.
15589 If you answer yes to the prompt, you might want to check and remove
15590 such private information before sending the email.")
15591 (add-text-properties (point-min) (point-max) '(face org-warning))
15592 (when (yes-or-no-p "Include your Org-mode configuration ")
15593 (mapatoms
15594 (lambda (v)
15595 (and (boundp v)
15596 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
15597 (or (and (symbol-value v)
15598 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
15599 (and
15600 (get v 'custom-type) (get v 'standard-value)
15601 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
15602 (push v list)))))
15603 (kill-buffer (get-buffer "*Warn about privacy*"))
15604 list))
15605 nil nil
15606 "Remember to cover the basics, that is, what you expected to happen and
15607 what in fact did happen. You don't know how to make a good report? See
15609 http://orgmode.org/manual/Feedback.html#Feedback
15611 Your bug report will be posted to the Org-mode mailing list.
15612 ------------------------------------------------------------------------")))
15614 (defun org-install-agenda-files-menu ()
15615 (let ((bl (buffer-list)))
15616 (save-excursion
15617 (while bl
15618 (set-buffer (pop bl))
15619 (if (org-mode-p) (setq bl nil)))
15620 (when (org-mode-p)
15621 (easy-menu-change
15622 '("Org") "File List for Agenda"
15623 (append
15624 (list
15625 ["Edit File List" (org-edit-agenda-file-list) t]
15626 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15627 ["Remove Current File from List" org-remove-file t]
15628 ["Cycle through agenda files" org-cycle-agenda-files t]
15629 ["Occur in all agenda files" org-occur-in-agenda-files t]
15630 "--")
15631 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15633 ;;;; Documentation
15635 ;;;###autoload
15636 (defun org-require-autoloaded-modules ()
15637 (interactive)
15638 (mapc 'require
15639 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15640 org-docbook org-exp org-html org-icalendar
15641 org-id org-latex
15642 org-publish org-remember org-table
15643 org-timer org-xoxo)))
15645 ;;;###autoload
15646 (defun org-reload (&optional uncompiled)
15647 "Reload all org lisp files.
15648 With prefix arg UNCOMPILED, load the uncompiled versions."
15649 (interactive "P")
15650 (require 'find-func)
15651 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15652 (dir-org (file-name-directory (org-find-library-name "org")))
15653 (dir-org-contrib (ignore-errors
15654 (file-name-directory
15655 (org-find-library-name "org-contribdir"))))
15656 (files
15657 (append (directory-files dir-org t file-re)
15658 (and dir-org-contrib
15659 (directory-files dir-org-contrib t file-re))))
15660 (remove-re (concat (if (featurep 'xemacs)
15661 "org-colview" "org-colview-xemacs")
15662 "\\'")))
15663 (setq files (mapcar 'file-name-sans-extension files))
15664 (setq files (mapcar
15665 (lambda (x) (if (string-match remove-re x) nil x))
15666 files))
15667 (setq files (delq nil files))
15668 (mapc
15669 (lambda (f)
15670 (when (featurep (intern (file-name-nondirectory f)))
15671 (if (and (not uncompiled)
15672 (file-exists-p (concat f ".elc")))
15673 (load (concat f ".elc") nil nil t)
15674 (load (concat f ".el") nil nil t))))
15675 files))
15676 (org-version))
15678 ;;;###autoload
15679 (defun org-customize ()
15680 "Call the customize function with org as argument."
15681 (interactive)
15682 (org-load-modules-maybe)
15683 (org-require-autoloaded-modules)
15684 (customize-browse 'org))
15686 (defun org-create-customize-menu ()
15687 "Create a full customization menu for Org-mode, insert it into the menu."
15688 (interactive)
15689 (org-load-modules-maybe)
15690 (org-require-autoloaded-modules)
15691 (if (fboundp 'customize-menu-create)
15692 (progn
15693 (easy-menu-change
15694 '("Org") "Customize"
15695 `(["Browse Org group" org-customize t]
15696 "--"
15697 ,(customize-menu-create 'org)
15698 ["Set" Custom-set t]
15699 ["Save" Custom-save t]
15700 ["Reset to Current" Custom-reset-current t]
15701 ["Reset to Saved" Custom-reset-saved t]
15702 ["Reset to Standard Settings" Custom-reset-standard t]))
15703 (message "\"Org\"-menu now contains full customization menu"))
15704 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15706 ;;;; Miscellaneous stuff
15708 ;;; Generally useful functions
15710 (defun org-find-text-property-in-string (prop s)
15711 "Return the first non-nil value of property PROP in string S."
15712 (or (get-text-property 0 prop s)
15713 (get-text-property (or (next-single-property-change 0 prop s) 0)
15714 prop s)))
15716 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15717 "Display the given MESSAGE as a warning."
15718 (if (fboundp 'display-warning)
15719 (display-warning 'org message
15720 (if (featurep 'xemacs)
15721 'warning
15722 :warning))
15723 (let ((buf (get-buffer-create "*Org warnings*")))
15724 (with-current-buffer buf
15725 (goto-char (point-max))
15726 (insert "Warning (Org): " message)
15727 (unless (bolp)
15728 (newline)))
15729 (display-buffer buf)
15730 (sit-for 0))))
15732 (defun org-in-commented-line ()
15733 "Is point in a line starting with `#'?"
15734 (equal (char-after (point-at-bol)) ?#))
15736 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15737 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15738 (if (and marker (marker-buffer marker)
15739 (buffer-live-p (marker-buffer marker)))
15740 (progn
15741 (switch-to-buffer (marker-buffer marker))
15742 (if (or (> marker (point-max)) (< marker (point-min)))
15743 (widen))
15744 (goto-char marker)
15745 (org-show-context 'org-goto))
15746 (if bookmark
15747 (bookmark-jump bookmark)
15748 (error "Cannot find location"))))
15750 (defun org-quote-csv-field (s)
15751 "Quote field for inclusion in CSV material."
15752 (if (string-match "[\",]" s)
15753 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15756 (defun org-plist-delete (plist property)
15757 "Delete PROPERTY from PLIST.
15758 This is in contrast to merely setting it to 0."
15759 (let (p)
15760 (while plist
15761 (if (not (eq property (car plist)))
15762 (setq p (plist-put p (car plist) (nth 1 plist))))
15763 (setq plist (cddr plist)))
15766 (defun org-force-self-insert (N)
15767 "Needed to enforce self-insert under remapping."
15768 (interactive "p")
15769 (self-insert-command N))
15771 (defun org-string-width (s)
15772 "Compute width of string, ignoring invisible characters.
15773 This ignores character with invisibility property `org-link', and also
15774 characters with property `org-cwidth', because these will become invisible
15775 upon the next fontification round."
15776 (let (b l)
15777 (when (or (eq t buffer-invisibility-spec)
15778 (assq 'org-link buffer-invisibility-spec))
15779 (while (setq b (text-property-any 0 (length s)
15780 'invisible 'org-link s))
15781 (setq s (concat (substring s 0 b)
15782 (substring s (or (next-single-property-change
15783 b 'invisible s) (length s)))))))
15784 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15785 (setq s (concat (substring s 0 b)
15786 (substring s (or (next-single-property-change
15787 b 'org-cwidth s) (length s))))))
15788 (setq l (string-width s) b -1)
15789 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15790 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15793 (defun org-get-indentation (&optional line)
15794 "Get the indentation of the current line, interpreting tabs.
15795 When LINE is given, assume it represents a line and compute its indentation."
15796 (if line
15797 (if (string-match "^ *" (org-remove-tabs line))
15798 (match-end 0))
15799 (save-excursion
15800 (beginning-of-line 1)
15801 (skip-chars-forward " \t")
15802 (current-column))))
15804 (defun org-remove-tabs (s &optional width)
15805 "Replace tabulators in S with spaces.
15806 Assumes that s is a single line, starting in column 0."
15807 (setq width (or width tab-width))
15808 (while (string-match "\t" s)
15809 (setq s (replace-match
15810 (make-string
15811 (- (* width (/ (+ (match-beginning 0) width) width))
15812 (match-beginning 0)) ?\ )
15813 t t s)))
15816 (defun org-fix-indentation (line ind)
15817 "Fix indentation in LINE.
15818 IND is a cons cell with target and minimum indentation.
15819 If the current indentation in LINE is smaller than the minimum,
15820 leave it alone. If it is larger than ind, set it to the target."
15821 (let* ((l (org-remove-tabs line))
15822 (i (org-get-indentation l))
15823 (i1 (car ind)) (i2 (cdr ind)))
15824 (if (>= i i2) (setq l (substring line i2)))
15825 (if (> i1 0)
15826 (concat (make-string i1 ?\ ) l)
15827 l)))
15829 (defun org-remove-indentation (code &optional n)
15830 "Remove the maximum common indentation from the lines in CODE.
15831 N may optionally be the number of spaces to remove."
15832 (with-temp-buffer
15833 (insert code)
15834 (org-do-remove-indentation n)
15835 (buffer-string)))
15837 (defun org-do-remove-indentation (&optional n)
15838 "Remove the maximum common indentation from the buffer."
15839 (untabify (point-min) (point-max))
15840 (let ((min 10000) re)
15841 (if n
15842 (setq min n)
15843 (goto-char (point-min))
15844 (while (re-search-forward "^ *[^ \n]" nil t)
15845 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15846 (unless (or (= min 0) (= min 10000))
15847 (setq re (format "^ \\{%d\\}" min))
15848 (goto-char (point-min))
15849 (while (re-search-forward re nil t)
15850 (replace-match "")
15851 (end-of-line 1))
15852 min)))
15854 (defun org-base-buffer (buffer)
15855 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15856 (if (not buffer)
15857 buffer
15858 (or (buffer-base-buffer buffer)
15859 buffer)))
15861 (defun org-trim (s)
15862 "Remove whitespace at beginning and end of string."
15863 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15864 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15867 (defun org-wrap (string &optional width lines)
15868 "Wrap string to either a number of lines, or a width in characters.
15869 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15870 that costs. If there is a word longer than WIDTH, the text is actually
15871 wrapped to the length of that word.
15872 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15873 many lines, whatever width that takes.
15874 The return value is a list of lines, without newlines at the end."
15875 (let* ((words (org-split-string string "[ \t\n]+"))
15876 (maxword (apply 'max (mapcar 'org-string-width words)))
15877 w ll)
15878 (cond (width
15879 (org-do-wrap words (max maxword width)))
15880 (lines
15881 (setq w maxword)
15882 (setq ll (org-do-wrap words maxword))
15883 (if (<= (length ll) lines)
15885 (setq ll words)
15886 (while (> (length ll) lines)
15887 (setq w (1+ w))
15888 (setq ll (org-do-wrap words w)))
15889 ll))
15890 (t (error "Cannot wrap this")))))
15892 (defun org-do-wrap (words width)
15893 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15894 (let (lines line)
15895 (while words
15896 (setq line (pop words))
15897 (while (and words (< (+ (length line) (length (car words))) width))
15898 (setq line (concat line " " (pop words))))
15899 (setq lines (push line lines)))
15900 (nreverse lines)))
15902 (defun org-split-string (string &optional separators)
15903 "Splits STRING into substrings at SEPARATORS.
15904 No empty strings are returned if there are matches at the beginning
15905 and end of string."
15906 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15907 (start 0)
15908 notfirst
15909 (list nil))
15910 (while (and (string-match rexp string
15911 (if (and notfirst
15912 (= start (match-beginning 0))
15913 (< start (length string)))
15914 (1+ start) start))
15915 (< (match-beginning 0) (length string)))
15916 (setq notfirst t)
15917 (or (eq (match-beginning 0) 0)
15918 (and (eq (match-beginning 0) (match-end 0))
15919 (eq (match-beginning 0) start))
15920 (setq list
15921 (cons (substring string start (match-beginning 0))
15922 list)))
15923 (setq start (match-end 0)))
15924 (or (eq start (length string))
15925 (setq list
15926 (cons (substring string start)
15927 list)))
15928 (nreverse list)))
15930 (defun org-quote-vert (s)
15931 "Replace \"|\" with \"\\vert\"."
15932 (while (string-match "|" s)
15933 (setq s (replace-match "\\vert" t t s)))
15936 (defun org-uuidgen-p (s)
15937 "Is S an ID created by UUIDGEN?"
15938 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15940 (defun org-context ()
15941 "Return a list of contexts of the current cursor position.
15942 If several contexts apply, all are returned.
15943 Each context entry is a list with a symbol naming the context, and
15944 two positions indicating start and end of the context. Possible
15945 contexts are:
15947 :headline anywhere in a headline
15948 :headline-stars on the leading stars in a headline
15949 :todo-keyword on a TODO keyword (including DONE) in a headline
15950 :tags on the TAGS in a headline
15951 :priority on the priority cookie in a headline
15952 :item on the first line of a plain list item
15953 :item-bullet on the bullet/number of a plain list item
15954 :checkbox on the checkbox in a plain list item
15955 :table in an org-mode table
15956 :table-special on a special filed in a table
15957 :table-table in a table.el table
15958 :link on a hyperlink
15959 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15960 :target on a <<target>>
15961 :radio-target on a <<<radio-target>>>
15962 :latex-fragment on a LaTeX fragment
15963 :latex-preview on a LaTeX fragment with overlayed preview image
15965 This function expects the position to be visible because it uses font-lock
15966 faces as a help to recognize the following contexts: :table-special, :link,
15967 and :keyword."
15968 (let* ((f (get-text-property (point) 'face))
15969 (faces (if (listp f) f (list f)))
15970 (p (point)) clist o)
15971 ;; First the large context
15972 (cond
15973 ((org-on-heading-p t)
15974 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15975 (when (progn
15976 (beginning-of-line 1)
15977 (looking-at org-todo-line-tags-regexp))
15978 (push (org-point-in-group p 1 :headline-stars) clist)
15979 (push (org-point-in-group p 2 :todo-keyword) clist)
15980 (push (org-point-in-group p 4 :tags) clist))
15981 (goto-char p)
15982 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15983 (if (looking-at "\\[#[A-Z0-9]\\]")
15984 (push (org-point-in-group p 0 :priority) clist)))
15986 ((org-at-item-p)
15987 (push (org-point-in-group p 2 :item-bullet) clist)
15988 (push (list :item (point-at-bol)
15989 (save-excursion (org-end-of-item) (point)))
15990 clist)
15991 (and (org-at-item-checkbox-p)
15992 (push (org-point-in-group p 0 :checkbox) clist)))
15994 ((org-at-table-p)
15995 (push (list :table (org-table-begin) (org-table-end)) clist)
15996 (if (memq 'org-formula faces)
15997 (push (list :table-special
15998 (previous-single-property-change p 'face)
15999 (next-single-property-change p 'face)) clist)))
16000 ((org-at-table-p 'any)
16001 (push (list :table-table) clist)))
16002 (goto-char p)
16004 ;; Now the small context
16005 (cond
16006 ((org-at-timestamp-p)
16007 (push (org-point-in-group p 0 :timestamp) clist))
16008 ((memq 'org-link faces)
16009 (push (list :link
16010 (previous-single-property-change p 'face)
16011 (next-single-property-change p 'face)) clist))
16012 ((memq 'org-special-keyword faces)
16013 (push (list :keyword
16014 (previous-single-property-change p 'face)
16015 (next-single-property-change p 'face)) clist))
16016 ((org-on-target-p)
16017 (push (org-point-in-group p 0 :target) clist)
16018 (goto-char (1- (match-beginning 0)))
16019 (if (looking-at org-radio-target-regexp)
16020 (push (org-point-in-group p 0 :radio-target) clist))
16021 (goto-char p))
16022 ((setq o (car (delq nil
16023 (mapcar
16024 (lambda (x)
16025 (if (memq x org-latex-fragment-image-overlays) x))
16026 (org-overlays-at (point))))))
16027 (push (list :latex-fragment
16028 (org-overlay-start o) (org-overlay-end o)) clist)
16029 (push (list :latex-preview
16030 (org-overlay-start o) (org-overlay-end o)) clist))
16031 ((org-inside-LaTeX-fragment-p)
16032 ;; FIXME: positions wrong.
16033 (push (list :latex-fragment (point) (point)) clist)))
16035 (setq clist (nreverse (delq nil clist)))
16036 clist))
16038 ;; FIXME: Compare with at-regexp-p Do we need both?
16039 (defun org-in-regexp (re &optional nlines visually)
16040 "Check if point is inside a match of regexp.
16041 Normally only the current line is checked, but you can include NLINES extra
16042 lines both before and after point into the search.
16043 If VISUALLY is set, require that the cursor is not after the match but
16044 really on, so that the block visually is on the match."
16045 (catch 'exit
16046 (let ((pos (point))
16047 (eol (point-at-eol (+ 1 (or nlines 0))))
16048 (inc (if visually 1 0)))
16049 (save-excursion
16050 (beginning-of-line (- 1 (or nlines 0)))
16051 (while (re-search-forward re eol t)
16052 (if (and (<= (match-beginning 0) pos)
16053 (>= (+ inc (match-end 0)) pos))
16054 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16056 (defun org-at-regexp-p (regexp)
16057 "Is point inside a match of REGEXP in the current line?"
16058 (catch 'exit
16059 (save-excursion
16060 (let ((pos (point)) (end (point-at-eol)))
16061 (beginning-of-line 1)
16062 (while (re-search-forward regexp end t)
16063 (if (and (<= (match-beginning 0) pos)
16064 (>= (match-end 0) pos))
16065 (throw 'exit t)))
16066 nil))))
16068 (defun org-occur-in-agenda-files (regexp &optional nlines)
16069 "Call `multi-occur' with buffers for all agenda files."
16070 (interactive "sOrg-files matching: \np")
16071 (let* ((files (org-agenda-files))
16072 (tnames (mapcar 'file-truename files))
16073 (extra org-agenda-text-search-extra-files)
16075 (when (eq (car extra) 'agenda-archives)
16076 (setq extra (cdr extra))
16077 (setq files (org-add-archive-files files)))
16078 (while (setq f (pop extra))
16079 (unless (member (file-truename f) tnames)
16080 (add-to-list 'files f 'append)
16081 (add-to-list 'tnames (file-truename f) 'append)))
16082 (multi-occur
16083 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16084 regexp)))
16086 (if (boundp 'occur-mode-find-occurrence-hook)
16087 ;; Emacs 23
16088 (add-hook 'occur-mode-find-occurrence-hook
16089 (lambda ()
16090 (when (org-mode-p)
16091 (org-reveal))))
16092 ;; Emacs 22
16093 (defadvice occur-mode-goto-occurrence
16094 (after org-occur-reveal activate)
16095 (and (org-mode-p) (org-reveal)))
16096 (defadvice occur-mode-goto-occurrence-other-window
16097 (after org-occur-reveal activate)
16098 (and (org-mode-p) (org-reveal)))
16099 (defadvice occur-mode-display-occurrence
16100 (after org-occur-reveal activate)
16101 (when (org-mode-p)
16102 (let ((pos (occur-mode-find-occurrence)))
16103 (with-current-buffer (marker-buffer pos)
16104 (save-excursion
16105 (goto-char pos)
16106 (org-reveal)))))))
16108 (defun org-occur-link-in-agenda-files ()
16109 "Create a link and search for it in the agendas.
16110 The link is not stored in `org-stored-links', it is just created
16111 for the search purpose."
16112 (interactive)
16113 (let ((link (condition-case nil
16114 (org-store-link nil)
16115 (error "Unable to create a link to here"))))
16116 (org-occur-in-agenda-files (regexp-quote link))))
16118 (defun org-uniquify (list)
16119 "Remove duplicate elements from LIST."
16120 (let (res)
16121 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16122 res))
16124 (defun org-delete-all (elts list)
16125 "Remove all elements in ELTS from LIST."
16126 (while elts
16127 (setq list (delete (pop elts) list)))
16128 list)
16130 (defun org-back-over-empty-lines ()
16131 "Move backwards over whitespace, to the beginning of the first empty line.
16132 Returns the number of empty lines passed."
16133 (let ((pos (point)))
16134 (skip-chars-backward " \t\n\r")
16135 (beginning-of-line 2)
16136 (goto-char (min (point) pos))
16137 (count-lines (point) pos)))
16139 (defun org-skip-whitespace ()
16140 (skip-chars-forward " \t\n\r"))
16142 (defun org-point-in-group (point group &optional context)
16143 "Check if POINT is in match-group GROUP.
16144 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16145 match. If the match group does ot exist or point is not inside it,
16146 return nil."
16147 (and (match-beginning group)
16148 (>= point (match-beginning group))
16149 (<= point (match-end group))
16150 (if context
16151 (list context (match-beginning group) (match-end group))
16152 t)))
16154 (defun org-switch-to-buffer-other-window (&rest args)
16155 "Switch to buffer in a second window on the current frame.
16156 In particular, do not allow pop-up frames."
16157 (let (pop-up-frames special-display-buffer-names special-display-regexps
16158 special-display-function)
16159 (apply 'switch-to-buffer-other-window args)))
16161 (defun org-combine-plists (&rest plists)
16162 "Create a single property list from all plists in PLISTS.
16163 The process starts by copying the first list, and then setting properties
16164 from the other lists. Settings in the last list are the most significant
16165 ones and overrule settings in the other lists."
16166 (let ((rtn (copy-sequence (pop plists)))
16167 p v ls)
16168 (while plists
16169 (setq ls (pop plists))
16170 (while ls
16171 (setq p (pop ls) v (pop ls))
16172 (setq rtn (plist-put rtn p v))))
16173 rtn))
16175 (defun org-move-line-down (arg)
16176 "Move the current line down. With prefix argument, move it past ARG lines."
16177 (interactive "p")
16178 (let ((col (current-column))
16179 beg end pos)
16180 (beginning-of-line 1) (setq beg (point))
16181 (beginning-of-line 2) (setq end (point))
16182 (beginning-of-line (+ 1 arg))
16183 (setq pos (move-marker (make-marker) (point)))
16184 (insert (delete-and-extract-region beg end))
16185 (goto-char pos)
16186 (org-move-to-column col)))
16188 (defun org-move-line-up (arg)
16189 "Move the current line up. With prefix argument, move it past ARG lines."
16190 (interactive "p")
16191 (let ((col (current-column))
16192 beg end pos)
16193 (beginning-of-line 1) (setq beg (point))
16194 (beginning-of-line 2) (setq end (point))
16195 (beginning-of-line (- arg))
16196 (setq pos (move-marker (make-marker) (point)))
16197 (insert (delete-and-extract-region beg end))
16198 (goto-char pos)
16199 (org-move-to-column col)))
16201 (defun org-replace-escapes (string table)
16202 "Replace %-escapes in STRING with values in TABLE.
16203 TABLE is an association list with keys like \"%a\" and string values.
16204 The sequences in STRING may contain normal field width and padding information,
16205 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16206 so values can contain further %-escapes if they are define later in TABLE."
16207 (let ((case-fold-search nil)
16208 e re rpl)
16209 (while (setq e (pop table))
16210 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16211 (while (string-match re string)
16212 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16213 (cdr e)))
16214 (setq string (replace-match rpl t t string))))
16215 string))
16218 (defun org-sublist (list start end)
16219 "Return a section of LIST, from START to END.
16220 Counting starts at 1."
16221 (let (rtn (c start))
16222 (setq list (nthcdr (1- start) list))
16223 (while (and list (<= c end))
16224 (push (pop list) rtn)
16225 (setq c (1+ c)))
16226 (nreverse rtn)))
16228 (defun org-find-base-buffer-visiting (file)
16229 "Like `find-buffer-visiting' but always return the base buffer and
16230 not an indirect buffer."
16231 (let ((buf (or (get-file-buffer file)
16232 (find-buffer-visiting file))))
16233 (if buf
16234 (or (buffer-base-buffer buf) buf)
16235 nil)))
16237 (defun org-image-file-name-regexp (&optional extensions)
16238 "Return regexp matching the file names of images.
16239 If EXTENSIONS is given, only match these."
16240 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16241 (image-file-name-regexp)
16242 (let ((image-file-name-extensions
16243 (or extensions
16244 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16245 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16246 (concat "\\."
16247 (regexp-opt (nconc (mapcar 'upcase
16248 image-file-name-extensions)
16249 image-file-name-extensions)
16251 "\\'"))))
16253 (defun org-file-image-p (file &optional extensions)
16254 "Return non-nil if FILE is an image."
16255 (save-match-data
16256 (string-match (org-image-file-name-regexp extensions) file)))
16258 (defun org-get-cursor-date ()
16259 "Return the date at cursor in as a time.
16260 This works in the calendar and in the agenda, anywhere else it just
16261 returns the current time."
16262 (let (date day defd)
16263 (cond
16264 ((eq major-mode 'calendar-mode)
16265 (setq date (calendar-cursor-to-date)
16266 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16267 ((eq major-mode 'org-agenda-mode)
16268 (setq day (get-text-property (point) 'day))
16269 (if day
16270 (setq date (calendar-gregorian-from-absolute day)
16271 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16272 (nth 2 date))))))
16273 (or defd (current-time))))
16275 (defvar org-agenda-action-marker (make-marker)
16276 "Marker pointing to the entry for the next agenda action.")
16278 (defun org-mark-entry-for-agenda-action ()
16279 "Mark the current entry as target of an agenda action.
16280 Agenda actions are actions executed from the agenda with the key `k',
16281 which make use of the date at the cursor."
16282 (interactive)
16283 (move-marker org-agenda-action-marker
16284 (save-excursion (org-back-to-heading t) (point))
16285 (current-buffer))
16286 (message
16287 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16289 ;;; Paragraph filling stuff.
16290 ;; We want this to be just right, so use the full arsenal.
16292 (defun org-indent-line-function ()
16293 "Indent line like previous, but further if previous was headline or item."
16294 (interactive)
16295 (let* ((pos (point))
16296 (itemp (org-at-item-p))
16297 (case-fold-search t)
16298 (org-drawer-regexp (or org-drawer-regexp "\000"))
16299 column bpos bcol tpos tcol bullet btype bullet-type)
16300 ;; Find the previous relevant line
16301 (beginning-of-line 1)
16302 (cond
16303 ((looking-at "#") (setq column 0))
16304 ((looking-at "\\*+ ") (setq column 0))
16305 ((and (looking-at "[ \t]*:END:")
16306 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16307 (save-excursion
16308 (goto-char (1- (match-beginning 1)))
16309 (setq column (current-column))))
16310 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16311 (save-excursion
16312 (re-search-backward
16313 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16314 (setq column (org-get-indentation (match-string 0))))
16316 (beginning-of-line 0)
16317 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16318 (not (looking-at "[ \t]*:END:"))
16319 (not (looking-at org-drawer-regexp)))
16320 (beginning-of-line 0))
16321 (cond
16322 ((looking-at "\\*+[ \t]+")
16323 (if (not org-adapt-indentation)
16324 (setq column 0)
16325 (goto-char (match-end 0))
16326 (setq column (current-column))))
16327 ((looking-at org-drawer-regexp)
16328 (goto-char (1- (match-beginning 1)))
16329 (setq column (current-column)))
16330 ((looking-at "\\([ \t]*\\):END:")
16331 (goto-char (match-end 1))
16332 (setq column (current-column)))
16333 ((org-in-item-p)
16334 (org-beginning-of-item)
16335 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16336 (setq bpos (match-beginning 1) tpos (match-end 0)
16337 bcol (progn (goto-char bpos) (current-column))
16338 tcol (progn (goto-char tpos) (current-column))
16339 bullet (match-string 1)
16340 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16341 (if (> tcol (+ bcol org-description-max-indent))
16342 (setq tcol (+ bcol 5)))
16343 (if (not itemp)
16344 (setq column tcol)
16345 (goto-char pos)
16346 (beginning-of-line 1)
16347 (if (looking-at "\\S-")
16348 (progn
16349 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16350 (setq bullet (match-string 1)
16351 btype (if (string-match "[0-9]" bullet) "n" bullet))
16352 (setq column (if (equal btype bullet-type) bcol tcol)))
16353 (setq column (org-get-indentation)))))
16354 (t (setq column (org-get-indentation))))))
16355 (goto-char pos)
16356 (if (<= (current-column) (current-indentation))
16357 (org-indent-line-to column)
16358 (save-excursion (org-indent-line-to column)))
16359 (setq column (current-column))
16360 (beginning-of-line 1)
16361 (if (looking-at
16362 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16363 (replace-match (concat "\\1" (format org-property-format
16364 (match-string 2) (match-string 3)))
16365 t nil))
16366 (org-move-to-column column)))
16368 (defun org-set-autofill-regexps ()
16369 (interactive)
16370 ;; In the paragraph separator we include headlines, because filling
16371 ;; text in a line directly attached to a headline would otherwise
16372 ;; fill the headline as well.
16373 (org-set-local 'comment-start-skip "^#+[ \t]*")
16374 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16375 ;; The paragraph starter includes hand-formatted lists.
16376 (org-set-local
16377 'paragraph-start
16378 (concat
16379 "\f" "\\|"
16380 "[ ]*$" "\\|"
16381 "\\*+ " "\\|"
16382 "[ \t]*#" "\\|"
16383 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16384 "[ \t]*[:|]" "\\|"
16385 "\\$\\$" "\\|"
16386 "\\\\\\(begin\\|end\\|[][]\\)"))
16387 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16388 ;; But only if the user has not turned off tables or fixed-width regions
16389 (org-set-local
16390 'auto-fill-inhibit-regexp
16391 (concat "\\*+ \\|#\\+"
16392 "\\|[ \t]*" org-keyword-time-regexp
16393 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16394 (concat
16395 "\\|[ \t]*["
16396 (if org-enable-table-editor "|" "")
16397 (if org-enable-fixed-width-editor ":" "")
16398 "]"))))
16399 ;; We use our own fill-paragraph function, to make sure that tables
16400 ;; and fixed-width regions are not wrapped. That function will pass
16401 ;; through to `fill-paragraph' when appropriate.
16402 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16403 ; Adaptive filling: To get full control, first make sure that
16404 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16405 (org-set-local 'adaptive-fill-regexp "\000")
16406 (org-set-local 'adaptive-fill-function
16407 'org-adaptive-fill-function)
16408 (org-set-local
16409 'align-mode-rules-list
16410 '((org-in-buffer-settings
16411 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16412 (modes . '(org-mode))))))
16414 (defun org-fill-paragraph (&optional justify)
16415 "Re-align a table, pass through to fill-paragraph if no table."
16416 (let ((table-p (org-at-table-p))
16417 (table.el-p (org-at-table.el-p)))
16418 (cond ((and (equal (char-after (point-at-bol)) ?*)
16419 (save-excursion (goto-char (point-at-bol))
16420 (looking-at outline-regexp)))
16421 t) ; skip headlines
16422 (table.el-p t) ; skip table.el tables
16423 (table-p (org-table-align) t) ; align org-mode tables
16424 (t nil)))) ; call paragraph-fill
16426 ;; For reference, this is the default value of adaptive-fill-regexp
16427 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16429 (defun org-adaptive-fill-function ()
16430 "Return a fill prefix for org-mode files.
16431 In particular, this makes sure hanging paragraphs for hand-formatted lists
16432 work correctly."
16433 (cond ((looking-at "#[ \t]+")
16434 (match-string 0))
16435 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16436 (save-excursion
16437 (if (> (match-end 1) (+ (match-beginning 1)
16438 org-description-max-indent))
16439 (goto-char (+ (match-beginning 1) 5))
16440 (goto-char (match-end 0)))
16441 (make-string (current-column) ?\ )))
16442 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16443 (save-excursion
16444 (goto-char (match-end 0))
16445 (make-string (current-column) ?\ )))
16446 (t nil)))
16448 ;;; Other stuff.
16450 (defun org-toggle-fixed-width-section (arg)
16451 "Toggle the fixed-width export.
16452 If there is no active region, the QUOTE keyword at the current headline is
16453 inserted or removed. When present, it causes the text between this headline
16454 and the next to be exported as fixed-width text, and unmodified.
16455 If there is an active region, this command adds or removes a colon as the
16456 first character of this line. If the first character of a line is a colon,
16457 this line is also exported in fixed-width font."
16458 (interactive "P")
16459 (let* ((cc 0)
16460 (regionp (org-region-active-p))
16461 (beg (if regionp (region-beginning) (point)))
16462 (end (if regionp (region-end)))
16463 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16464 (case-fold-search nil)
16465 (re "[ \t]*\\(: \\)")
16466 off)
16467 (if regionp
16468 (save-excursion
16469 (goto-char beg)
16470 (setq cc (current-column))
16471 (beginning-of-line 1)
16472 (setq off (looking-at re))
16473 (while (> nlines 0)
16474 (setq nlines (1- nlines))
16475 (beginning-of-line 1)
16476 (cond
16477 (arg
16478 (org-move-to-column cc t)
16479 (insert ": \n")
16480 (forward-line -1))
16481 ((and off (looking-at re))
16482 (replace-match "" t t nil 1))
16483 ((not off) (org-move-to-column cc t) (insert ": ")))
16484 (forward-line 1)))
16485 (save-excursion
16486 (org-back-to-heading)
16487 (if (looking-at (concat outline-regexp
16488 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16489 (replace-match "" t t nil 1)
16490 (if (looking-at outline-regexp)
16491 (progn
16492 (goto-char (match-end 0))
16493 (insert org-quote-string " "))))))))
16495 (defun org-reftex-citation ()
16496 "Use reftex-citation to insert a citation into the buffer.
16497 This looks for a line like
16499 #+BIBLIOGRAPHY: foo plain option:-d
16501 and derives from it that foo.bib is the bbliography file relevant
16502 for this document. It then installs the necessary environment for RefTeX
16503 to work in this buffer and calls `reftex-citation' to insert a citation
16504 into the buffer.
16506 Export of such citations to both LaTeX and HTML is handled by the contributed
16507 package org-exp-bibtex by Taru Karttunen."
16508 (interactive)
16509 (let ((reftex-docstruct-symbol 'rds)
16510 (reftex-cite-format "\\cite{%l}")
16511 rds bib)
16512 (save-excursion
16513 (save-restriction
16514 (widen)
16515 (let ((case-fold-search t)
16516 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16517 (if (not (save-excursion
16518 (or (re-search-forward re nil t)
16519 (re-search-backward re nil t))))
16520 (error "No bibliography defined in file")
16521 (setq bib (concat (match-string 1) ".bib")
16522 rds (list (list 'bib bib)))))))
16523 (call-interactively 'reftex-citation)))
16525 ;;;; Functions extending outline functionality
16527 (defun org-beginning-of-line (&optional arg)
16528 "Go to the beginning of the current line. If that is invisible, continue
16529 to a visible line beginning. This makes the function of C-a more intuitive.
16530 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16531 first attempt, and only move to after the tags when the cursor is already
16532 beyond the end of the headline."
16533 (interactive "P")
16534 (let ((pos (point))
16535 (special (if (consp org-special-ctrl-a/e)
16536 (car org-special-ctrl-a/e)
16537 org-special-ctrl-a/e))
16538 refpos)
16539 (if (org-bound-and-true-p line-move-visual)
16540 (beginning-of-visual-line 1)
16541 (beginning-of-line 1))
16542 (if (and arg (fboundp 'move-beginning-of-line))
16543 (call-interactively 'move-beginning-of-line)
16544 (if (bobp)
16546 (backward-char 1)
16547 (if (org-invisible-p)
16548 (while (and (not (bobp)) (org-invisible-p))
16549 (backward-char 1)
16550 (beginning-of-line 1))
16551 (forward-char 1))))
16552 (when special
16553 (cond
16554 ((and (looking-at org-complex-heading-regexp)
16555 (= (char-after (match-end 1)) ?\ ))
16556 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16557 (point-at-eol)))
16558 (goto-char
16559 (if (eq special t)
16560 (cond ((> pos refpos) refpos)
16561 ((= pos (point)) refpos)
16562 (t (point)))
16563 (cond ((> pos (point)) (point))
16564 ((not (eq last-command this-command)) (point))
16565 (t refpos)))))
16566 ((org-at-item-p)
16567 (goto-char
16568 (if (eq special t)
16569 (cond ((> pos (match-end 4)) (match-end 4))
16570 ((= pos (point)) (match-end 4))
16571 (t (point)))
16572 (cond ((> pos (point)) (point))
16573 ((not (eq last-command this-command)) (point))
16574 (t (match-end 4))))))))
16575 (org-no-warnings
16576 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16578 (defun org-end-of-line (&optional arg)
16579 "Go to the end of the line.
16580 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16581 first attempt, and only move to after the tags when the cursor is already
16582 beyond the end of the headline."
16583 (interactive "P")
16584 (let ((special (if (consp org-special-ctrl-a/e)
16585 (cdr org-special-ctrl-a/e)
16586 org-special-ctrl-a/e)))
16587 (if (or (not special)
16588 (not (org-on-heading-p))
16589 arg)
16590 (call-interactively
16591 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16592 ((fboundp 'move-end-of-line) 'move-end-of-line)
16593 (t 'end-of-line)))
16594 (let ((pos (point)))
16595 (beginning-of-line 1)
16596 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16597 (if (eq special t)
16598 (if (or (< pos (match-beginning 1))
16599 (= pos (match-end 0)))
16600 (goto-char (match-beginning 1))
16601 (goto-char (match-end 0)))
16602 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16603 (goto-char (match-end 0))
16604 (goto-char (match-beginning 1))))
16605 (call-interactively (if (fboundp 'move-end-of-line)
16606 'move-end-of-line
16607 'end-of-line)))))
16608 (org-no-warnings
16609 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16611 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16612 (define-key org-mode-map "\C-e" 'org-end-of-line)
16614 (defun org-backward-sentence (&optional arg)
16615 "Go to beginning of sentence, or beginning of table field.
16616 This will call `backward-sentence' or `org-table-beginning-of-field',
16617 depending on context."
16618 (interactive "P")
16619 (cond
16620 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16621 (t (call-interactively 'backward-sentence))))
16623 (defun org-forward-sentence (&optional arg)
16624 "Go to end of sentence, or end of table field.
16625 This will call `forward-sentence' or `org-table-end-of-field',
16626 depending on context."
16627 (interactive "P")
16628 (cond
16629 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16630 (t (call-interactively 'forward-sentence))))
16632 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16633 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16635 (defun org-kill-line (&optional arg)
16636 "Kill line, to tags or end of line."
16637 (interactive "P")
16638 (cond
16639 ((or (not org-special-ctrl-k)
16640 (bolp)
16641 (not (org-on-heading-p)))
16642 (call-interactively 'kill-line))
16643 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16644 (kill-region (point) (match-beginning 1))
16645 (org-set-tags nil t))
16646 (t (kill-region (point) (point-at-eol)))))
16648 (define-key org-mode-map "\C-k" 'org-kill-line)
16650 (defun org-yank (&optional arg)
16651 "Yank. If the kill is a subtree, treat it specially.
16652 This command will look at the current kill and check if is a single
16653 subtree, or a series of subtrees[1]. If it passes the test, and if the
16654 cursor is at the beginning of a line or after the stars of a currently
16655 empty headline, then the yank is handled specially. How exactly depends
16656 on the value of the following variables, both set by default.
16658 org-yank-folded-subtrees
16659 When set, the subtree(s) will be folded after insertion, but only
16660 if doing so would now swallow text after the yanked text.
16662 org-yank-adjusted-subtrees
16663 When set, the subtree will be promoted or demoted in order to
16664 fit into the local outline tree structure, which means that the level
16665 will be adjusted so that it becomes the smaller one of the two
16666 *visible* surrounding headings.
16668 Any prefix to this command will cause `yank' to be called directly with
16669 no special treatment. In particular, a simple `C-u' prefix will just
16670 plainly yank the text as it is.
16672 \[1] The test checks if the first non-white line is a heading
16673 and if there are no other headings with fewer stars."
16674 (interactive "P")
16675 (org-yank-generic 'yank arg))
16677 (defun org-yank-generic (command arg)
16678 "Perform some yank-like command.
16680 This function implements the behavior described in the `org-yank'
16681 documentation. However, it has been generalized to work for any
16682 interactive command with similar behavior."
16684 ;; pretend to be command COMMAND
16685 (setq this-command command)
16687 (if arg
16688 (call-interactively command)
16690 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16691 (and (org-kill-is-subtree-p)
16692 (or (bolp)
16693 (and (looking-at "[ \t]*$")
16694 (string-match
16695 "\\`\\*+\\'"
16696 (buffer-substring (point-at-bol) (point)))))))
16697 swallowp)
16698 (cond
16699 ((and subtreep org-yank-folded-subtrees)
16700 (let ((beg (point))
16701 end)
16702 (if (and subtreep org-yank-adjusted-subtrees)
16703 (org-paste-subtree nil nil 'for-yank)
16704 (call-interactively command))
16706 (setq end (point))
16707 (goto-char beg)
16708 (when (and (bolp) subtreep
16709 (not (setq swallowp
16710 (org-yank-folding-would-swallow-text beg end))))
16711 (or (looking-at outline-regexp)
16712 (re-search-forward (concat "^" outline-regexp) end t))
16713 (while (and (< (point) end) (looking-at outline-regexp))
16714 (hide-subtree)
16715 (org-cycle-show-empty-lines 'folded)
16716 (condition-case nil
16717 (outline-forward-same-level 1)
16718 (error (goto-char end)))))
16719 (when swallowp
16720 (message
16721 "Inserted text not folded because that would swallow text"))
16723 (goto-char end)
16724 (skip-chars-forward " \t\n\r")
16725 (beginning-of-line 1)
16726 (push-mark beg 'nomsg)))
16727 ((and subtreep org-yank-adjusted-subtrees)
16728 (let ((beg (point-at-bol)))
16729 (org-paste-subtree nil nil 'for-yank)
16730 (push-mark beg 'nomsg)))
16732 (call-interactively command))))))
16734 (defun org-yank-folding-would-swallow-text (beg end)
16735 "Would hide-subtree at BEG swallow any text after END?"
16736 (let (level)
16737 (save-excursion
16738 (goto-char beg)
16739 (when (or (looking-at outline-regexp)
16740 (re-search-forward (concat "^" outline-regexp) end t))
16741 (setq level (org-outline-level)))
16742 (goto-char end)
16743 (skip-chars-forward " \t\r\n\v\f")
16744 (if (or (eobp)
16745 (and (bolp) (looking-at org-outline-regexp)
16746 (<= (org-outline-level) level)))
16747 nil ; Nothing would be swallowed
16748 t)))) ; something would swallow
16750 (define-key org-mode-map "\C-y" 'org-yank)
16752 (defun org-invisible-p ()
16753 "Check if point is at a character currently not visible."
16754 ;; Early versions of noutline don't have `outline-invisible-p'.
16755 (if (fboundp 'outline-invisible-p)
16756 (outline-invisible-p)
16757 (get-char-property (point) 'invisible)))
16759 (defun org-invisible-p2 ()
16760 "Check if point is at a character currently not visible."
16761 (save-excursion
16762 (if (and (eolp) (not (bobp))) (backward-char 1))
16763 ;; Early versions of noutline don't have `outline-invisible-p'.
16764 (if (fboundp 'outline-invisible-p)
16765 (outline-invisible-p)
16766 (get-char-property (point) 'invisible))))
16768 (defun org-back-to-heading (&optional invisible-ok)
16769 "Call `outline-back-to-heading', but provide a better error message."
16770 (condition-case nil
16771 (outline-back-to-heading invisible-ok)
16772 (error (error "Before first headline at position %d in buffer %s"
16773 (point) (current-buffer)))))
16775 (defun org-before-first-heading-p ()
16776 "Before first heading?"
16777 (save-excursion
16778 (null (re-search-backward "^\\*+ " nil t))))
16780 (defalias 'org-on-heading-p 'outline-on-heading-p)
16781 (defalias 'org-at-heading-p 'outline-on-heading-p)
16782 (defun org-at-heading-or-item-p ()
16783 (or (org-on-heading-p) (org-at-item-p)))
16785 (defun org-on-target-p ()
16786 (or (org-in-regexp org-radio-target-regexp)
16787 (org-in-regexp org-target-regexp)))
16789 (defun org-up-heading-all (arg)
16790 "Move to the heading line of which the present line is a subheading.
16791 This function considers both visible and invisible heading lines.
16792 With argument, move up ARG levels."
16793 (if (fboundp 'outline-up-heading-all)
16794 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16795 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16797 (defun org-up-heading-safe ()
16798 "Move to the heading line of which the present line is a subheading.
16799 This version will not throw an error. It will return the level of the
16800 headline found, or nil if no higher level is found.
16802 Also, this function will be a lot faster than `outline-up-heading',
16803 because it relies on stars being the outline starters. This can really
16804 make a significant difference in outlines with very many siblings."
16805 (let (start-level re)
16806 (org-back-to-heading t)
16807 (setq start-level (funcall outline-level))
16808 (if (equal start-level 1)
16810 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16811 (if (re-search-backward re nil t)
16812 (funcall outline-level)))))
16814 (defun org-first-sibling-p ()
16815 "Is this heading the first child of its parents?"
16816 (interactive)
16817 (let ((re (concat "^" outline-regexp))
16818 level l)
16819 (unless (org-at-heading-p t)
16820 (error "Not at a heading"))
16821 (setq level (funcall outline-level))
16822 (save-excursion
16823 (if (not (re-search-backward re nil t))
16825 (setq l (funcall outline-level))
16826 (< l level)))))
16828 (defun org-goto-sibling (&optional previous)
16829 "Goto the next sibling, even if it is invisible.
16830 When PREVIOUS is set, go to the previous sibling instead. Returns t
16831 when a sibling was found. When none is found, return nil and don't
16832 move point."
16833 (let ((fun (if previous 're-search-backward 're-search-forward))
16834 (pos (point))
16835 (re (concat "^" outline-regexp))
16836 level l)
16837 (when (condition-case nil (org-back-to-heading t) (error nil))
16838 (setq level (funcall outline-level))
16839 (catch 'exit
16840 (or previous (forward-char 1))
16841 (while (funcall fun re nil t)
16842 (setq l (funcall outline-level))
16843 (when (< l level) (goto-char pos) (throw 'exit nil))
16844 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16845 (goto-char pos)
16846 nil))))
16848 (defun org-show-siblings ()
16849 "Show all siblings of the current headline."
16850 (save-excursion
16851 (while (org-goto-sibling) (org-flag-heading nil)))
16852 (save-excursion
16853 (while (org-goto-sibling 'previous)
16854 (org-flag-heading nil))))
16856 (defun org-show-hidden-entry ()
16857 "Show an entry where even the heading is hidden."
16858 (save-excursion
16859 (org-show-entry)))
16861 (defun org-flag-heading (flag &optional entry)
16862 "Flag the current heading. FLAG non-nil means make invisible.
16863 When ENTRY is non-nil, show the entire entry."
16864 (save-excursion
16865 (org-back-to-heading t)
16866 ;; Check if we should show the entire entry
16867 (if entry
16868 (progn
16869 (org-show-entry)
16870 (save-excursion
16871 (and (outline-next-heading)
16872 (org-flag-heading nil))))
16873 (outline-flag-region (max (point-min) (1- (point)))
16874 (save-excursion (outline-end-of-heading) (point))
16875 flag))))
16877 (defun org-get-next-sibling ()
16878 "Move to next heading of the same level, and return point.
16879 If there is no such heading, return nil.
16880 This is like outline-next-sibling, but invisible headings are ok."
16881 (let ((level (funcall outline-level)))
16882 (outline-next-heading)
16883 (while (and (not (eobp)) (> (funcall outline-level) level))
16884 (outline-next-heading))
16885 (if (or (eobp) (< (funcall outline-level) level))
16887 (point))))
16889 (defun org-get-last-sibling ()
16890 "Move to previous heading of the same level, and return point.
16891 If there is no such heading, return nil."
16892 (let ((opoint (point))
16893 (level (funcall outline-level)))
16894 (outline-previous-heading)
16895 (when (and (/= (point) opoint) (outline-on-heading-p t))
16896 (while (and (> (funcall outline-level) level)
16897 (not (bobp)))
16898 (outline-previous-heading))
16899 (if (< (funcall outline-level) level)
16901 (point)))))
16903 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16904 ;; This contains an exact copy of the original function, but it uses
16905 ;; `org-back-to-heading', to make it work also in invisible
16906 ;; trees. And is uses an invisible-OK argument.
16907 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16908 ;; Furthermore, when used inside Org, finding the end of a large subtree
16909 ;; with many children and grandchildren etc, this can be much faster
16910 ;; than the outline version.
16911 (org-back-to-heading invisible-OK)
16912 (let ((first t)
16913 (level (funcall outline-level)))
16914 (if (and (org-mode-p) (< level 1000))
16915 ;; A true heading (not a plain list item), in Org-mode
16916 ;; This means we can easily find the end by looking
16917 ;; only for the right number of stars. Using a regexp to do
16918 ;; this is so much faster than using a Lisp loop.
16919 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16920 (forward-char 1)
16921 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16922 ;; something else, do it the slow way
16923 (while (and (not (eobp))
16924 (or first (> (funcall outline-level) level)))
16925 (setq first nil)
16926 (outline-next-heading)))
16927 (unless to-heading
16928 (if (memq (preceding-char) '(?\n ?\^M))
16929 (progn
16930 ;; Go to end of line before heading
16931 (forward-char -1)
16932 (if (memq (preceding-char) '(?\n ?\^M))
16933 ;; leave blank line before heading
16934 (forward-char -1))))))
16935 (point))
16937 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16938 "Use Org version in org-mode, for dramatic speed-up."
16939 (if (eq major-mode 'org-mode)
16940 (progn
16941 (org-end-of-subtree nil t)
16942 (unless (eobp) (backward-char 1)))
16943 ad-do-it))
16945 (defun org-forward-same-level (arg &optional invisible-ok)
16946 "Move forward to the arg'th subheading at same level as this one.
16947 Stop at the first and last subheadings of a superior heading."
16948 (interactive "p")
16949 (org-back-to-heading invisible-ok)
16950 (org-on-heading-p)
16951 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16952 (re (format "^\\*\\{1,%d\\} " level))
16954 (forward-char 1)
16955 (while (> arg 0)
16956 (while (and (re-search-forward re nil 'move)
16957 (setq l (- (match-end 0) (match-beginning 0) 1))
16958 (= l level)
16959 (not invisible-ok)
16960 (org-invisible-p))
16961 (if (< l level) (setq arg 1)))
16962 (setq arg (1- arg)))
16963 (beginning-of-line 1)))
16965 (defun org-backward-same-level (arg &optional invisible-ok)
16966 "Move backward to the arg'th subheading at same level as this one.
16967 Stop at the first and last subheadings of a superior heading."
16968 (interactive "p")
16969 (org-back-to-heading)
16970 (org-on-heading-p)
16971 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16972 (re (format "^\\*\\{1,%d\\} " level))
16974 (while (> arg 0)
16975 (while (and (re-search-backward re nil 'move)
16976 (setq l (- (match-end 0) (match-beginning 0) 1))
16977 (= l level)
16978 (not invisible-ok)
16979 (org-invisible-p))
16980 (if (< l level) (setq arg 1)))
16981 (setq arg (1- arg)))))
16983 (defun org-show-subtree ()
16984 "Show everything after this heading at deeper levels."
16985 (outline-flag-region
16986 (point)
16987 (save-excursion
16988 (org-end-of-subtree t t))
16989 nil))
16991 (defun org-show-entry ()
16992 "Show the body directly following this heading.
16993 Show the heading too, if it is currently invisible."
16994 (interactive)
16995 (save-excursion
16996 (condition-case nil
16997 (progn
16998 (org-back-to-heading t)
16999 (outline-flag-region
17000 (max (point-min) (1- (point)))
17001 (save-excursion
17002 (if (re-search-forward
17003 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17004 (match-beginning 1)
17005 (point-max)))
17006 nil)
17007 (org-cycle-hide-drawers 'children))
17008 (error nil))))
17010 (defun org-make-options-regexp (kwds &optional extra)
17011 "Make a regular expression for keyword lines."
17012 (concat
17014 "#?[ \t]*\\+\\("
17015 (mapconcat 'regexp-quote kwds "\\|")
17016 (if extra (concat "\\|" extra))
17017 "\\):[ \t]*"
17018 "\\(.*\\)"))
17020 ;; Make isearch reveal the necessary context
17021 (defun org-isearch-end ()
17022 "Reveal context after isearch exits."
17023 (when isearch-success ; only if search was successful
17024 (if (featurep 'xemacs)
17025 ;; Under XEmacs, the hook is run in the correct place,
17026 ;; we directly show the context.
17027 (org-show-context 'isearch)
17028 ;; In Emacs the hook runs *before* restoring the overlays.
17029 ;; So we have to use a one-time post-command-hook to do this.
17030 ;; (Emacs 22 has a special variable, see function `org-mode')
17031 (unless (and (boundp 'isearch-mode-end-hook-quit)
17032 isearch-mode-end-hook-quit)
17033 ;; Only when the isearch was not quitted.
17034 (org-add-hook 'post-command-hook 'org-isearch-post-command
17035 'append 'local)))))
17037 (defun org-isearch-post-command ()
17038 "Remove self from hook, and show context."
17039 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17040 (org-show-context 'isearch))
17043 ;;;; Integration with and fixes for other packages
17045 ;;; Imenu support
17047 (defvar org-imenu-markers nil
17048 "All markers currently used by Imenu.")
17049 (make-variable-buffer-local 'org-imenu-markers)
17051 (defun org-imenu-new-marker (&optional pos)
17052 "Return a new marker for use by Imenu, and remember the marker."
17053 (let ((m (make-marker)))
17054 (move-marker m (or pos (point)))
17055 (push m org-imenu-markers)
17058 (defun org-imenu-get-tree ()
17059 "Produce the index for Imenu."
17060 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17061 (setq org-imenu-markers nil)
17062 (let* ((n org-imenu-depth)
17063 (re (concat "^" outline-regexp))
17064 (subs (make-vector (1+ n) nil))
17065 (last-level 0)
17066 m level head)
17067 (save-excursion
17068 (save-restriction
17069 (widen)
17070 (goto-char (point-max))
17071 (while (re-search-backward re nil t)
17072 (setq level (org-reduced-level (funcall outline-level)))
17073 (when (<= level n)
17074 (looking-at org-complex-heading-regexp)
17075 (setq head (org-link-display-format
17076 (org-match-string-no-properties 4))
17077 m (org-imenu-new-marker))
17078 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17079 (if (>= level last-level)
17080 (push (cons head m) (aref subs level))
17081 (push (cons head (aref subs (1+ level))) (aref subs level))
17082 (loop for i from (1+ level) to n do (aset subs i nil)))
17083 (setq last-level level)))))
17084 (aref subs 1)))
17086 (eval-after-load "imenu"
17087 '(progn
17088 (add-hook 'imenu-after-jump-hook
17089 (lambda ()
17090 (if (eq major-mode 'org-mode)
17091 (org-show-context 'org-goto))))))
17093 (defun org-link-display-format (link)
17094 "Replace a link with either the description, or the link target
17095 if no description is present"
17096 (save-match-data
17097 (if (string-match org-bracket-link-analytic-regexp link)
17098 (replace-match (or (match-string 5 link)
17099 (concat (match-string 1 link)
17100 (match-string 3 link)))
17101 nil nil link)
17102 link)))
17104 ;; Speedbar support
17106 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17107 "Overlay marking the agenda restriction line in speedbar.")
17108 (org-overlay-put org-speedbar-restriction-lock-overlay
17109 'face 'org-agenda-restriction-lock)
17110 (org-overlay-put org-speedbar-restriction-lock-overlay
17111 'help-echo "Agendas are currently limited to this item.")
17112 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17114 (defun org-speedbar-set-agenda-restriction ()
17115 "Restrict future agenda commands to the location at point in speedbar.
17116 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17117 (interactive)
17118 (require 'org-agenda)
17119 (let (p m tp np dir txt)
17120 (cond
17121 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17122 'org-imenu t))
17123 (setq m (get-text-property p 'org-imenu-marker))
17124 (save-excursion
17125 (save-restriction
17126 (set-buffer (marker-buffer m))
17127 (goto-char m)
17128 (org-agenda-set-restriction-lock 'subtree))))
17129 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17130 'speedbar-function 'speedbar-find-file))
17131 (setq tp (previous-single-property-change
17132 (1+ p) 'speedbar-function)
17133 np (next-single-property-change
17134 tp 'speedbar-function)
17135 dir (speedbar-line-directory)
17136 txt (buffer-substring-no-properties (or tp (point-min))
17137 (or np (point-max))))
17138 (save-excursion
17139 (save-restriction
17140 (set-buffer (find-file-noselect
17141 (let ((default-directory dir))
17142 (expand-file-name txt))))
17143 (unless (org-mode-p)
17144 (error "Cannot restrict to non-Org-mode file"))
17145 (org-agenda-set-restriction-lock 'file))))
17146 (t (error "Don't know how to restrict Org-mode's agenda")))
17147 (org-move-overlay org-speedbar-restriction-lock-overlay
17148 (point-at-bol) (point-at-eol))
17149 (setq current-prefix-arg nil)
17150 (org-agenda-maybe-redo)))
17152 (eval-after-load "speedbar"
17153 '(progn
17154 (speedbar-add-supported-extension ".org")
17155 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17156 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17157 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17158 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17159 (add-hook 'speedbar-visiting-tag-hook
17160 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17163 ;;; Fixes and Hacks for problems with other packages
17165 ;; Make flyspell not check words in links, to not mess up our keymap
17166 (defun org-mode-flyspell-verify ()
17167 "Don't let flyspell put overlays at active buttons."
17168 (and (not (get-text-property (point) 'keymap))
17169 (not (get-text-property (point) 'org-no-flyspell))))
17171 (defun org-remove-flyspell-overlays-in (beg end)
17172 "Remove flyspell overlays in region."
17173 (and (org-bound-and-true-p flyspell-mode)
17174 (fboundp 'flyspell-delete-region-overlays)
17175 (flyspell-delete-region-overlays beg end))
17176 (add-text-properties beg end '(org-no-flyspell t)))
17178 ;; Make `bookmark-jump' show the jump location if it was hidden.
17179 (eval-after-load "bookmark"
17180 '(if (boundp 'bookmark-after-jump-hook)
17181 ;; We can use the hook
17182 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17183 ;; Hook not available, use advice
17184 (defadvice bookmark-jump (after org-make-visible activate)
17185 "Make the position visible."
17186 (org-bookmark-jump-unhide))))
17188 ;; Make sure saveplace show the location if it was hidden
17189 (eval-after-load "saveplace"
17190 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17191 "Make the position visible."
17192 (org-bookmark-jump-unhide)))
17194 (defun org-bookmark-jump-unhide ()
17195 "Unhide the current position, to show the bookmark location."
17196 (and (org-mode-p)
17197 (or (org-invisible-p)
17198 (save-excursion (goto-char (max (point-min) (1- (point))))
17199 (org-invisible-p)))
17200 (org-show-context 'bookmark-jump)))
17202 ;; Make session.el ignore our circular variable
17203 (eval-after-load "session"
17204 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17206 ;;;; Experimental code
17208 (defun org-closed-in-range ()
17209 "Sparse tree of items closed in a certain time range.
17210 Still experimental, may disappear in the future."
17211 (interactive)
17212 ;; Get the time interval from the user.
17213 (let* ((time1 (org-float-time
17214 (org-read-date nil 'to-time nil "Starting date: ")))
17215 (time2 (org-float-time
17216 (org-read-date nil 'to-time nil "End date:")))
17217 ;; callback function
17218 (callback (lambda ()
17219 (let ((time
17220 (org-float-time
17221 (apply 'encode-time
17222 (org-parse-time-string
17223 (match-string 1))))))
17224 ;; check if time in interval
17225 (and (>= time time1) (<= time time2))))))
17226 ;; make tree, check each match with the callback
17227 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17229 ;;;; Finish up
17231 (provide 'org)
17233 (run-hooks 'org-load-hook)
17235 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17237 ;;; org.el ends here