Fix typo in variable name
[rgr-org-mode.git] / lisp / org.el
blob2ef6def44868d57781a4610394b7637a9a2a75e8
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.33trans
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.33trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let* ((origin default-directory)
106 (version org-version)
107 (git-version)
108 (dir (concat (file-name-directory (locate-library "org")) "../" )))
109 (when (and (file-exists-p (expand-file-name ".git" dir))
110 (executable-find "git"))
111 (unwind-protect
112 (progn
113 (cd dir)
114 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
115 (with-current-buffer "*Shell Command Output*"
116 (goto-char (point-min))
117 (setq git-version (buffer-substring (point) (point-at-eol))))
118 (subst-char-in-string ?- ?. git-version t)
119 (when (string-match "\\S-"
120 (shell-command-to-string
121 "git diff-index --name-only HEAD --"))
122 (setq git-version (concat git-version ".dirty")))
123 (setq version (concat version " (" git-version ")"))))
124 (cd origin)))
125 (setq version (format "Org-mode version %s" version))
126 (if here (insert version))
127 (message version)))
129 ;;; Compatibility constants
131 ;;; The custom variables
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
140 (defcustom org-mode-hook nil
141 "Mode hook for Org-mode, run after the mode was turned on."
142 :group 'org
143 :type 'hook)
145 (defcustom org-load-hook nil
146 "Hook that is run after org.el has been loaded."
147 :group 'org
148 :type 'hook)
150 (defvar org-modules) ; defined below
151 (defvar org-modules-loaded nil
152 "Have the modules been loaded already?")
154 (defun org-load-modules-maybe (&optional force)
155 "Load all extensions listed in `org-modules'."
156 (when (or force (not org-modules-loaded))
157 (mapc (lambda (ext)
158 (condition-case nil (require ext)
159 (error (message "Problems while trying to load feature `%s'" ext))))
160 org-modules)
161 (setq org-modules-loaded t)))
163 (defun org-set-modules (var value)
164 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
165 (set var value)
166 (when (featurep 'org)
167 (org-load-modules-maybe 'force)))
169 (when (org-bound-and-true-p org-modules)
170 (let ((a (member 'org-infojs org-modules)))
171 (and a (setcar a 'org-jsinfo))))
173 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
174 "Modules that should always be loaded together with org.el.
175 If a description starts with <C>, the file is not part of Emacs
176 and loading it will require that you have downloaded and properly installed
177 the org-mode distribution.
179 You can also use this system to load external packages (i.e. neither Org
180 core modules, nor modules from the CONTRIB directory). Just add symbols
181 to the end of the list. If the package is called org-xyz.el, then you need
182 to add the symbol `xyz', and the package must have a call to
184 (provide 'org-xyz)"
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
191 (const :tag " crypt: Encryption of subtrees" org-crypt)
192 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
193 (const :tag " docview: Links to doc-view buffers" org-docview)
194 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
195 (const :tag " id: Global IDs for identifying entries" org-id)
196 (const :tag " info: Links to Info nodes" org-info)
197 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
198 (const :tag " habit: Track your consistency with habits" org-habit)
199 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
200 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
201 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
202 (const :tag " mew Links to Mew folders/messages" org-mew)
203 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
204 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
205 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
206 (const :tag " vm: Links to VM folders/messages" org-vm)
207 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
208 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
209 (const :tag " mouse: Additional mouse support" org-mouse)
211 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
212 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
213 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
214 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
215 (const :tag "C collector: Collect properties into tables" org-collector)
216 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
217 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
218 (const :tag "C eval: Include command output as text" org-eval)
219 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
220 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
221 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
222 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
223 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
225 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
227 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
228 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
229 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
230 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
231 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
232 (const :tag "C mtags: Support for muse-like tags" org-mtags)
233 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
234 (const :tag "C R: Computation using the R language" org-R)
235 (const :tag "C registry: A registry for Org-mode links" org-registry)
236 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
237 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
238 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
239 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
240 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
241 (const :tag "C track: Keep up with Org-mode development" org-track)
242 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
244 (defcustom org-support-shift-select nil
245 "Non-nil means, make shift-cursor commands select text when possible.
247 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
248 selecting a region, or enlarge thusly regions started in this way.
249 In Org-mode, in special contexts, these same keys are used for other
250 purposes, important enough to compete with shift selection. Org tries
251 to balance these needs by supporting `shift-select-mode' outside these
252 special contexts, under control of this variable.
254 The default of this variable is nil, to avoid confusing behavior. Shifted
255 cursor keys will then execute Org commands in the following contexts:
256 - on a headline, changing TODO state (left/right) and priority (up/down)
257 - on a time stamp, changing the time
258 - in a plain list item, changing the bullet type
259 - in a property definition line, switching between allowed values
260 - in the BEGIN line of a clock table (changing the time block).
261 Outside these contexts, the commands will throw an error.
263 When this variable is t and the cursor is not in a special context,
264 Org-mode will support shift-selection for making and enlarging regions.
265 To make this more effective, the bullet cycling will no longer happen
266 anywhere in an item line, but only if the cursor is exactly on the bullet.
268 If you set this variable to the symbol `always', then the keys
269 will not be special in headlines, property lines, and item lines, to make
270 shift selection work there as well. If this is what you want, you can
271 use the following alternative commands: `C-c C-t' and `C-c ,' to
272 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
273 TODO sets, `C-c -' to cycle item bullet types, and properties can be
274 edited by hand or in column view.
276 However, when the cursor is on a timestamp, shift-cursor commands
277 will still edit the time stamp - this is just too good to give up.
279 XEmacs user should have this variable set to nil, because shift-select-mode
280 is Emacs 23 only."
281 :group 'org
282 :type '(choice
283 (const :tag "Never" nil)
284 (const :tag "When outside special context" t)
285 (const :tag "Everywhere except timestamps" always)))
287 (defgroup org-startup nil
288 "Options concerning startup of Org-mode."
289 :tag "Org Startup"
290 :group 'org)
292 (defcustom org-startup-folded t
293 "Non-nil means, entering Org-mode will switch to OVERVIEW.
294 This can also be configured on a per-file basis by adding one of
295 the following lines anywhere in the buffer:
297 #+STARTUP: fold (or `overview', this is equivalent)
298 #+STARTUP: nofold (or `showall', this is equivalent)
299 #+STARTUP: content
300 #+STARTUP: showeverything"
301 :group 'org-startup
302 :type '(choice
303 (const :tag "nofold: show all" nil)
304 (const :tag "fold: overview" t)
305 (const :tag "content: all headlines" content)
306 (const :tag "show everything, even drawers" showeverything)))
308 (defcustom org-startup-truncated t
309 "Non-nil means, entering Org-mode will set `truncate-lines'.
310 This is useful since some lines containing links can be very long and
311 uninteresting. Also tables look terrible when wrapped."
312 :group 'org-startup
313 :type 'boolean)
315 (defcustom org-startup-indented nil
316 "Non-nil means, turn on `org-indent-mode' on startup.
317 This can also be configured on a per-file basis by adding one of
318 the following lines anywhere in the buffer:
320 #+STARTUP: indent
321 #+STARTUP: noindent"
322 :group 'org-structure
323 :type '(choice
324 (const :tag "Not" nil)
325 (const :tag "Globally (slow on startup in large files)" t)))
327 (defcustom org-startup-with-beamer-mode nil
328 "Non-nil means, turn on `org-beamer-mode' on startup.
329 This can also be configured on a per-file basis by adding one of
330 the following lines anywhere in the buffer:
332 #+STARTUP: beamer"
333 :group 'org-startup
334 :type 'boolean)
336 (defcustom org-startup-align-all-tables nil
337 "Non-nil means, align all tables when visiting a file.
338 This is useful when the column width in tables is forced with <N> cookies
339 in table fields. Such tables will look correct only after the first re-align.
340 This can also be configured on a per-file basis by adding one of
341 the following lines anywhere in the buffer:
342 #+STARTUP: align
343 #+STARTUP: noalign"
344 :group 'org-startup
345 :type 'boolean)
347 (defcustom org-insert-mode-line-in-empty-file nil
348 "Non-nil means insert the first line setting Org-mode in empty files.
349 When the function `org-mode' is called interactively in an empty file, this
350 normally means that the file name does not automatically trigger Org-mode.
351 To ensure that the file will always be in Org-mode in the future, a
352 line enforcing Org-mode will be inserted into the buffer, if this option
353 has been set."
354 :group 'org-startup
355 :type 'boolean)
357 (defcustom org-replace-disputed-keys nil
358 "Non-nil means use alternative key bindings for some keys.
359 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
360 These keys are also used by other packages like shift-selection-mode'
361 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
362 If you want to use Org-mode together with one of these other modes,
363 or more generally if you would like to move some Org-mode commands to
364 other keys, set this variable and configure the keys with the variable
365 `org-disputed-keys'.
367 This option is only relevant at load-time of Org-mode, and must be set
368 *before* org.el is loaded. Changing it requires a restart of Emacs to
369 become effective."
370 :group 'org-startup
371 :type 'boolean)
373 (defcustom org-use-extra-keys nil
374 "Non-nil means use extra key sequence definitions for certain
375 commands. This happens automatically if you run XEmacs or if
376 window-system is nil. This variable lets you do the same
377 manually. You must set it before loading org.
379 Example: on Carbon Emacs 22 running graphically, with an external
380 keyboard on a Powerbook, the default way of setting M-left might
381 not work for either Alt or ESC. Setting this variable will make
382 it work for ESC."
383 :group 'org-startup
384 :type 'boolean)
386 (if (fboundp 'defvaralias)
387 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
389 (defcustom org-disputed-keys
390 '(([(shift up)] . [(meta p)])
391 ([(shift down)] . [(meta n)])
392 ([(shift left)] . [(meta -)])
393 ([(shift right)] . [(meta +)])
394 ([(control shift right)] . [(meta shift +)])
395 ([(control shift left)] . [(meta shift -)]))
396 "Keys for which Org-mode and other modes compete.
397 This is an alist, cars are the default keys, second element specifies
398 the alternative to use when `org-replace-disputed-keys' is t.
400 Keys can be specified in any syntax supported by `define-key'.
401 The value of this option takes effect only at Org-mode's startup,
402 therefore you'll have to restart Emacs to apply it after changing."
403 :group 'org-startup
404 :type 'alist)
406 (defun org-key (key)
407 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
408 Or return the original if not disputed."
409 (if org-replace-disputed-keys
410 (let* ((nkey (key-description key))
411 (x (org-find-if (lambda (x)
412 (equal (key-description (car x)) nkey))
413 org-disputed-keys)))
414 (if x (cdr x) key))
415 key))
417 (defun org-find-if (predicate seq)
418 (catch 'exit
419 (while seq
420 (if (funcall predicate (car seq))
421 (throw 'exit (car seq))
422 (pop seq)))))
424 (defun org-defkey (keymap key def)
425 "Define a key, possibly translated, as returned by `org-key'."
426 (define-key keymap (org-key key) def))
428 (defcustom org-ellipsis nil
429 "The ellipsis to use in the Org-mode outline.
430 When nil, just use the standard three dots. When a string, use that instead,
431 When a face, use the standard 3 dots, but with the specified face.
432 The change affects only Org-mode (which will then use its own display table).
433 Changing this requires executing `M-x org-mode' in a buffer to become
434 effective."
435 :group 'org-startup
436 :type '(choice (const :tag "Default" nil)
437 (face :tag "Face" :value org-warning)
438 (string :tag "String" :value "...#")))
440 (defvar org-display-table nil
441 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
443 (defgroup org-keywords nil
444 "Keywords in Org-mode."
445 :tag "Org Keywords"
446 :group 'org)
448 (defcustom org-deadline-string "DEADLINE:"
449 "String to mark deadline entries.
450 A deadline is this string, followed by a time stamp. Should be a word,
451 terminated by a colon. You can insert a schedule keyword and
452 a timestamp with \\[org-deadline].
453 Changes become only effective after restarting Emacs."
454 :group 'org-keywords
455 :type 'string)
457 (defcustom org-scheduled-string "SCHEDULED:"
458 "String to mark scheduled TODO entries.
459 A schedule is this string, followed by a time stamp. Should be a word,
460 terminated by a colon. You can insert a schedule keyword and
461 a timestamp with \\[org-schedule].
462 Changes become only effective after restarting Emacs."
463 :group 'org-keywords
464 :type 'string)
466 (defcustom org-closed-string "CLOSED:"
467 "String used as the prefix for timestamps logging closing a TODO entry."
468 :group 'org-keywords
469 :type 'string)
471 (defcustom org-clock-string "CLOCK:"
472 "String used as prefix for timestamps clocking work hours on an item."
473 :group 'org-keywords
474 :type 'string)
476 (defcustom org-comment-string "COMMENT"
477 "Entries starting with this keyword will never be exported.
478 An entry can be toggled between COMMENT and normal with
479 \\[org-toggle-comment].
480 Changes become only effective after restarting Emacs."
481 :group 'org-keywords
482 :type 'string)
484 (defcustom org-quote-string "QUOTE"
485 "Entries starting with this keyword will be exported in fixed-width font.
486 Quoting applies only to the text in the entry following the headline, and does
487 not extend beyond the next headline, even if that is lower level.
488 An entry can be toggled between QUOTE and normal with
489 \\[org-toggle-fixed-width-section]."
490 :group 'org-keywords
491 :type 'string)
493 (defconst org-repeat-re
494 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
495 "Regular expression for specifying repeated events.
496 After a match, group 1 contains the repeat expression.")
498 (defgroup org-structure nil
499 "Options concerning the general structure of Org-mode files."
500 :tag "Org Structure"
501 :group 'org)
503 (defgroup org-reveal-location nil
504 "Options about how to make context of a location visible."
505 :tag "Org Reveal Location"
506 :group 'org-structure)
508 (defconst org-context-choice
509 '(choice
510 (const :tag "Always" t)
511 (const :tag "Never" nil)
512 (repeat :greedy t :tag "Individual contexts"
513 (cons
514 (choice :tag "Context"
515 (const agenda)
516 (const org-goto)
517 (const occur-tree)
518 (const tags-tree)
519 (const link-search)
520 (const mark-goto)
521 (const bookmark-jump)
522 (const isearch)
523 (const default))
524 (boolean))))
525 "Contexts for the reveal options.")
527 (defcustom org-show-hierarchy-above '((default . t))
528 "Non-nil means, show full hierarchy when revealing a location.
529 Org-mode often shows locations in an org-mode file which might have
530 been invisible before. When this is set, the hierarchy of headings
531 above the exposed location is shown.
532 Turning this off for example for sparse trees makes them very compact.
533 Instead of t, this can also be an alist specifying this option for different
534 contexts. Valid contexts are
535 agenda when exposing an entry from the agenda
536 org-goto when using the command `org-goto' on key C-c C-j
537 occur-tree when using the command `org-occur' on key C-c /
538 tags-tree when constructing a sparse tree based on tags matches
539 link-search when exposing search matches associated with a link
540 mark-goto when exposing the jump goal of a mark
541 bookmark-jump when exposing a bookmark location
542 isearch when exiting from an incremental search
543 default default for all contexts not set explicitly"
544 :group 'org-reveal-location
545 :type org-context-choice)
547 (defcustom org-show-following-heading '((default . nil))
548 "Non-nil means, show following heading when revealing a location.
549 Org-mode often shows locations in an org-mode file which might have
550 been invisible before. When this is set, the heading following the
551 match is shown.
552 Turning this off for example for sparse trees makes them very compact,
553 but makes it harder to edit the location of the match. In such a case,
554 use the command \\[org-reveal] to show more context.
555 Instead of t, this can also be an alist specifying this option for different
556 contexts. See `org-show-hierarchy-above' for valid contexts."
557 :group 'org-reveal-location
558 :type org-context-choice)
560 (defcustom org-show-siblings '((default . nil) (isearch t))
561 "Non-nil means, show all sibling heading when revealing a location.
562 Org-mode often shows locations in an org-mode file which might have
563 been invisible before. When this is set, the sibling of the current entry
564 heading are all made visible. If `org-show-hierarchy-above' is t,
565 the same happens on each level of the hierarchy above the current entry.
567 By default this is on for the isearch context, off for all other contexts.
568 Turning this off for example for sparse trees makes them very compact,
569 but makes it harder to edit the location of the match. In such a case,
570 use the command \\[org-reveal] to show more context.
571 Instead of t, this can also be an alist specifying this option for different
572 contexts. See `org-show-hierarchy-above' for valid contexts."
573 :group 'org-reveal-location
574 :type org-context-choice)
576 (defcustom org-show-entry-below '((default . nil))
577 "Non-nil means, show the entry below a headline when revealing a location.
578 Org-mode often shows locations in an org-mode file which might have
579 been invisible before. When this is set, the text below the headline that is
580 exposed is also shown.
582 By default this is off for all contexts.
583 Instead of t, this can also be an alist specifying this option for different
584 contexts. See `org-show-hierarchy-above' for valid contexts."
585 :group 'org-reveal-location
586 :type org-context-choice)
588 (defcustom org-indirect-buffer-display 'other-window
589 "How should indirect tree buffers be displayed?
590 This applies to indirect buffers created with the commands
591 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
592 Valid values are:
593 current-window Display in the current window
594 other-window Just display in another window.
595 dedicated-frame Create one new frame, and re-use it each time.
596 new-frame Make a new frame each time. Note that in this case
597 previously-made indirect buffers are kept, and you need to
598 kill these buffers yourself."
599 :group 'org-structure
600 :group 'org-agenda-windows
601 :type '(choice
602 (const :tag "In current window" current-window)
603 (const :tag "In current frame, other window" other-window)
604 (const :tag "Each time a new frame" new-frame)
605 (const :tag "One dedicated frame" dedicated-frame)))
607 (defcustom org-use-speed-commands nil
608 "Non-nil means, activate single letter commands at beginning of a headline.
609 This may also be a function to test for appropriate locations where speed
610 commands should be active."
611 :group 'org-structure
612 :type '(choice
613 (const :tag "Never" nil)
614 (const :tag "At beginning of headline stars" t)
615 (function)))
617 (defcustom org-speed-commands-user nil
618 "Alist of additional speed commands.
619 This list will be checked before `org-speed-commands-default'
620 when the variable `org-use-speed-commands' is non-nil
621 and when the cursor is at the beginning of a headline.
622 The car if each entry is a string with a single letter, which must
623 be assigned to `self-insert-command' in the global map.
624 The cdr is either a command to be called interactively, a function
625 to be called, or a form to be evaluated.
626 An entry that is just a list with a single string will be interpreted
627 as a descriptive headline that will be added when listing the speed
628 copmmands in the Help buffer using the `?' speed command."
629 :group 'org-structure
630 :type '(repeat :value ("k" . ignore)
631 (choice :value ("k" . ignore)
632 (list :tag "Descriptive Headline" (string :tag "Headline"))
633 (cons :tag "Letter and Command"
634 (string :tag "Command letter")
635 (choice
636 (function)
637 (sexp))))))
639 (defgroup org-cycle nil
640 "Options concerning visibility cycling in Org-mode."
641 :tag "Org Cycle"
642 :group 'org-structure)
644 (defcustom org-cycle-skip-children-state-if-no-children t
645 "Non-nil means, skip CHILDREN state in entries that don't have any."
646 :group 'org-cycle
647 :type 'boolean)
649 (defcustom org-cycle-max-level nil
650 "Maximum level which should still be subject to visibility cycling.
651 Levels higher than this will, for cycling, be treated as text, not a headline.
652 When `org-odd-levels-only' is set, a value of N in this variable actually
653 means 2N-1 stars as the limiting headline.
654 When nil, cycle all levels.
655 Note that the limiting level of cycling is also influenced by
656 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
657 `org-inlinetask-min-level' is, cycling will be limited to levels one less
658 than its value."
659 :group 'org-cycle
660 :type '(choice
661 (const :tag "No limit" nil)
662 (integer :tag "Maximum level")))
664 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
665 "Names of drawers. Drawers are not opened by cycling on the headline above.
666 Drawers only open with a TAB on the drawer line itself. A drawer looks like
667 this:
668 :DRAWERNAME:
669 .....
670 :END:
671 The drawer \"PROPERTIES\" is special for capturing properties through
672 the property API.
674 Drawers can be defined on the per-file basis with a line like:
676 #+DRAWERS: HIDDEN STATE PROPERTIES"
677 :group 'org-structure
678 :group 'org-cycle
679 :type '(repeat (string :tag "Drawer Name")))
681 (defcustom org-hide-block-startup nil
682 "Non-nil means, , entering Org-mode will fold all blocks.
683 This can also be set in on a per-file basis with
685 #+STARTUP: hideblocks
686 #+STARTUP: showblocks"
687 :group 'org-startup
688 :group 'org-cycle
689 :type 'boolean)
691 (defcustom org-cycle-global-at-bob nil
692 "Cycle globally if cursor is at beginning of buffer and not at a headline.
693 This makes it possible to do global cycling without having to use S-TAB or
694 C-u TAB. For this special case to work, the first line of the buffer
695 must not be a headline - it may be empty or some other text. When used in
696 this way, `org-cycle-hook' is disables temporarily, to make sure the
697 cursor stays at the beginning of the buffer.
698 When this option is nil, don't do anything special at the beginning
699 of the buffer."
700 :group 'org-cycle
701 :type 'boolean)
703 (defcustom org-cycle-level-after-item/entry-creation t
704 "Non-nil means, cycle entry level or item indentation in new empty entries.
706 When the cursor is at the end of an empty headline, i.e with only stars
707 and maybe a TODO keyword, TAB will then switch the entry to become a child,
708 and then all possible anchestor states, before returning to the original state.
709 This makes data entry extremely fast: M-RET to create a new headline,
710 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
712 When the cursor is at the end of an empty plain list item, one TAB will
713 make it a subitem, two or more tabs will back up to make this an item
714 higher up in the item hierarchy."
715 :group 'org-cycle
716 :type 'boolean)
718 (defcustom org-cycle-emulate-tab t
719 "Where should `org-cycle' emulate TAB.
720 nil Never
721 white Only in completely white lines
722 whitestart Only at the beginning of lines, before the first non-white char
723 t Everywhere except in headlines
724 exc-hl-bol Everywhere except at the start of a headline
725 If TAB is used in a place where it does not emulate TAB, the current subtree
726 visibility is cycled."
727 :group 'org-cycle
728 :type '(choice (const :tag "Never" nil)
729 (const :tag "Only in completely white lines" white)
730 (const :tag "Before first char in a line" whitestart)
731 (const :tag "Everywhere except in headlines" t)
732 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
735 (defcustom org-cycle-separator-lines 2
736 "Number of empty lines needed to keep an empty line between collapsed trees.
737 If you leave an empty line between the end of a subtree and the following
738 headline, this empty line is hidden when the subtree is folded.
739 Org-mode will leave (exactly) one empty line visible if the number of
740 empty lines is equal or larger to the number given in this variable.
741 So the default 2 means, at least 2 empty lines after the end of a subtree
742 are needed to produce free space between a collapsed subtree and the
743 following headline.
745 If the number is negative, and the number of empty lines is at least -N,
746 all empty lines are shown.
748 Special case: when 0, never leave empty lines in collapsed view."
749 :group 'org-cycle
750 :type 'integer)
751 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
753 (defcustom org-pre-cycle-hook nil
754 "Hook that is run before visibility cycling is happening.
755 The function(s) in this hook must accept a single argument which indicates
756 the new state that will be set right after running this hook. The
757 argument is a symbol. Before a global state change, it can have the values
758 `overview', `content', or `all'. Before a local state change, it can have
759 the values `folded', `children', or `subtree'."
760 :group 'org-cycle
761 :type 'hook)
763 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
764 org-cycle-hide-drawers
765 org-cycle-show-empty-lines
766 org-optimize-window-after-visibility-change)
767 "Hook that is run after `org-cycle' has changed the buffer visibility.
768 The function(s) in this hook must accept a single argument which indicates
769 the new state that was set by the most recent `org-cycle' command. The
770 argument is a symbol. After a global state change, it can have the values
771 `overview', `content', or `all'. After a local state change, it can have
772 the values `folded', `children', or `subtree'."
773 :group 'org-cycle
774 :type 'hook)
776 (defgroup org-edit-structure nil
777 "Options concerning structure editing in Org-mode."
778 :tag "Org Edit Structure"
779 :group 'org-structure)
781 (defcustom org-odd-levels-only nil
782 "Non-nil means, skip even levels and only use odd levels for the outline.
783 This has the effect that two stars are being added/taken away in
784 promotion/demotion commands. It also influences how levels are
785 handled by the exporters.
786 Changing it requires restart of `font-lock-mode' to become effective
787 for fontification also in regions already fontified.
788 You may also set this on a per-file basis by adding one of the following
789 lines to the buffer:
791 #+STARTUP: odd
792 #+STARTUP: oddeven"
793 :group 'org-edit-structure
794 :group 'org-font-lock
795 :type 'boolean)
797 (defcustom org-adapt-indentation t
798 "Non-nil means, adapt indentation to outline node level.
800 When this variable is set, Org assumes that you write outlines by
801 indenting text in each node to align with the headline (after the stars).
802 The following issues are influenced by this variable:
804 - When this is set and the *entire* text in an entry is indented, the
805 indentation is increased by one space in a demotion command, and
806 decreased by one in a promotion command. If any line in the entry
807 body starts with text at column 0, indentation is not changed at all.
809 - Property drawers and planning information is inserted indented when
810 this variable s set. When nil, they will not be indented.
812 - TAB indents a line relative to context. The lines below a headline
813 will be indented when this variable is set.
815 Note that this is all about true indentation, by adding and removing
816 space characters. See also `org-indent.el' which does level-dependent
817 indentation in a virtual way, i.e. at display time in Emacs."
818 :group 'org-edit-structure
819 :type 'boolean)
821 (defcustom org-special-ctrl-a/e nil
822 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
824 When t, `C-a' will bring back the cursor to the beginning of the
825 headline text, i.e. after the stars and after a possible TODO keyword.
826 In an item, this will be the position after the bullet.
827 When the cursor is already at that position, another `C-a' will bring
828 it to the beginning of the line.
830 `C-e' will jump to the end of the headline, ignoring the presence of tags
831 in the headline. A second `C-e' will then jump to the true end of the
832 line, after any tags. This also means that, when this variable is
833 non-nil, `C-e' also will never jump beyond the end of the heading of a
834 folded section, i.e. not after the ellipses.
836 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
837 going to the true line boundary first. Only a directly following, identical
838 keypress will bring the cursor to the special positions.
840 This may also be a cons cell where the behavior for `C-a' and `C-e' is
841 set separately."
842 :group 'org-edit-structure
843 :type '(choice
844 (const :tag "off" nil)
845 (const :tag "on: after stars/bullet and before tags first" t)
846 (const :tag "reversed: true line boundary first" reversed)
847 (cons :tag "Set C-a and C-e separately"
848 (choice :tag "Special C-a"
849 (const :tag "off" nil)
850 (const :tag "on: after stars/bullet first" t)
851 (const :tag "reversed: before stars/bullet first" reversed))
852 (choice :tag "Special C-e"
853 (const :tag "off" nil)
854 (const :tag "on: before tags first" t)
855 (const :tag "reversed: after tags first" reversed)))))
856 (if (fboundp 'defvaralias)
857 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
859 (defcustom org-special-ctrl-k nil
860 "Non-nil means `C-k' will behave specially in headlines.
861 When nil, `C-k' will call the default `kill-line' command.
862 When t, the following will happen while the cursor is in the headline:
864 - When the cursor is at the beginning of a headline, kill the entire
865 line and possible the folded subtree below the line.
866 - When in the middle of the headline text, kill the headline up to the tags.
867 - When after the headline text, kill the tags."
868 :group 'org-edit-structure
869 :type 'boolean)
871 (defcustom org-yank-folded-subtrees t
872 "Non-nil means, when yanking subtrees, fold them.
873 If the kill is a single subtree, or a sequence of subtrees, i.e. if
874 it starts with a heading and all other headings in it are either children
875 or siblings, then fold all the subtrees. However, do this only if no
876 text after the yank would be swallowed into a folded tree by this action."
877 :group 'org-edit-structure
878 :type 'boolean)
880 (defcustom org-yank-adjusted-subtrees nil
881 "Non-nil means, when yanking subtrees, adjust the level.
882 With this setting, `org-paste-subtree' is used to insert the subtree, see
883 this function for details."
884 :group 'org-edit-structure
885 :type 'boolean)
887 (defcustom org-M-RET-may-split-line '((default . t))
888 "Non-nil means, M-RET will split the line at the cursor position.
889 When nil, it will go to the end of the line before making a
890 new line.
891 You may also set this option in a different way for different
892 contexts. Valid contexts are:
894 headline when creating a new headline
895 item when creating a new item
896 table in a table field
897 default the value to be used for all contexts not explicitly
898 customized"
899 :group 'org-structure
900 :group 'org-table
901 :type '(choice
902 (const :tag "Always" t)
903 (const :tag "Never" nil)
904 (repeat :greedy t :tag "Individual contexts"
905 (cons
906 (choice :tag "Context"
907 (const headline)
908 (const item)
909 (const table)
910 (const default))
911 (boolean)))))
914 (defcustom org-insert-heading-respect-content nil
915 "Non-nil means, insert new headings after the current subtree.
916 When nil, the new heading is created directly after the current line.
917 The commands \\[org-insert-heading-respect-content] and
918 \\[org-insert-todo-heading-respect-content] turn this variable on
919 for the duration of the command."
920 :group 'org-structure
921 :type 'boolean)
923 (defcustom org-blank-before-new-entry '((heading . auto)
924 (plain-list-item . auto))
925 "Should `org-insert-heading' leave a blank line before new heading/item?
926 The value is an alist, with `heading' and `plain-list-item' as car,
927 and a boolean flag as cdr. For plain lists, if the variable
928 `org-empty-line-terminates-plain-lists' is set, the setting here
929 is ignored and no empty line is inserted, to keep the list in tact."
930 :group 'org-edit-structure
931 :type '(list
932 (cons (const heading)
933 (choice (const :tag "Never" nil)
934 (const :tag "Always" t)
935 (const :tag "Auto" auto)))
936 (cons (const plain-list-item)
937 (choice (const :tag "Never" nil)
938 (const :tag "Always" t)
939 (const :tag "Auto" auto)))))
941 (defcustom org-insert-heading-hook nil
942 "Hook being run after inserting a new heading."
943 :group 'org-edit-structure
944 :type 'hook)
946 (defcustom org-enable-fixed-width-editor t
947 "Non-nil means, lines starting with \":\" are treated as fixed-width.
948 This currently only means, they are never auto-wrapped.
949 When nil, such lines will be treated like ordinary lines.
950 See also the QUOTE keyword."
951 :group 'org-edit-structure
952 :type 'boolean)
955 (defcustom org-goto-auto-isearch t
956 "Non-nil means, typing characters in org-goto starts incremental search."
957 :group 'org-edit-structure
958 :type 'boolean)
960 (defgroup org-sparse-trees nil
961 "Options concerning sparse trees in Org-mode."
962 :tag "Org Sparse Trees"
963 :group 'org-structure)
965 (defcustom org-highlight-sparse-tree-matches t
966 "Non-nil means, highlight all matches that define a sparse tree.
967 The highlights will automatically disappear the next time the buffer is
968 changed by an edit command."
969 :group 'org-sparse-trees
970 :type 'boolean)
972 (defcustom org-remove-highlights-with-change t
973 "Non-nil means, any change to the buffer will remove temporary highlights.
974 Such highlights are created by `org-occur' and `org-clock-display'.
975 When nil, `C-c C-c needs to be used to get rid of the highlights.
976 The highlights created by `org-preview-latex-fragment' always need
977 `C-c C-c' to be removed."
978 :group 'org-sparse-trees
979 :group 'org-time
980 :type 'boolean)
983 (defcustom org-occur-hook '(org-first-headline-recenter)
984 "Hook that is run after `org-occur' has constructed a sparse tree.
985 This can be used to recenter the window to show as much of the structure
986 as possible."
987 :group 'org-sparse-trees
988 :type 'hook)
990 (defgroup org-imenu-and-speedbar nil
991 "Options concerning imenu and speedbar in Org-mode."
992 :tag "Org Imenu and Speedbar"
993 :group 'org-structure)
995 (defcustom org-imenu-depth 2
996 "The maximum level for Imenu access to Org-mode headlines.
997 This also applied for speedbar access."
998 :group 'org-imenu-and-speedbar
999 :type 'integer)
1001 (defgroup org-table nil
1002 "Options concerning tables in Org-mode."
1003 :tag "Org Table"
1004 :group 'org)
1006 (defcustom org-enable-table-editor 'optimized
1007 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1008 When nil, such lines will be treated like ordinary lines.
1010 When equal to the symbol `optimized', the table editor will be optimized to
1011 do the following:
1012 - Automatic overwrite mode in front of whitespace in table fields.
1013 This makes the structure of the table stay in tact as long as the edited
1014 field does not exceed the column width.
1015 - Minimize the number of realigns. Normally, the table is aligned each time
1016 TAB or RET are pressed to move to another field. With optimization this
1017 happens only if changes to a field might have changed the column width.
1018 Optimization requires replacing the functions `self-insert-command',
1019 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1020 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1021 very good at guessing when a re-align will be necessary, but you can always
1022 force one with \\[org-ctrl-c-ctrl-c].
1024 If you would like to use the optimized version in Org-mode, but the
1025 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1027 This variable can be used to turn on and off the table editor during a session,
1028 but in order to toggle optimization, a restart is required.
1030 See also the variable `org-table-auto-blank-field'."
1031 :group 'org-table
1032 :type '(choice
1033 (const :tag "off" nil)
1034 (const :tag "on" t)
1035 (const :tag "on, optimized" optimized)))
1037 (defcustom org-self-insert-cluster-for-undo t
1038 "Non-nil means cluster self-insert commands for undo when possible.
1039 If this is set, then, like in the Emacs command loop, 20 consecutive
1040 characters will be undone together.
1041 This is configurable, because there is some impact on typing performance."
1042 :group 'org-table
1043 :type 'boolean)
1045 (defcustom org-table-tab-recognizes-table.el t
1046 "Non-nil means, TAB will automatically notice a table.el table.
1047 When it sees such a table, it moves point into it and - if necessary -
1048 calls `table-recognize-table'."
1049 :group 'org-table-editing
1050 :type 'boolean)
1052 (defgroup org-link nil
1053 "Options concerning links in Org-mode."
1054 :tag "Org Link"
1055 :group 'org)
1057 (defvar org-link-abbrev-alist-local nil
1058 "Buffer-local version of `org-link-abbrev-alist', which see.
1059 The value of this is taken from the #+LINK lines.")
1060 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1062 (defcustom org-link-abbrev-alist nil
1063 "Alist of link abbreviations.
1064 The car of each element is a string, to be replaced at the start of a link.
1065 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1066 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1068 [[linkkey:tag][description]]
1070 The 'linkkey' must be a word word, starting with a letter, followed
1071 by letters, numbers, '-' or '_'.
1073 If REPLACE is a string, the tag will simply be appended to create the link.
1074 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1075 the placeholder \"%h\" will cause a url-encoded version of the tag to
1076 be inserted at that point (see the function `url-hexify-string').
1078 REPLACE may also be a function that will be called with the tag as the
1079 only argument to create the link, which should be returned as a string.
1081 See the manual for examples."
1082 :group 'org-link
1083 :type '(repeat
1084 (cons
1085 (string :tag "Protocol")
1086 (choice
1087 (string :tag "Format")
1088 (function)))))
1090 (defcustom org-descriptive-links t
1091 "Non-nil means, hide link part and only show description of bracket links.
1092 Bracket links are like [[link][description]]. This variable sets the initial
1093 state in new org-mode buffers. The setting can then be toggled on a
1094 per-buffer basis from the Org->Hyperlinks menu."
1095 :group 'org-link
1096 :type 'boolean)
1098 (defcustom org-link-file-path-type 'adaptive
1099 "How the path name in file links should be stored.
1100 Valid values are:
1102 relative Relative to the current directory, i.e. the directory of the file
1103 into which the link is being inserted.
1104 absolute Absolute path, if possible with ~ for home directory.
1105 noabbrev Absolute path, no abbreviation of home directory.
1106 adaptive Use relative path for files in the current directory and sub-
1107 directories of it. For other files, use an absolute path."
1108 :group 'org-link
1109 :type '(choice
1110 (const relative)
1111 (const absolute)
1112 (const noabbrev)
1113 (const adaptive)))
1115 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1116 "Types of links that should be activated in Org-mode files.
1117 This is a list of symbols, each leading to the activation of a certain link
1118 type. In principle, it does not hurt to turn on most link types - there may
1119 be a small gain when turning off unused link types. The types are:
1121 bracket The recommended [[link][description]] or [[link]] links with hiding.
1122 angular Links in angular brackets that may contain whitespace like
1123 <bbdb:Carsten Dominik>.
1124 plain Plain links in normal text, no whitespace, like http://google.com.
1125 radio Text that is matched by a radio target, see manual for details.
1126 tag Tag settings in a headline (link to tag search).
1127 date Time stamps (link to calendar).
1128 footnote Footnote labels.
1130 Changing this variable requires a restart of Emacs to become effective."
1131 :group 'org-link
1132 :type '(set :greedy t
1133 (const :tag "Double bracket links (new style)" bracket)
1134 (const :tag "Angular bracket links (old style)" angular)
1135 (const :tag "Plain text links" plain)
1136 (const :tag "Radio target matches" radio)
1137 (const :tag "Tags" tag)
1138 (const :tag "Timestamps" date)
1139 (const :tag "Footnotes" footnote)))
1141 (defcustom org-make-link-description-function nil
1142 "Function to use to generate link descriptions from links. If
1143 nil the link location will be used. This function must take two
1144 parameters; the first is the link and the second the description
1145 org-insert-link has generated, and should return the description
1146 to use."
1147 :group 'org-link
1148 :type 'function)
1150 (defgroup org-link-store nil
1151 "Options concerning storing links in Org-mode."
1152 :tag "Org Store Link"
1153 :group 'org-link)
1155 (defcustom org-email-link-description-format "Email %c: %.30s"
1156 "Format of the description part of a link to an email or usenet message.
1157 The following %-escapes will be replaced by corresponding information:
1159 %F full \"From\" field
1160 %f name, taken from \"From\" field, address if no name
1161 %T full \"To\" field
1162 %t first name in \"To\" field, address if no name
1163 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1164 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1165 %s subject
1166 %m message-id.
1168 You may use normal field width specification between the % and the letter.
1169 This is for example useful to limit the length of the subject.
1171 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1172 :group 'org-link-store
1173 :type 'string)
1175 (defcustom org-from-is-user-regexp
1176 (let (r1 r2)
1177 (when (and user-mail-address (not (string= user-mail-address "")))
1178 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1179 (when (and user-full-name (not (string= user-full-name "")))
1180 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1181 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1182 "Regexp matched against the \"From:\" header of an email or usenet message.
1183 It should match if the message is from the user him/herself."
1184 :group 'org-link-store
1185 :type 'regexp)
1187 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1188 "Non-nil means, storing a link to an Org file will use entry IDs.
1190 Note that before this variable is even considered, org-id must be loaded,
1191 so please customize `org-modules' and turn it on.
1193 The variable can have the following values:
1195 t Create an ID if needed to make a link to the current entry.
1197 create-if-interactive
1198 If `org-store-link' is called directly (interactively, as a user
1199 command), do create an ID to support the link. But when doing the
1200 job for remember, only use the ID if it already exists. The
1201 purpose of this setting is to avoid proliferation of unwanted
1202 IDs, just because you happen to be in an Org file when you
1203 call `org-remember' that automatically and preemptively
1204 creates a link. If you do want to get an ID link in a remember
1205 template to an entry not having an ID, create it first by
1206 explicitly creating a link to it, using `C-c C-l' first.
1208 create-if-interactive-and-no-custom-id
1209 Like create-if-interactive, but do not create an ID if there is
1210 a CUSTOM_ID property defined in the entry. This is the default.
1212 use-existing
1213 Use existing ID, do not create one.
1215 nil Never use an ID to make a link, instead link using a text search for
1216 the headline text."
1217 :group 'org-link-store
1218 :type '(choice
1219 (const :tag "Create ID to make link" t)
1220 (const :tag "Create if storing link interactively"
1221 create-if-interactive)
1222 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1223 create-if-interactive-and-no-custom-id)
1224 (const :tag "Only use existing" use-existing)
1225 (const :tag "Do not use ID to create link" nil)))
1227 (defcustom org-context-in-file-links t
1228 "Non-nil means, file links from `org-store-link' contain context.
1229 A search string will be added to the file name with :: as separator and
1230 used to find the context when the link is activated by the command
1231 `org-open-at-point'.
1232 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1233 negates this setting for the duration of the command."
1234 :group 'org-link-store
1235 :type 'boolean)
1237 (defcustom org-keep-stored-link-after-insertion nil
1238 "Non-nil means, keep link in list for entire session.
1240 The command `org-store-link' adds a link pointing to the current
1241 location to an internal list. These links accumulate during a session.
1242 The command `org-insert-link' can be used to insert links into any
1243 Org-mode file (offering completion for all stored links). When this
1244 option is nil, every link which has been inserted once using \\[org-insert-link]
1245 will be removed from the list, to make completing the unused links
1246 more efficient."
1247 :group 'org-link-store
1248 :type 'boolean)
1250 (defgroup org-link-follow nil
1251 "Options concerning following links in Org-mode."
1252 :tag "Org Follow Link"
1253 :group 'org-link)
1255 (defcustom org-link-translation-function nil
1256 "Function to translate links with different syntax to Org syntax.
1257 This can be used to translate links created for example by the Planner
1258 or emacs-wiki packages to Org syntax.
1259 The function must accept two parameters, a TYPE containing the link
1260 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1261 which is everything after the link protocol. It should return a cons
1262 with possibly modified values of type and path.
1263 Org contains a function for this, so if you set this variable to
1264 `org-translate-link-from-planner', you should be able follow many
1265 links created by planner."
1266 :group 'org-link-follow
1267 :type 'function)
1269 (defcustom org-follow-link-hook nil
1270 "Hook that is run after a link has been followed."
1271 :group 'org-link-follow
1272 :type 'hook)
1274 (defcustom org-tab-follows-link nil
1275 "Non-nil means, on links TAB will follow the link.
1276 Needs to be set before org.el is loaded.
1277 This really should not be used, it does not make sense, and the
1278 implementation is bad."
1279 :group 'org-link-follow
1280 :type 'boolean)
1282 (defcustom org-return-follows-link nil
1283 "Non-nil means, on links RET will follow the link.
1284 Needs to be set before org.el is loaded."
1285 :group 'org-link-follow
1286 :type 'boolean)
1288 (defcustom org-mouse-1-follows-link
1289 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1290 "Non-nil means, mouse-1 on a link will follow the link.
1291 A longer mouse click will still set point. Does not work on XEmacs.
1292 Needs to be set before org.el is loaded."
1293 :group 'org-link-follow
1294 :type 'boolean)
1296 (defcustom org-mark-ring-length 4
1297 "Number of different positions to be recorded in the ring
1298 Changing this requires a restart of Emacs to work correctly."
1299 :group 'org-link-follow
1300 :type 'integer)
1302 (defcustom org-link-frame-setup
1303 '((vm . vm-visit-folder-other-frame)
1304 (gnus . gnus-other-frame)
1305 (file . find-file-other-window))
1306 "Setup the frame configuration for following links.
1307 When following a link with Emacs, it may often be useful to display
1308 this link in another window or frame. This variable can be used to
1309 set this up for the different types of links.
1310 For VM, use any of
1311 `vm-visit-folder'
1312 `vm-visit-folder-other-frame'
1313 For Gnus, use any of
1314 `gnus'
1315 `gnus-other-frame'
1316 `org-gnus-no-new-news'
1317 For FILE, use any of
1318 `find-file'
1319 `find-file-other-window'
1320 `find-file-other-frame'
1321 For the calendar, use the variable `calendar-setup'.
1322 For BBDB, it is currently only possible to display the matches in
1323 another window."
1324 :group 'org-link-follow
1325 :type '(list
1326 (cons (const vm)
1327 (choice
1328 (const vm-visit-folder)
1329 (const vm-visit-folder-other-window)
1330 (const vm-visit-folder-other-frame)))
1331 (cons (const gnus)
1332 (choice
1333 (const gnus)
1334 (const gnus-other-frame)
1335 (const org-gnus-no-new-news)))
1336 (cons (const file)
1337 (choice
1338 (const find-file)
1339 (const find-file-other-window)
1340 (const find-file-other-frame)))))
1342 (defcustom org-display-internal-link-with-indirect-buffer nil
1343 "Non-nil means, use indirect buffer to display infile links.
1344 Activating internal links (from one location in a file to another location
1345 in the same file) normally just jumps to the location. When the link is
1346 activated with a C-u prefix (or with mouse-3), the link is displayed in
1347 another window. When this option is set, the other window actually displays
1348 an indirect buffer clone of the current buffer, to avoid any visibility
1349 changes to the current buffer."
1350 :group 'org-link-follow
1351 :type 'boolean)
1353 (defcustom org-open-non-existing-files nil
1354 "Non-nil means, `org-open-file' will open non-existing files.
1355 When nil, an error will be generated.
1356 This variable applies only to external applications because they
1357 might choke on non-existing files. If the link is to a file that
1358 will be opened in Emacs, the variable is ignored."
1359 :group 'org-link-follow
1360 :type 'boolean)
1362 (defcustom org-open-directory-means-index-dot-org nil
1363 "Non-nil means, a link to a directory really means to index.org.
1364 When nil, following a directory link will run dired or open a finder/explorer
1365 window on that directory."
1366 :group 'org-link-follow
1367 :type 'boolean)
1369 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1370 "Function and arguments to call for following mailto links.
1371 This is a list with the first element being a lisp function, and the
1372 remaining elements being arguments to the function. In string arguments,
1373 %a will be replaced by the address, and %s will be replaced by the subject
1374 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1375 :group 'org-link-follow
1376 :type '(choice
1377 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1378 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1379 (const :tag "message-mail" (message-mail "%a" "%s"))
1380 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1382 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1383 "Non-nil means, ask for confirmation before executing shell links.
1384 Shell links can be dangerous: just think about a link
1386 [[shell:rm -rf ~/*][Google Search]]
1388 This link would show up in your Org-mode document as \"Google Search\",
1389 but really it would remove your entire home directory.
1390 Therefore we advise against setting this variable to nil.
1391 Just change it to `y-or-n-p' if you want to confirm with a
1392 single keystroke rather than having to type \"yes\"."
1393 :group 'org-link-follow
1394 :type '(choice
1395 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1396 (const :tag "with y-or-n (faster)" y-or-n-p)
1397 (const :tag "no confirmation (dangerous)" nil)))
1399 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1400 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1401 Elisp links can be dangerous: just think about a link
1403 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1405 This link would show up in your Org-mode document as \"Google Search\",
1406 but really it would remove your entire home directory.
1407 Therefore we advise against setting this variable to nil.
1408 Just change it to `y-or-n-p' if you want to confirm with a
1409 single keystroke rather than having to type \"yes\"."
1410 :group 'org-link-follow
1411 :type '(choice
1412 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1413 (const :tag "with y-or-n (faster)" y-or-n-p)
1414 (const :tag "no confirmation (dangerous)" nil)))
1416 (defconst org-file-apps-defaults-gnu
1417 '((remote . emacs)
1418 (system . mailcap)
1419 (t . mailcap))
1420 "Default file applications on a UNIX or GNU/Linux system.
1421 See `org-file-apps'.")
1423 (defconst org-file-apps-defaults-macosx
1424 '((remote . emacs)
1425 (t . "open %s")
1426 (system . "open %s")
1427 ("ps.gz" . "gv %s")
1428 ("eps.gz" . "gv %s")
1429 ("dvi" . "xdvi %s")
1430 ("fig" . "xfig %s"))
1431 "Default file applications on a MacOS X system.
1432 The system \"open\" is known as a default, but we use X11 applications
1433 for some files for which the OS does not have a good default.
1434 See `org-file-apps'.")
1436 (defconst org-file-apps-defaults-windowsnt
1437 (list
1438 '(remote . emacs)
1439 (cons t
1440 (list (if (featurep 'xemacs)
1441 'mswindows-shell-execute
1442 'w32-shell-execute)
1443 "open" 'file))
1444 (cons 'system
1445 (list (if (featurep 'xemacs)
1446 'mswindows-shell-execute
1447 'w32-shell-execute)
1448 "open" 'file)))
1449 "Default file applications on a Windows NT system.
1450 The system \"open\" is used for most files.
1451 See `org-file-apps'.")
1453 (defcustom org-file-apps
1455 (auto-mode . emacs)
1456 ("\\.mm\\'" . default)
1457 ("\\.x?html?\\'" . default)
1458 ("\\.pdf\\'" . default)
1460 "External applications for opening `file:path' items in a document.
1461 Org-mode uses system defaults for different file types, but
1462 you can use this variable to set the application for a given file
1463 extension. The entries in this list are cons cells where the car identifies
1464 files and the cdr the corresponding command. Possible values for the
1465 file identifier are
1466 \"regex\" Regular expression matched against the file name. For backward
1467 compatibility, this can also be a string with only alphanumeric
1468 characters, which is then interpreted as an extension.
1469 `directory' Matches a directory
1470 `remote' Matches a remote file, accessible through tramp or efs.
1471 Remote files most likely should be visited through Emacs
1472 because external applications cannot handle such paths.
1473 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1474 so all files Emacs knows how to handle. Using this with
1475 command `emacs' will open most files in Emacs. Beware that this
1476 will also open html files inside Emacs, unless you add
1477 (\"html\" . default) to the list as well.
1478 t Default for files not matched by any of the other options.
1479 `system' The system command to open files, like `open' on Windows
1480 and Mac OS X, and mailcap under GNU/Linux. This is the command
1481 that will be selected if you call `C-c C-o' with a double
1482 `C-u C-u' prefix.
1484 Possible values for the command are:
1485 `emacs' The file will be visited by the current Emacs process.
1486 `default' Use the default application for this file type, which is the
1487 association for t in the list, most likely in the system-specific
1488 part.
1489 This can be used to overrule an unwanted setting in the
1490 system-specific variable.
1491 `system' Use the system command for opening files, like \"open\".
1492 This command is specified by the entry whose car is `system'.
1493 Most likely, the system-specific version of this variable
1494 does define this command, but you can overrule/replace it
1495 here.
1496 string A command to be executed by a shell; %s will be replaced
1497 by the path to the file.
1498 sexp A Lisp form which will be evaluated. The file path will
1499 be available in the Lisp variable `file'.
1500 For more examples, see the system specific constants
1501 `org-file-apps-defaults-macosx'
1502 `org-file-apps-defaults-windowsnt'
1503 `org-file-apps-defaults-gnu'."
1504 :group 'org-link-follow
1505 :type '(repeat
1506 (cons (choice :value ""
1507 (string :tag "Extension")
1508 (const :tag "System command to open files" system)
1509 (const :tag "Default for unrecognized files" t)
1510 (const :tag "Remote file" remote)
1511 (const :tag "Links to a directory" directory)
1512 (const :tag "Any files that have Emacs modes"
1513 auto-mode))
1514 (choice :value ""
1515 (const :tag "Visit with Emacs" emacs)
1516 (const :tag "Use default" default)
1517 (const :tag "Use the system command" system)
1518 (string :tag "Command")
1519 (sexp :tag "Lisp form")))))
1521 (defgroup org-refile nil
1522 "Options concerning refiling entries in Org-mode."
1523 :tag "Org Refile"
1524 :group 'org)
1526 (defcustom org-directory "~/org"
1527 "Directory with org files.
1528 This is just a default location to look for Org files. There is no need
1529 at all to put your files into this directory. It is only used in the
1530 following situations:
1532 1. When a remember template specifies a target file that is not an
1533 absolute path. The path will then be interpreted relative to
1534 `org-directory'
1535 2. When a remember note is filed away in an interactive way (when exiting the
1536 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1537 with `org-directory' as the default path."
1538 :group 'org-refile
1539 :group 'org-remember
1540 :type 'directory)
1542 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1543 "Default target for storing notes.
1544 Used by the hooks for remember.el. This can be a string, or nil to mean
1545 the value of `remember-data-file'.
1546 You can set this on a per-template basis with the variable
1547 `org-remember-templates'."
1548 :group 'org-refile
1549 :group 'org-remember
1550 :type '(choice
1551 (const :tag "Default from remember-data-file" nil)
1552 file))
1554 (defcustom org-goto-interface 'outline
1555 "The default interface to be used for `org-goto'.
1556 Allowed values are:
1557 outline The interface shows an outline of the relevant file
1558 and the correct heading is found by moving through
1559 the outline or by searching with incremental search.
1560 outline-path-completion Headlines in the current buffer are offered via
1561 completion. This is the interface also used by
1562 the refile command."
1563 :group 'org-refile
1564 :type '(choice
1565 (const :tag "Outline" outline)
1566 (const :tag "Outline-path-completion" outline-path-completion)))
1568 (defcustom org-goto-max-level 5
1569 "Maximum level to be considered when running org-goto with refile interface."
1570 :group 'org-refile
1571 :type 'integer)
1573 (defcustom org-reverse-note-order nil
1574 "Non-nil means, store new notes at the beginning of a file or entry.
1575 When nil, new notes will be filed to the end of a file or entry.
1576 This can also be a list with cons cells of regular expressions that
1577 are matched against file names, and values."
1578 :group 'org-remember
1579 :group 'org-refile
1580 :type '(choice
1581 (const :tag "Reverse always" t)
1582 (const :tag "Reverse never" nil)
1583 (repeat :tag "By file name regexp"
1584 (cons regexp boolean))))
1586 (defcustom org-refile-targets nil
1587 "Targets for refiling entries with \\[org-refile].
1588 This is list of cons cells. Each cell contains:
1589 - a specification of the files to be considered, either a list of files,
1590 or a symbol whose function or variable value will be used to retrieve
1591 a file name or a list of file names. If you use `org-agenda-files' for
1592 that, all agenda files will be scanned for targets. Nil means, consider
1593 headings in the current buffer.
1594 - A specification of how to find candidate refile targets. This may be
1595 any of:
1596 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1597 This tag has to be present in all target headlines, inheritance will
1598 not be considered.
1599 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1600 todo keyword.
1601 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1602 headlines that are refiling targets.
1603 - a cons cell (:level . N). Any headline of level N is considered a target.
1604 Note that, when `org-odd-levels-only' is set, level corresponds to
1605 order in hierarchy, not to the number of stars.
1606 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1607 Note that, when `org-odd-levels-only' is set, level corresponds to
1608 order in hierarchy, not to the number of stars.
1610 You can set the variable `org-refile-target-verify-function' to a function
1611 to verify each headline found by the simple critery above.
1613 When this variable is nil, all top-level headlines in the current buffer
1614 are used, equivalent to the value `((nil . (:level . 1))'."
1615 :group 'org-refile
1616 :type '(repeat
1617 (cons
1618 (choice :value org-agenda-files
1619 (const :tag "All agenda files" org-agenda-files)
1620 (const :tag "Current buffer" nil)
1621 (function) (variable) (file))
1622 (choice :tag "Identify target headline by"
1623 (cons :tag "Specific tag" (const :value :tag) (string))
1624 (cons :tag "TODO keyword" (const :value :todo) (string))
1625 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1626 (cons :tag "Level number" (const :value :level) (integer))
1627 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1629 (defcustom org-refile-target-verify-function nil
1630 "Function to verify if the headline at point should be a refile target.
1631 The function will be called without arguments, with point at the
1632 beginning of the headline. It should return t and leave point
1633 where it is if the headline is a valid target for refiling.
1635 If the target should not be selected, the function must return nil.
1636 In addition to this, it may move point to a place from where the search
1637 should be continued. For example, the function may decide that the entire
1638 subtree of the current entry should be excluded and move point to the end
1639 of the subtree."
1640 :group 'org-refile
1641 :type 'function)
1643 (defcustom org-refile-use-outline-path nil
1644 "Non-nil means, provide refile targets as paths.
1645 So a level 3 headline will be available as level1/level2/level3.
1647 When the value is `file', also include the file name (without directory)
1648 into the path. In this case, you can also stop the completion after
1649 the file name, to get entries inserted as top level in the file.
1651 When `full-file-path', include the full file path."
1652 :group 'org-refile
1653 :type '(choice
1654 (const :tag "Not" nil)
1655 (const :tag "Yes" t)
1656 (const :tag "Start with file name" file)
1657 (const :tag "Start with full file path" full-file-path)))
1659 (defcustom org-outline-path-complete-in-steps t
1660 "Non-nil means, complete the outline path in hierarchical steps.
1661 When Org-mode uses the refile interface to select an outline path
1662 \(see variable `org-refile-use-outline-path'), the completion of
1663 the path can be done is a single go, or if can be done in steps down
1664 the headline hierarchy. Going in steps is probably the best if you
1665 do not use a special completion package like `ido' or `icicles'.
1666 However, when using these packages, going in one step can be very
1667 fast, while still showing the whole path to the entry."
1668 :group 'org-refile
1669 :type 'boolean)
1671 (defcustom org-refile-allow-creating-parent-nodes nil
1672 "Non-nil means, allow to create new nodes as refile targets.
1673 New nodes are then created by adding \"/new node name\" to the completion
1674 of an existing node. When the value of this variable is `confirm',
1675 new node creation must be confirmed by the user (recommended)
1676 When nil, the completion must match an existing entry.
1678 Note that, if the new heading is not seen by the criteria
1679 listed in `org-refile-targets', multiple instances of the same
1680 heading would be created by trying again to file under the new
1681 heading."
1682 :group 'org-refile
1683 :type '(choice
1684 (const :tag "Never" nil)
1685 (const :tag "Always" t)
1686 (const :tag "Prompt for confirmation" confirm)))
1688 (defgroup org-todo nil
1689 "Options concerning TODO items in Org-mode."
1690 :tag "Org TODO"
1691 :group 'org)
1693 (defgroup org-progress nil
1694 "Options concerning Progress logging in Org-mode."
1695 :tag "Org Progress"
1696 :group 'org-time)
1698 (defvar org-todo-interpretation-widgets
1700 (:tag "Sequence (cycling hits every state)" sequence)
1701 (:tag "Type (cycling directly to DONE)" type))
1702 "The available interpretation symbols for customizing
1703 `org-todo-keywords'.
1704 Interested libraries should add to this list.")
1706 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1707 "List of TODO entry keyword sequences and their interpretation.
1708 \\<org-mode-map>This is a list of sequences.
1710 Each sequence starts with a symbol, either `sequence' or `type',
1711 indicating if the keywords should be interpreted as a sequence of
1712 action steps, or as different types of TODO items. The first
1713 keywords are states requiring action - these states will select a headline
1714 for inclusion into the global TODO list Org-mode produces. If one of
1715 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1716 signify that no further action is necessary. If \"|\" is not found,
1717 the last keyword is treated as the only DONE state of the sequence.
1719 The command \\[org-todo] cycles an entry through these states, and one
1720 additional state where no keyword is present. For details about this
1721 cycling, see the manual.
1723 TODO keywords and interpretation can also be set on a per-file basis with
1724 the special #+SEQ_TODO and #+TYP_TODO lines.
1726 Each keyword can optionally specify a character for fast state selection
1727 \(in combination with the variable `org-use-fast-todo-selection')
1728 and specifiers for state change logging, using the same syntax
1729 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1730 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1731 indicates to record a time stamp each time this state is selected.
1733 Each keyword may also specify if a timestamp or a note should be
1734 recorded when entering or leaving the state, by adding additional
1735 characters in the parenthesis after the keyword. This looks like this:
1736 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1737 record only the time of the state change. With X and Y being either
1738 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1739 Y when leaving the state if and only if the *target* state does not
1740 define X. You may omit any of the fast-selection key or X or /Y,
1741 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1743 For backward compatibility, this variable may also be just a list
1744 of keywords - in this case the interpretation (sequence or type) will be
1745 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1746 :group 'org-todo
1747 :group 'org-keywords
1748 :type '(choice
1749 (repeat :tag "Old syntax, just keywords"
1750 (string :tag "Keyword"))
1751 (repeat :tag "New syntax"
1752 (cons
1753 (choice
1754 :tag "Interpretation"
1755 ;;Quick and dirty way to see
1756 ;;`org-todo-interpretations'. This takes the
1757 ;;place of item arguments
1758 :convert-widget
1759 (lambda (widget)
1760 (widget-put widget
1761 :args (mapcar
1762 #'(lambda (x)
1763 (widget-convert
1764 (cons 'const x)))
1765 org-todo-interpretation-widgets))
1766 widget))
1767 (repeat
1768 (string :tag "Keyword"))))))
1770 (defvar org-todo-keywords-1 nil
1771 "All TODO and DONE keywords active in a buffer.")
1772 (make-variable-buffer-local 'org-todo-keywords-1)
1773 (defvar org-todo-keywords-for-agenda nil)
1774 (defvar org-done-keywords-for-agenda nil)
1775 (defvar org-drawers-for-agenda nil)
1776 (defvar org-todo-keyword-alist-for-agenda nil)
1777 (defvar org-tag-alist-for-agenda nil)
1778 (defvar org-agenda-contributing-files nil)
1779 (defvar org-not-done-keywords nil)
1780 (make-variable-buffer-local 'org-not-done-keywords)
1781 (defvar org-done-keywords nil)
1782 (make-variable-buffer-local 'org-done-keywords)
1783 (defvar org-todo-heads nil)
1784 (make-variable-buffer-local 'org-todo-heads)
1785 (defvar org-todo-sets nil)
1786 (make-variable-buffer-local 'org-todo-sets)
1787 (defvar org-todo-log-states nil)
1788 (make-variable-buffer-local 'org-todo-log-states)
1789 (defvar org-todo-kwd-alist nil)
1790 (make-variable-buffer-local 'org-todo-kwd-alist)
1791 (defvar org-todo-key-alist nil)
1792 (make-variable-buffer-local 'org-todo-key-alist)
1793 (defvar org-todo-key-trigger nil)
1794 (make-variable-buffer-local 'org-todo-key-trigger)
1796 (defcustom org-todo-interpretation 'sequence
1797 "Controls how TODO keywords are interpreted.
1798 This variable is in principle obsolete and is only used for
1799 backward compatibility, if the interpretation of todo keywords is
1800 not given already in `org-todo-keywords'. See that variable for
1801 more information."
1802 :group 'org-todo
1803 :group 'org-keywords
1804 :type '(choice (const sequence)
1805 (const type)))
1807 (defcustom org-use-fast-todo-selection t
1808 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1809 This variable describes if and under what circumstances the cycling
1810 mechanism for TODO keywords will be replaced by a single-key, direct
1811 selection scheme.
1813 When nil, fast selection is never used.
1815 When the symbol `prefix', it will be used when `org-todo' is called with
1816 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1817 in an agenda buffer.
1819 When t, fast selection is used by default. In this case, the prefix
1820 argument forces cycling instead.
1822 In all cases, the special interface is only used if access keys have actually
1823 been assigned by the user, i.e. if keywords in the configuration are followed
1824 by a letter in parenthesis, like TODO(t)."
1825 :group 'org-todo
1826 :type '(choice
1827 (const :tag "Never" nil)
1828 (const :tag "By default" t)
1829 (const :tag "Only with C-u C-c C-t" prefix)))
1831 (defcustom org-provide-todo-statistics t
1832 "Non-nil means, update todo statistics after insert and toggle.
1833 ALL-HEADLINES means update todo statistics by including headlines
1834 with no TODO keyword as well, counting them as not done.
1835 A list of TODO keywords means the same, but skip keywords that are
1836 not in this list.
1838 When this is set, todo statistics is updated in the parent of the
1839 current entry each time a todo state is changed."
1840 :group 'org-todo
1841 :type '(choice
1842 (const :tag "Yes, only for TODO entries" t)
1843 (const :tag "Yes, including all entries" 'all-headlines)
1844 (repeat :tag "Yes, for TODOs in this list"
1845 (string :tag "TODO keyword"))
1846 (other :tag "No TODO statistics" nil)))
1848 (defcustom org-hierarchical-todo-statistics t
1849 "Non-nil means, TODO statistics covers just direct children.
1850 When nil, all entries in the subtree are considered.
1851 This has only an effect if `org-provide-todo-statistics' is set.
1852 To set this to nil for only a single subtree, use a COOKIE_DATA
1853 property and include the word \"recursive\" into the value."
1854 :group 'org-todo
1855 :type 'boolean)
1857 (defcustom org-after-todo-state-change-hook nil
1858 "Hook which is run after the state of a TODO item was changed.
1859 The new state (a string with a TODO keyword, or nil) is available in the
1860 Lisp variable `state'."
1861 :group 'org-todo
1862 :type 'hook)
1864 (defvar org-blocker-hook nil
1865 "Hook for functions that are allowed to block a state change.
1867 Each function gets as its single argument a property list, see
1868 `org-trigger-hook' for more information about this list.
1870 If any of the functions in this hook returns nil, the state change
1871 is blocked.")
1873 (defvar org-trigger-hook nil
1874 "Hook for functions that are triggered by a state change.
1876 Each function gets as its single argument a property list with at least
1877 the following elements:
1879 (:type type-of-change :position pos-at-entry-start
1880 :from old-state :to new-state)
1882 Depending on the type, more properties may be present.
1884 This mechanism is currently implemented for:
1886 TODO state changes
1887 ------------------
1888 :type todo-state-change
1889 :from previous state (keyword as a string), or nil, or a symbol
1890 'todo' or 'done', to indicate the general type of state.
1891 :to new state, like in :from")
1893 (defcustom org-enforce-todo-dependencies nil
1894 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1895 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1896 be blocked if any prior sibling is not yet done.
1897 Finally, if the parent is blocked because of ordered siblings of its own,
1898 the child will also be blocked.
1899 This variable needs to be set before org.el is loaded, and you need to
1900 restart Emacs after a change to make the change effective. The only way
1901 to change is while Emacs is running is through the customize interface."
1902 :set (lambda (var val)
1903 (set var val)
1904 (if val
1905 (add-hook 'org-blocker-hook
1906 'org-block-todo-from-children-or-siblings-or-parent)
1907 (remove-hook 'org-blocker-hook
1908 'org-block-todo-from-children-or-siblings-or-parent)))
1909 :group 'org-todo
1910 :type 'boolean)
1912 (defcustom org-enforce-todo-checkbox-dependencies nil
1913 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1914 When this is nil, checkboxes have no influence on switching TODO states.
1915 When non-nil, you first need to check off all check boxes before the TODO
1916 entry can be switched to DONE.
1917 This variable needs to be set before org.el is loaded, and you need to
1918 restart Emacs after a change to make the change effective. The only way
1919 to change is while Emacs is running is through the customize interface."
1920 :set (lambda (var val)
1921 (set var val)
1922 (if val
1923 (add-hook 'org-blocker-hook
1924 'org-block-todo-from-checkboxes)
1925 (remove-hook 'org-blocker-hook
1926 'org-block-todo-from-checkboxes)))
1927 :group 'org-todo
1928 :type 'boolean)
1930 (defcustom org-treat-insert-todo-heading-as-state-change nil
1931 "Non-nil means, inserting a TODO heading is treated as state change.
1932 So when the command \\[org-insert-todo-heading] is used, state change
1933 logging will apply if appropriate. When nil, the new TODO item will
1934 be inserted directly, and no logging will take place."
1935 :group 'org-todo
1936 :type 'boolean)
1938 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1939 "Non-nil means, switching TODO states with S-cursor counts as state change.
1940 This is the default behavior. However, setting this to nil allows a
1941 convenient way to select a TODO state and bypass any logging associated
1942 with that."
1943 :group 'org-todo
1944 :type 'boolean)
1946 (defcustom org-todo-state-tags-triggers nil
1947 "Tag changes that should be triggered by TODO state changes.
1948 This is a list. Each entry is
1950 (state-change (tag . flag) .......)
1952 State-change can be a string with a state, and empty string to indicate the
1953 state that has no TODO keyword, or it can be one of the symbols `todo'
1954 or `done', meaning any not-done or done state, respectively."
1955 :group 'org-todo
1956 :group 'org-tags
1957 :type '(repeat
1958 (cons (choice :tag "When changing to"
1959 (const :tag "Not-done state" todo)
1960 (const :tag "Done state" done)
1961 (string :tag "State"))
1962 (repeat
1963 (cons :tag "Tag action"
1964 (string :tag "Tag")
1965 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1967 (defcustom org-log-done nil
1968 "Information to record when a task moves to the DONE state.
1970 Possible values are:
1972 nil Don't add anything, just change the keyword
1973 time Add a time stamp to the task
1974 note Prompt for a note and add it with template `org-log-note-headings'
1976 This option can also be set with on a per-file-basis with
1978 #+STARTUP: nologdone
1979 #+STARTUP: logdone
1980 #+STARTUP: lognotedone
1982 You can have local logging settings for a subtree by setting the LOGGING
1983 property to one or more of these keywords."
1984 :group 'org-todo
1985 :group 'org-progress
1986 :type '(choice
1987 (const :tag "No logging" nil)
1988 (const :tag "Record CLOSED timestamp" time)
1989 (const :tag "Record CLOSED timestamp with note." note)))
1991 ;; Normalize old uses of org-log-done.
1992 (cond
1993 ((eq org-log-done t) (setq org-log-done 'time))
1994 ((and (listp org-log-done) (memq 'done org-log-done))
1995 (setq org-log-done 'note)))
1997 (defcustom org-log-reschedule nil
1998 "Information to record when the scheduling date of a tasks is modified.
2000 Possible values are:
2002 nil Don't add anything, just change the date
2003 time Add a time stamp to the task
2004 note Prompt for a note and add it with template `org-log-note-headings'
2006 This option can also be set with on a per-file-basis with
2008 #+STARTUP: nologreschedule
2009 #+STARTUP: logreschedule
2010 #+STARTUP: lognotereschedule"
2011 :group 'org-todo
2012 :group 'org-progress
2013 :type '(choice
2014 (const :tag "No logging" nil)
2015 (const :tag "Record timestamp" time)
2016 (const :tag "Record timestamp with note." note)))
2018 (defcustom org-log-redeadline nil
2019 "Information to record when the deadline date of a tasks is modified.
2021 Possible values are:
2023 nil Don't add anything, just change the date
2024 time Add a time stamp to the task
2025 note Prompt for a note and add it with template `org-log-note-headings'
2027 This option can also be set with on a per-file-basis with
2029 #+STARTUP: nologredeadline
2030 #+STARTUP: logredeadline
2031 #+STARTUP: lognoteredeadline
2033 You can have local logging settings for a subtree by setting the LOGGING
2034 property to one or more of these keywords."
2035 :group 'org-todo
2036 :group 'org-progress
2037 :type '(choice
2038 (const :tag "No logging" nil)
2039 (const :tag "Record timestamp" time)
2040 (const :tag "Record timestamp with note." note)))
2042 (defcustom org-log-note-clock-out nil
2043 "Non-nil means, record a note when clocking out of an item.
2044 This can also be configured on a per-file basis by adding one of
2045 the following lines anywhere in the buffer:
2047 #+STARTUP: lognoteclock-out
2048 #+STARTUP: nolognoteclock-out"
2049 :group 'org-todo
2050 :group 'org-progress
2051 :type 'boolean)
2053 (defcustom org-log-done-with-time t
2054 "Non-nil means, the CLOSED time stamp will contain date and time.
2055 When nil, only the date will be recorded."
2056 :group 'org-progress
2057 :type 'boolean)
2059 (defcustom org-log-note-headings
2060 '((done . "CLOSING NOTE %t")
2061 (state . "State %-12s from %-12S %t")
2062 (note . "Note taken on %t")
2063 (reschedule . "Rescheduled from %S on %t")
2064 (delschedule . "Not scheduled, was %S on %t")
2065 (redeadline . "New deadline from %S on %t")
2066 (deldeadline . "Removed deadline, was %S on %t")
2067 (clock-out . ""))
2068 "Headings for notes added to entries.
2069 The value is an alist, with the car being a symbol indicating the note
2070 context, and the cdr is the heading to be used. The heading may also be the
2071 empty string.
2072 %t in the heading will be replaced by a time stamp.
2073 %s will be replaced by the new TODO state, in double quotes.
2074 %S will be replaced by the old TODO state, in double quotes.
2075 %u will be replaced by the user name.
2076 %U will be replaced by the full user name.
2078 In fact, it is not a good idea to change the `state' entry, because
2079 agenda log mode depends on the format of these entries."
2080 :group 'org-todo
2081 :group 'org-progress
2082 :type '(list :greedy t
2083 (cons (const :tag "Heading when closing an item" done) string)
2084 (cons (const :tag
2085 "Heading when changing todo state (todo sequence only)"
2086 state) string)
2087 (cons (const :tag "Heading when just taking a note" note) string)
2088 (cons (const :tag "Heading when clocking out" clock-out) string)
2089 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2090 (cons (const :tag "Heading when rescheduling" reschedule) string)
2091 (cons (const :tag "Heading when changing deadline" redeadline) string
2092 (cons (const :tag "Heading when deleting a deadline" deldeadline) string))))
2094 (unless (assq 'note org-log-note-headings)
2095 (push '(note . "%t") org-log-note-headings))
2097 (defcustom org-log-into-drawer nil
2098 "Non-nil means, insert state change notes and time stamps into a drawer.
2099 When nil, state changes notes will be inserted after the headline and
2100 any scheduling and clock lines, but not inside a drawer.
2102 The value of this variable should be the name of the drawer to use.
2103 LOGBOOK is proposed at the default drawer for this purpose, you can
2104 also set this to a string to define the drawer of your choice.
2106 A value of t is also allowed, representing \"LOGBOOK\".
2108 If this variable is set, `org-log-state-notes-insert-after-drawers'
2109 will be ignored.
2111 You can set the property LOG_INTO_DRAWER to overrule this setting for
2112 a subtree."
2113 :group 'org-todo
2114 :group 'org-progress
2115 :type '(choice
2116 (const :tag "Not into a drawer" nil)
2117 (const :tag "LOGBOOK" t)
2118 (string :tag "Other")))
2120 (if (fboundp 'defvaralias)
2121 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2123 (defun org-log-into-drawer ()
2124 "Return the value of `org-log-into-drawer', but let properties overrule.
2125 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2126 used instead of the default value."
2127 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2128 (cond
2129 ((or (not p) (equal p "nil")) org-log-into-drawer)
2130 ((equal p "t") "LOGBOOK")
2131 (t p))))
2133 (defcustom org-log-state-notes-insert-after-drawers nil
2134 "Non-nil means, insert state change notes after any drawers in entry.
2135 Only the drawers that *immediately* follow the headline and the
2136 deadline/scheduled line are skipped.
2137 When nil, insert notes right after the heading and perhaps the line
2138 with deadline/scheduling if present.
2140 This variable will have no effect if `org-log-into-drawer' is
2141 set."
2142 :group 'org-todo
2143 :group 'org-progress
2144 :type 'boolean)
2146 (defcustom org-log-states-order-reversed t
2147 "Non-nil means, the latest state change note will be directly after heading.
2148 When nil, the notes will be orderer according to time."
2149 :group 'org-todo
2150 :group 'org-progress
2151 :type 'boolean)
2153 (defcustom org-log-repeat 'time
2154 "Non-nil means, record moving through the DONE state when triggering repeat.
2155 An auto-repeating task is immediately switched back to TODO when
2156 marked DONE. If you are not logging state changes (by adding \"@\"
2157 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2158 record a closing note, there will be no record of the task moving
2159 through DONE. This variable forces taking a note anyway.
2161 nil Don't force a record
2162 time Record a time stamp
2163 note Record a note
2165 This option can also be set with on a per-file-basis with
2167 #+STARTUP: logrepeat
2168 #+STARTUP: lognoterepeat
2169 #+STARTUP: nologrepeat
2171 You can have local logging settings for a subtree by setting the LOGGING
2172 property to one or more of these keywords."
2173 :group 'org-todo
2174 :group 'org-progress
2175 :type '(choice
2176 (const :tag "Don't force a record" nil)
2177 (const :tag "Force recording the DONE state" time)
2178 (const :tag "Force recording a note with the DONE state" note)))
2181 (defgroup org-priorities nil
2182 "Priorities in Org-mode."
2183 :tag "Org Priorities"
2184 :group 'org-todo)
2186 (defcustom org-enable-priority-commands t
2187 "Non-nil means, priority commands are active.
2188 When nil, these commands will be disabled, so that you never accidentally
2189 set a priority."
2190 :group 'org-priorities
2191 :type 'boolean)
2193 (defcustom org-highest-priority ?A
2194 "The highest priority of TODO items. A character like ?A, ?B etc.
2195 Must have a smaller ASCII number than `org-lowest-priority'."
2196 :group 'org-priorities
2197 :type 'character)
2199 (defcustom org-lowest-priority ?C
2200 "The lowest priority of TODO items. A character like ?A, ?B etc.
2201 Must have a larger ASCII number than `org-highest-priority'."
2202 :group 'org-priorities
2203 :type 'character)
2205 (defcustom org-default-priority ?B
2206 "The default priority of TODO items.
2207 This is the priority an item get if no explicit priority is given."
2208 :group 'org-priorities
2209 :type 'character)
2211 (defcustom org-priority-start-cycle-with-default t
2212 "Non-nil means, start with default priority when starting to cycle.
2213 When this is nil, the first step in the cycle will be (depending on the
2214 command used) one higher or lower that the default priority."
2215 :group 'org-priorities
2216 :type 'boolean)
2218 (defgroup org-time nil
2219 "Options concerning time stamps and deadlines in Org-mode."
2220 :tag "Org Time"
2221 :group 'org)
2223 (defcustom org-insert-labeled-timestamps-at-point nil
2224 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2225 When nil, these labeled time stamps are forces into the second line of an
2226 entry, just after the headline. When scheduling from the global TODO list,
2227 the time stamp will always be forced into the second line."
2228 :group 'org-time
2229 :type 'boolean)
2231 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2232 "Formats for `format-time-string' which are used for time stamps.
2233 It is not recommended to change this constant.")
2235 (defcustom org-time-stamp-rounding-minutes '(0 5)
2236 "Number of minutes to round time stamps to.
2237 These are two values, the first applies when first creating a time stamp.
2238 The second applies when changing it with the commands `S-up' and `S-down'.
2239 When changing the time stamp, this means that it will change in steps
2240 of N minutes, as given by the second value.
2242 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2243 numbers should be factors of 60, so for example 5, 10, 15.
2245 When this is larger than 1, you can still force an exact time-stamp by using
2246 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2247 and by using a prefix arg to `S-up/down' to specify the exact number
2248 of minutes to shift."
2249 :group 'org-time
2250 :get '(lambda (var) ; Make sure all entries have 5 elements
2251 (if (integerp (default-value var))
2252 (list (default-value var) 5)
2253 (default-value var)))
2254 :type '(list
2255 (integer :tag "when inserting times")
2256 (integer :tag "when modifying times")))
2258 ;; Normalize old customizations of this variable.
2259 (when (integerp org-time-stamp-rounding-minutes)
2260 (setq org-time-stamp-rounding-minutes
2261 (list org-time-stamp-rounding-minutes
2262 org-time-stamp-rounding-minutes)))
2264 (defcustom org-display-custom-times nil
2265 "Non-nil means, overlay custom formats over all time stamps.
2266 The formats are defined through the variable `org-time-stamp-custom-formats'.
2267 To turn this on on a per-file basis, insert anywhere in the file:
2268 #+STARTUP: customtime"
2269 :group 'org-time
2270 :set 'set-default
2271 :type 'sexp)
2272 (make-variable-buffer-local 'org-display-custom-times)
2274 (defcustom org-time-stamp-custom-formats
2275 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2276 "Custom formats for time stamps. See `format-time-string' for the syntax.
2277 These are overlayed over the default ISO format if the variable
2278 `org-display-custom-times' is set. Time like %H:%M should be at the
2279 end of the second format. The custom formats are also honored by export
2280 commands, if custom time display is turned on at the time of export."
2281 :group 'org-time
2282 :type 'sexp)
2284 (defun org-time-stamp-format (&optional long inactive)
2285 "Get the right format for a time string."
2286 (let ((f (if long (cdr org-time-stamp-formats)
2287 (car org-time-stamp-formats))))
2288 (if inactive
2289 (concat "[" (substring f 1 -1) "]")
2290 f)))
2292 (defcustom org-time-clocksum-format "%d:%02d"
2293 "The format string used when creating CLOCKSUM lines, or when
2294 org-mode generates a time duration."
2295 :group 'org-time
2296 :type 'string)
2298 (defcustom org-time-clocksum-use-fractional nil
2299 "If non-nil, \\[org-clock-display] uses fractional times.
2300 org-mode generates a time duration."
2301 :group 'org-time
2302 :type 'boolean)
2304 (defcustom org-time-clocksum-fractional-format "%.2f"
2305 "The format string used when creating CLOCKSUM lines, or when
2306 org-mode generates a time duration."
2307 :group 'org-time
2308 :type 'string)
2310 (defcustom org-deadline-warning-days 14
2311 "No. of days before expiration during which a deadline becomes active.
2312 This variable governs the display in sparse trees and in the agenda.
2313 When 0 or negative, it means use this number (the absolute value of it)
2314 even if a deadline has a different individual lead time specified.
2316 Custom commands can set this variable in the options section."
2317 :group 'org-time
2318 :group 'org-agenda-daily/weekly
2319 :type 'integer)
2321 (defcustom org-read-date-prefer-future t
2322 "Non-nil means, assume future for incomplete date input from user.
2323 This affects the following situations:
2324 1. The user gives a month but not a year.
2325 For example, if it is april and you enter \"feb 2\", this will be read
2326 as feb 2, *next* year. \"May 5\", however, will be this year.
2327 2. The user gives a day, but no month.
2328 For example, if today is the 15th, and you enter \"3\", Org-mode will
2329 read this as the third of *next* month. However, if you enter \"17\",
2330 it will be considered as *this* month.
2332 If you set this variable to the symbol `time', then also the following
2333 will work:
2335 3. If the user gives a time, but no day. If the time is before now,
2336 to will be interpreted as tomorrow.
2338 Currently none of this works for ISO week specifications.
2340 When this option is nil, the current day, month and year will always be
2341 used as defaults."
2342 :group 'org-time
2343 :type '(choice
2344 (const :tag "Never" nil)
2345 (const :tag "Check month and day" t)
2346 (const :tag "Check month, day, and time" time)))
2348 (defcustom org-read-date-display-live t
2349 "Non-nil means, display current interpretation of date prompt live.
2350 This display will be in an overlay, in the minibuffer."
2351 :group 'org-time
2352 :type 'boolean)
2354 (defcustom org-read-date-popup-calendar t
2355 "Non-nil means, pop up a calendar when prompting for a date.
2356 In the calendar, the date can be selected with mouse-1. However, the
2357 minibuffer will also be active, and you can simply enter the date as well.
2358 When nil, only the minibuffer will be available."
2359 :group 'org-time
2360 :type 'boolean)
2361 (if (fboundp 'defvaralias)
2362 (defvaralias 'org-popup-calendar-for-date-prompt
2363 'org-read-date-popup-calendar))
2365 (defcustom org-read-date-minibuffer-setup-hook nil
2366 "Hook to be used to set up keys for the date/time interface.
2367 Add key definitions to `minibuffer-local-map', which will be a temporary
2368 copy."
2369 :group 'org-time
2370 :type 'hook)
2372 (defcustom org-extend-today-until 0
2373 "The hour when your day really ends. Must be an integer.
2374 This has influence for the following applications:
2375 - When switching the agenda to \"today\". It it is still earlier than
2376 the time given here, the day recognized as TODAY is actually yesterday.
2377 - When a date is read from the user and it is still before the time given
2378 here, the current date and time will be assumed to be yesterday, 23:59.
2379 Also, timestamps inserted in remember templates follow this rule.
2381 IMPORTANT: This is a feature whose implementation is and likely will
2382 remain incomplete. Really, it is only here because past midnight seems to
2383 be the favorite working time of John Wiegley :-)"
2384 :group 'org-time
2385 :type 'integer)
2387 (defcustom org-edit-timestamp-down-means-later nil
2388 "Non-nil means, S-down will increase the time in a time stamp.
2389 When nil, S-up will increase."
2390 :group 'org-time
2391 :type 'boolean)
2393 (defcustom org-calendar-follow-timestamp-change t
2394 "Non-nil means, make the calendar window follow timestamp changes.
2395 When a timestamp is modified and the calendar window is visible, it will be
2396 moved to the new date."
2397 :group 'org-time
2398 :type 'boolean)
2400 (defgroup org-tags nil
2401 "Options concerning tags in Org-mode."
2402 :tag "Org Tags"
2403 :group 'org)
2405 (defcustom org-tag-alist nil
2406 "List of tags allowed in Org-mode files.
2407 When this list is nil, Org-mode will base TAG input on what is already in the
2408 buffer.
2409 The value of this variable is an alist, the car of each entry must be a
2410 keyword as a string, the cdr may be a character that is used to select
2411 that tag through the fast-tag-selection interface.
2412 See the manual for details."
2413 :group 'org-tags
2414 :type '(repeat
2415 (choice
2416 (cons (string :tag "Tag name")
2417 (character :tag "Access char"))
2418 (list :tag "Start radio group"
2419 (const :startgroup)
2420 (option (string :tag "Group description")))
2421 (list :tag "End radio group"
2422 (const :endgroup)
2423 (option (string :tag "Group description")))
2424 (const :tag "New line" (:newline)))))
2426 (defcustom org-tag-persistent-alist nil
2427 "List of tags that will always appear in all Org-mode files.
2428 This is in addition to any in buffer settings or customizations
2429 of `org-tag-alist'.
2430 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2431 The value of this variable is an alist, the car of each entry must be a
2432 keyword as a string, the cdr may be a character that is used to select
2433 that tag through the fast-tag-selection interface.
2434 See the manual for details.
2435 To disable these tags on a per-file basis, insert anywhere in the file:
2436 #+STARTUP: noptag"
2437 :group 'org-tags
2438 :type '(repeat
2439 (choice
2440 (cons (string :tag "Tag name")
2441 (character :tag "Access char"))
2442 (const :tag "Start radio group" (:startgroup))
2443 (const :tag "End radio group" (:endgroup))
2444 (const :tag "New line" (:newline)))))
2446 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2447 "If non-nil, always offer completion for all tags of all agenda files.
2448 Instead of customizing this variable directly, you might want to
2449 set it locally for remember buffers, because there no list of
2450 tags in that file can be created dynamically (there are none).
2452 (add-hook 'org-remember-mode-hook
2453 (lambda ()
2454 (set (make-local-variable
2455 'org-complete-tags-always-offer-all-agenda-tags)
2456 t)))"
2457 :group 'org-tags
2458 :type 'boolean)
2460 (defvar org-file-tags nil
2461 "List of tags that can be inherited by all entries in the file.
2462 The tags will be inherited if the variable `org-use-tag-inheritance'
2463 says they should be.
2464 This variable is populated from #+FILETAGS lines.")
2466 (defcustom org-use-fast-tag-selection 'auto
2467 "Non-nil means, use fast tag selection scheme.
2468 This is a special interface to select and deselect tags with single keys.
2469 When nil, fast selection is never used.
2470 When the symbol `auto', fast selection is used if and only if selection
2471 characters for tags have been configured, either through the variable
2472 `org-tag-alist' or through a #+TAGS line in the buffer.
2473 When t, fast selection is always used and selection keys are assigned
2474 automatically if necessary."
2475 :group 'org-tags
2476 :type '(choice
2477 (const :tag "Always" t)
2478 (const :tag "Never" nil)
2479 (const :tag "When selection characters are configured" 'auto)))
2481 (defcustom org-fast-tag-selection-single-key nil
2482 "Non-nil means, fast tag selection exits after first change.
2483 When nil, you have to press RET to exit it.
2484 During fast tag selection, you can toggle this flag with `C-c'.
2485 This variable can also have the value `expert'. In this case, the window
2486 displaying the tags menu is not even shown, until you press C-c again."
2487 :group 'org-tags
2488 :type '(choice
2489 (const :tag "No" nil)
2490 (const :tag "Yes" t)
2491 (const :tag "Expert" expert)))
2493 (defvar org-fast-tag-selection-include-todo nil
2494 "Non-nil means, fast tags selection interface will also offer TODO states.
2495 This is an undocumented feature, you should not rely on it.")
2497 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2498 "The column to which tags should be indented in a headline.
2499 If this number is positive, it specifies the column. If it is negative,
2500 it means that the tags should be flushright to that column. For example,
2501 -80 works well for a normal 80 character screen."
2502 :group 'org-tags
2503 :type 'integer)
2505 (defcustom org-auto-align-tags t
2506 "Non-nil means, realign tags after pro/demotion of TODO state change.
2507 These operations change the length of a headline and therefore shift
2508 the tags around. With this options turned on, after each such operation
2509 the tags are again aligned to `org-tags-column'."
2510 :group 'org-tags
2511 :type 'boolean)
2513 (defcustom org-use-tag-inheritance t
2514 "Non-nil means, tags in levels apply also for sublevels.
2515 When nil, only the tags directly given in a specific line apply there.
2516 This may also be a list of tags that should be inherited, or a regexp that
2517 matches tags that should be inherited. Additional control is possible
2518 with the variable `org-tags-exclude-from-inheritance' which gives an
2519 explicit list of tags to be excluded from inheritance., even if the value of
2520 `org-use-tag-inheritance' would select it for inheritance.
2522 If this option is t, a match early-on in a tree can lead to a large
2523 number of matches in the subtree when constructing the agenda or creating
2524 a sparse tree. If you only want to see the first match in a tree during
2525 a search, check out the variable `org-tags-match-list-sublevels'."
2526 :group 'org-tags
2527 :type '(choice
2528 (const :tag "Not" nil)
2529 (const :tag "Always" t)
2530 (repeat :tag "Specific tags" (string :tag "Tag"))
2531 (regexp :tag "Tags matched by regexp")))
2533 (defcustom org-tags-exclude-from-inheritance nil
2534 "List of tags that should never be inherited.
2535 This is a way to exclude a few tags from inheritance. For way to do
2536 the opposite, to actively allow inheritance for selected tags,
2537 see the variable `org-use-tag-inheritance'."
2538 :group 'org-tags
2539 :type '(repeat (string :tag "Tag")))
2541 (defun org-tag-inherit-p (tag)
2542 "Check if TAG is one that should be inherited."
2543 (cond
2544 ((member tag org-tags-exclude-from-inheritance) nil)
2545 ((eq org-use-tag-inheritance t) t)
2546 ((not org-use-tag-inheritance) nil)
2547 ((stringp org-use-tag-inheritance)
2548 (string-match org-use-tag-inheritance tag))
2549 ((listp org-use-tag-inheritance)
2550 (member tag org-use-tag-inheritance))
2551 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2553 (defcustom org-tags-match-list-sublevels t
2554 "Non-nil means list also sublevels of headlines matching a search.
2555 This variable applies to tags/property searches, and also to stuck
2556 projects because this search is based on a tags match as well.
2558 When set to the symbol `indented', sublevels are indented with
2559 leading dots.
2561 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2562 the sublevels of a headline matching a tag search often also match
2563 the same search. Listing all of them can create very long lists.
2564 Setting this variable to nil causes subtrees of a match to be skipped.
2566 This variable is semi-obsolete and probably should always be true. It
2567 is better to limit inheritance to certain tags using the variables
2568 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2569 :group 'org-tags
2570 :type '(choice
2571 (const :tag "No, don't list them" nil)
2572 (const :tag "Yes, do list them" t)
2573 (const :tag "List them, indented with leading dots" indented)))
2575 (defcustom org-tags-sort-function nil
2576 "When set, tags are sorted using this function as a comparator"
2577 :group 'org-tags
2578 :type '(choice
2579 (const :tag "No sorting" nil)
2580 (const :tag "Alphabetical" string<)
2581 (const :tag "Reverse alphabetical" string>)
2582 (function :tag "Custom function" nil)))
2584 (defvar org-tags-history nil
2585 "History of minibuffer reads for tags.")
2586 (defvar org-last-tags-completion-table nil
2587 "The last used completion table for tags.")
2588 (defvar org-after-tags-change-hook nil
2589 "Hook that is run after the tags in a line have changed.")
2591 (defgroup org-properties nil
2592 "Options concerning properties in Org-mode."
2593 :tag "Org Properties"
2594 :group 'org)
2596 (defcustom org-property-format "%-10s %s"
2597 "How property key/value pairs should be formatted by `indent-line'.
2598 When `indent-line' hits a property definition, it will format the line
2599 according to this format, mainly to make sure that the values are
2600 lined-up with respect to each other."
2601 :group 'org-properties
2602 :type 'string)
2604 (defcustom org-use-property-inheritance nil
2605 "Non-nil means, properties apply also for sublevels.
2607 This setting is chiefly used during property searches. Turning it on can
2608 cause significant overhead when doing a search, which is why it is not
2609 on by default.
2611 When nil, only the properties directly given in the current entry count.
2612 When t, every property is inherited. The value may also be a list of
2613 properties that should have inheritance, or a regular expression matching
2614 properties that should be inherited.
2616 However, note that some special properties use inheritance under special
2617 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2618 and the properties ending in \"_ALL\" when they are used as descriptor
2619 for valid values of a property.
2621 Note for programmers:
2622 When querying an entry with `org-entry-get', you can control if inheritance
2623 should be used. By default, `org-entry-get' looks only at the local
2624 properties. You can request inheritance by setting the inherit argument
2625 to t (to force inheritance) or to `selective' (to respect the setting
2626 in this variable)."
2627 :group 'org-properties
2628 :type '(choice
2629 (const :tag "Not" nil)
2630 (const :tag "Always" t)
2631 (repeat :tag "Specific properties" (string :tag "Property"))
2632 (regexp :tag "Properties matched by regexp")))
2634 (defun org-property-inherit-p (property)
2635 "Check if PROPERTY is one that should be inherited."
2636 (cond
2637 ((eq org-use-property-inheritance t) t)
2638 ((not org-use-property-inheritance) nil)
2639 ((stringp org-use-property-inheritance)
2640 (string-match org-use-property-inheritance property))
2641 ((listp org-use-property-inheritance)
2642 (member property org-use-property-inheritance))
2643 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2645 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2646 "The default column format, if no other format has been defined.
2647 This variable can be set on the per-file basis by inserting a line
2649 #+COLUMNS: %25ITEM ....."
2650 :group 'org-properties
2651 :type 'string)
2653 (defcustom org-columns-ellipses ".."
2654 "The ellipses to be used when a field in column view is truncated.
2655 When this is the empty string, as many characters as possible are shown,
2656 but then there will be no visual indication that the field has been truncated.
2657 When this is a string of length N, the last N characters of a truncated
2658 field are replaced by this string. If the column is narrower than the
2659 ellipses string, only part of the ellipses string will be shown."
2660 :group 'org-properties
2661 :type 'string)
2663 (defcustom org-columns-modify-value-for-display-function nil
2664 "Function that modifies values for display in column view.
2665 For example, it can be used to cut out a certain part from a time stamp.
2666 The function must take 2 arguments:
2668 column-title The title of the column (*not* the property name)
2669 value The value that should be modified.
2671 The function should return the value that should be displayed,
2672 or nil if the normal value should be used."
2673 :group 'org-properties
2674 :type 'function)
2676 (defcustom org-effort-property "Effort"
2677 "The property that is being used to keep track of effort estimates.
2678 Effort estimates given in this property need to have the format H:MM."
2679 :group 'org-properties
2680 :group 'org-progress
2681 :type '(string :tag "Property"))
2683 (defconst org-global-properties-fixed
2684 '(("VISIBILITY_ALL" . "folded children content all")
2685 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2686 "List of property/value pairs that can be inherited by any entry.
2688 These are fixed values, for the preset properties. The user variable
2689 that can be used to add to this list is `org-global-properties'.
2691 The entries in this list are cons cells where the car is a property
2692 name and cdr is a string with the value. If the value represents
2693 multiple items like an \"_ALL\" property, separate the items by
2694 spaces.")
2696 (defcustom org-global-properties nil
2697 "List of property/value pairs that can be inherited by any entry.
2699 This list will be combined with the constant `org-global-properties-fixed'.
2701 The entries in this list are cons cells where the car is a property
2702 name and cdr is a string with the value.
2704 You can set buffer-local values for the same purpose in the variable
2705 `org-file-properties' this by adding lines like
2707 #+PROPERTY: NAME VALUE"
2708 :group 'org-properties
2709 :type '(repeat
2710 (cons (string :tag "Property")
2711 (string :tag "Value"))))
2713 (defvar org-file-properties nil
2714 "List of property/value pairs that can be inherited by any entry.
2715 Valid for the current buffer.
2716 This variable is populated from #+PROPERTY lines.")
2717 (make-variable-buffer-local 'org-file-properties)
2719 (defgroup org-agenda nil
2720 "Options concerning agenda views in Org-mode."
2721 :tag "Org Agenda"
2722 :group 'org)
2724 (defvar org-category nil
2725 "Variable used by org files to set a category for agenda display.
2726 Such files should use a file variable to set it, for example
2728 # -*- mode: org; org-category: \"ELisp\"
2730 or contain a special line
2732 #+CATEGORY: ELisp
2734 If the file does not specify a category, then file's base name
2735 is used instead.")
2736 (make-variable-buffer-local 'org-category)
2737 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2739 (defcustom org-agenda-files nil
2740 "The files to be used for agenda display.
2741 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2742 \\[org-remove-file]. You can also use customize to edit the list.
2744 If an entry is a directory, all files in that directory that are matched by
2745 `org-agenda-file-regexp' will be part of the file list.
2747 If the value of the variable is not a list but a single file name, then
2748 the list of agenda files is actually stored and maintained in that file, one
2749 agenda file per line."
2750 :group 'org-agenda
2751 :type '(choice
2752 (repeat :tag "List of files and directories" file)
2753 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2755 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2756 "Regular expression to match files for `org-agenda-files'.
2757 If any element in the list in that variable contains a directory instead
2758 of a normal file, all files in that directory that are matched by this
2759 regular expression will be included."
2760 :group 'org-agenda
2761 :type 'regexp)
2763 (defcustom org-agenda-text-search-extra-files nil
2764 "List of extra files to be searched by text search commands.
2765 These files will be search in addition to the agenda files by the
2766 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2767 Note that these files will only be searched for text search commands,
2768 not for the other agenda views like todo lists, tag searches or the weekly
2769 agenda. This variable is intended to list notes and possibly archive files
2770 that should also be searched by these two commands.
2771 In fact, if the first element in the list is the symbol `agenda-archives',
2772 than all archive files of all agenda files will be added to the search
2773 scope."
2774 :group 'org-agenda
2775 :type '(set :greedy t
2776 (const :tag "Agenda Archives" agenda-archives)
2777 (repeat :inline t (file))))
2779 (if (fboundp 'defvaralias)
2780 (defvaralias 'org-agenda-multi-occur-extra-files
2781 'org-agenda-text-search-extra-files))
2783 (defcustom org-agenda-skip-unavailable-files nil
2784 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2785 A nil value means to remove them, after a query, from the list."
2786 :group 'org-agenda
2787 :type 'boolean)
2789 (defcustom org-calendar-to-agenda-key [?c]
2790 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2791 The command `org-calendar-goto-agenda' will be bound to this key. The
2792 default is the character `c' because then `c' can be used to switch back and
2793 forth between agenda and calendar."
2794 :group 'org-agenda
2795 :type 'sexp)
2797 (defcustom org-calendar-agenda-action-key [?k]
2798 "The key to be installed in `calendar-mode-map' for agenda-action.
2799 The command `org-agenda-action' will be bound to this key. The
2800 default is the character `k' because we use the same key in the agenda."
2801 :group 'org-agenda
2802 :type 'sexp)
2804 (defcustom org-calendar-insert-diary-entry-key [?i]
2805 "The key to be installed in `calendar-mode-map' for adding diary entries.
2806 This option is irrelevant until `org-agenda-diary-file' has been configured
2807 to point to an Org-mode file. When that is the case, the command
2808 `org-agenda-diary-entry' will be bound to the key given here, by default
2809 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2810 if you want to continue doing this, you need to change this to a different
2811 key."
2812 :group 'org-agenda
2813 :type 'sexp)
2815 (defcustom org-agenda-diary-file 'diary-file
2816 "File to which to add new entries with the `i' key in agenda and calendar.
2817 When this is the symbol `diary-file', the functionality in the Emacs
2818 calendar will be used to add entries to the `diary-file'. But when this
2819 points to a file, `org-agenda-diary-entry' will be used instead."
2820 :group 'org-agenda
2821 :type '(choice
2822 (const :tag "The standard Emacs diary file" diary-file)
2823 (file :tag "Special Org file diary entries")))
2825 (eval-after-load "calendar"
2826 '(progn
2827 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2828 'org-calendar-goto-agenda)
2829 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2830 'org-agenda-action)
2831 (add-hook 'calendar-mode-hook
2832 (lambda ()
2833 (unless (eq org-agenda-diary-file 'diary-file)
2834 (define-key calendar-mode-map
2835 org-calendar-insert-diary-entry-key
2836 'org-agenda-diary-entry))))))
2838 (defgroup org-latex nil
2839 "Options for embedding LaTeX code into Org-mode."
2840 :tag "Org LaTeX"
2841 :group 'org)
2843 (defcustom org-format-latex-options
2844 '(:foreground default :background default :scale 1.0
2845 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2846 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2847 "Options for creating images from LaTeX fragments.
2848 This is a property list with the following properties:
2849 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2850 `default' means use the foreground of the default face.
2851 :background the background color, or \"Transparent\".
2852 `default' means use the background of the default face.
2853 :scale a scaling factor for the size of the images.
2854 :html-foreground, :html-background, :html-scale
2855 the same numbers for HTML export.
2856 :matchers a list indicating which matchers should be used to
2857 find LaTeX fragments. Valid members of this list are:
2858 \"begin\" find environments
2859 \"$1\" find single characters surrounded by $.$
2860 \"$\" find math expressions surrounded by $...$
2861 \"$$\" find math expressions surrounded by $$....$$
2862 \"\\(\" find math expressions surrounded by \\(...\\)
2863 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2864 :group 'org-latex
2865 :type 'plist)
2867 (defcustom org-format-latex-header "\\documentclass{article}
2868 \\usepackage{amssymb}
2869 \\usepackage[usenames]{color}
2870 \\usepackage{amsmath}
2871 \\usepackage{latexsym}
2872 \\usepackage[mathscr]{eucal}
2873 \\pagestyle{empty} % do not remove
2874 % The settings below are copied from fullpage.sty
2875 \\setlength{\\textwidth}{\\paperwidth}
2876 \\addtolength{\\textwidth}{-3cm}
2877 \\setlength{\\oddsidemargin}{1.5cm}
2878 \\addtolength{\\oddsidemargin}{-2.54cm}
2879 \\setlength{\\evensidemargin}{\\oddsidemargin}
2880 \\setlength{\\textheight}{\\paperheight}
2881 \\addtolength{\\textheight}{-\\headheight}
2882 \\addtolength{\\textheight}{-\\headsep}
2883 \\addtolength{\\textheight}{-\\footskip}
2884 \\addtolength{\\textheight}{-3cm}
2885 \\setlength{\\topmargin}{1.5cm}
2886 \\addtolength{\\topmargin}{-2.54cm}"
2887 "The document header used for processing LaTeX fragments.
2888 It is imperative that this header make sure that no page number
2889 appears on the page."
2890 :group 'org-latex
2891 :type 'string)
2893 (defvar org-format-latex-header-extra nil)
2895 ;; The following variable is defined here because is it also used
2896 ;; when formatting latex fragments. Originally it was part of the
2897 ;; LaTeX exporter, which is why the name includes "export".
2898 (defcustom org-export-latex-packages-alist nil
2899 "Alist of packages to be inserted in the header.
2900 Each cell is of the format \( \"option\" . \"package\" \)."
2901 :group 'org-export-latex
2902 :type '(repeat
2903 (list
2904 (string :tag "option")
2905 (string :tag "package"))))
2907 (defgroup org-font-lock nil
2908 "Font-lock settings for highlighting in Org-mode."
2909 :tag "Org Font Lock"
2910 :group 'org)
2912 (defcustom org-level-color-stars-only nil
2913 "Non-nil means fontify only the stars in each headline.
2914 When nil, the entire headline is fontified.
2915 Changing it requires restart of `font-lock-mode' to become effective
2916 also in regions already fontified."
2917 :group 'org-font-lock
2918 :type 'boolean)
2920 (defcustom org-hide-leading-stars nil
2921 "Non-nil means, hide the first N-1 stars in a headline.
2922 This works by using the face `org-hide' for these stars. This
2923 face is white for a light background, and black for a dark
2924 background. You may have to customize the face `org-hide' to
2925 make this work.
2926 Changing it requires restart of `font-lock-mode' to become effective
2927 also in regions already fontified.
2928 You may also set this on a per-file basis by adding one of the following
2929 lines to the buffer:
2931 #+STARTUP: hidestars
2932 #+STARTUP: showstars"
2933 :group 'org-font-lock
2934 :type 'boolean)
2936 (defcustom org-fontify-done-headline nil
2937 "Non-nil means, change the face of a headline if it is marked DONE.
2938 Normally, only the TODO/DONE keyword indicates the state of a headline.
2939 When this is non-nil, the headline after the keyword is set to the
2940 `org-headline-done' as an additional indication."
2941 :group 'org-font-lock
2942 :type 'boolean)
2944 (defcustom org-fontify-emphasized-text t
2945 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2946 Changing this variable requires a restart of Emacs to take effect."
2947 :group 'org-font-lock
2948 :type 'boolean)
2950 (defcustom org-fontify-whole-heading-line nil
2951 "Non-nil means fontify the whole line for headings.
2952 This is useful when setting a background color for the
2953 org-level-* faces."
2954 :group 'org-font-lock
2955 :type 'boolean)
2957 (defcustom org-highlight-latex-fragments-and-specials nil
2958 "Non-nil means, fontify what is treated specially by the exporters."
2959 :group 'org-font-lock
2960 :type 'boolean)
2962 (defcustom org-hide-emphasis-markers nil
2963 "Non-nil mean font-lock should hide the emphasis marker characters."
2964 :group 'org-font-lock
2965 :type 'boolean)
2967 (defvar org-emph-re nil
2968 "Regular expression for matching emphasis.")
2969 (defvar org-verbatim-re nil
2970 "Regular expression for matching verbatim text.")
2971 (defvar org-emphasis-regexp-components) ; defined just below
2972 (defvar org-emphasis-alist) ; defined just below
2973 (defun org-set-emph-re (var val)
2974 "Set variable and compute the emphasis regular expression."
2975 (set var val)
2976 (when (and (boundp 'org-emphasis-alist)
2977 (boundp 'org-emphasis-regexp-components)
2978 org-emphasis-alist org-emphasis-regexp-components)
2979 (let* ((e org-emphasis-regexp-components)
2980 (pre (car e))
2981 (post (nth 1 e))
2982 (border (nth 2 e))
2983 (body (nth 3 e))
2984 (nl (nth 4 e))
2985 (body1 (concat body "*?"))
2986 (markers (mapconcat 'car org-emphasis-alist ""))
2987 (vmarkers (mapconcat
2988 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2989 org-emphasis-alist "")))
2990 ;; make sure special characters appear at the right position in the class
2991 (if (string-match "\\^" markers)
2992 (setq markers (concat (replace-match "" t t markers) "^")))
2993 (if (string-match "-" markers)
2994 (setq markers (concat (replace-match "" t t markers) "-")))
2995 (if (string-match "\\^" vmarkers)
2996 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2997 (if (string-match "-" vmarkers)
2998 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2999 (if (> nl 0)
3000 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3001 (int-to-string nl) "\\}")))
3002 ;; Make the regexp
3003 (setq org-emph-re
3004 (concat "\\([" pre "]\\|^\\)"
3005 "\\("
3006 "\\([" markers "]\\)"
3007 "\\("
3008 "[^" border "]\\|"
3009 "[^" border "]"
3010 body1
3011 "[^" border "]"
3012 "\\)"
3013 "\\3\\)"
3014 "\\([" post "]\\|$\\)"))
3015 (setq org-verbatim-re
3016 (concat "\\([" pre "]\\|^\\)"
3017 "\\("
3018 "\\([" vmarkers "]\\)"
3019 "\\("
3020 "[^" border "]\\|"
3021 "[^" border "]"
3022 body1
3023 "[^" border "]"
3024 "\\)"
3025 "\\3\\)"
3026 "\\([" post "]\\|$\\)")))))
3028 (defcustom org-emphasis-regexp-components
3029 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3030 "Components used to build the regular expression for emphasis.
3031 This is a list with 6 entries. Terminology: In an emphasis string
3032 like \" *strong word* \", we call the initial space PREMATCH, the final
3033 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3034 and \"trong wor\" is the body. The different components in this variable
3035 specify what is allowed/forbidden in each part:
3037 pre Chars allowed as prematch. Beginning of line will be allowed too.
3038 post Chars allowed as postmatch. End of line will be allowed too.
3039 border The chars *forbidden* as border characters.
3040 body-regexp A regexp like \".\" to match a body character. Don't use
3041 non-shy groups here, and don't allow newline here.
3042 newline The maximum number of newlines allowed in an emphasis exp.
3044 Use customize to modify this, or restart Emacs after changing it."
3045 :group 'org-font-lock
3046 :set 'org-set-emph-re
3047 :type '(list
3048 (sexp :tag "Allowed chars in pre ")
3049 (sexp :tag "Allowed chars in post ")
3050 (sexp :tag "Forbidden chars in border ")
3051 (sexp :tag "Regexp for body ")
3052 (integer :tag "number of newlines allowed")
3053 (option (boolean :tag "Please ignore this button"))))
3055 (defcustom org-emphasis-alist
3056 `(("*" bold "<b>" "</b>")
3057 ("/" italic "<i>" "</i>")
3058 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3059 ("=" org-code "<code>" "</code>" verbatim)
3060 ("~" org-verbatim "<code>" "</code>" verbatim)
3061 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3062 "<del>" "</del>")
3064 "Special syntax for emphasized text.
3065 Text starting and ending with a special character will be emphasized, for
3066 example *bold*, _underlined_ and /italic/. This variable sets the marker
3067 characters, the face to be used by font-lock for highlighting in Org-mode
3068 Emacs buffers, and the HTML tags to be used for this.
3069 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3070 Use customize to modify this, or restart Emacs after changing it."
3071 :group 'org-font-lock
3072 :set 'org-set-emph-re
3073 :type '(repeat
3074 (list
3075 (string :tag "Marker character")
3076 (choice
3077 (face :tag "Font-lock-face")
3078 (plist :tag "Face property list"))
3079 (string :tag "HTML start tag")
3080 (string :tag "HTML end tag")
3081 (option (const verbatim)))))
3083 (defvar org-protecting-blocks
3084 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3085 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3086 This is needed for font-lock setup.")
3088 ;;; Miscellaneous options
3090 (defgroup org-completion nil
3091 "Completion in Org-mode."
3092 :tag "Org Completion"
3093 :group 'org)
3095 (defcustom org-completion-use-ido nil
3096 "Non-nil means, use ido completion wherever possible.
3097 Note that `ido-mode' must be active for this variable to be relevant.
3098 If you decide to turn this variable on, you might well want to turn off
3099 `org-outline-path-complete-in-steps'.
3100 See also `org-completion-use-iswitchb'."
3101 :group 'org-completion
3102 :type 'boolean)
3104 (defcustom org-completion-use-iswitchb nil
3105 "Non-nil means, use iswitchb completion wherever possible.
3106 Note that `iswitchb-mode' must be active for this variable to be relevant.
3107 If you decide to turn this variable on, you might well want to turn off
3108 `org-outline-path-complete-in-steps'.
3109 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3110 :group 'org-completion
3111 :type 'boolean)
3113 (defcustom org-completion-fallback-command 'hippie-expand
3114 "The expansion command called by \\[org-complete] in normal context.
3115 Normal means, no org-mode-specific context."
3116 :group 'org-completion
3117 :type 'function)
3119 ;;; Functions and variables from their packages
3120 ;; Declared here to avoid compiler warnings
3122 ;; XEmacs only
3123 (defvar outline-mode-menu-heading)
3124 (defvar outline-mode-menu-show)
3125 (defvar outline-mode-menu-hide)
3126 (defvar zmacs-regions) ; XEmacs regions
3128 ;; Emacs only
3129 (defvar mark-active)
3131 ;; Various packages
3132 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3133 (declare-function calendar-forward-day "cal-move" (arg))
3134 (declare-function calendar-goto-date "cal-move" (date))
3135 (declare-function calendar-goto-today "cal-move" ())
3136 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3137 (defvar calc-embedded-close-formula)
3138 (defvar calc-embedded-open-formula)
3139 (declare-function cdlatex-tab "ext:cdlatex" ())
3140 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3141 (defvar font-lock-unfontify-region-function)
3142 (declare-function iswitchb-read-buffer "iswitchb"
3143 (prompt &optional default require-match start matches-set))
3144 (defvar iswitchb-temp-buflist)
3145 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3146 (defvar org-agenda-tags-todo-honor-ignore-options)
3147 (declare-function org-agenda-skip "org-agenda" ())
3148 (declare-function
3149 org-format-agenda-item "org-agenda"
3150 (extra txt &optional category tags dotime noprefix remove-re habitp))
3151 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3152 (declare-function org-agenda-change-all-lines "org-agenda"
3153 (newhead hdmarker &optional fixface just-this))
3154 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3155 (declare-function org-agenda-maybe-redo "org-agenda" ())
3156 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3157 (beg end))
3158 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3159 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3160 "org-agenda" (&optional end))
3161 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3162 (declare-function org-indent-mode "org-indent" (&optional arg))
3163 (declare-function parse-time-string "parse-time" (string))
3164 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3165 (defvar remember-data-file)
3166 (defvar texmathp-why)
3167 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3168 (declare-function table--at-cell-p "table" (position &optional object at-column))
3170 (defvar w3m-current-url)
3171 (defvar w3m-current-title)
3173 (defvar org-latex-regexps)
3175 ;;; Autoload and prepare some org modules
3177 ;; Some table stuff that needs to be defined here, because it is used
3178 ;; by the functions setting up org-mode or checking for table context.
3180 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3181 "Detects an org-type or table-type table.")
3182 (defconst org-table-line-regexp "^[ \t]*|"
3183 "Detects an org-type table line.")
3184 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3185 "Detects an org-type table line.")
3186 (defconst org-table-hline-regexp "^[ \t]*|-"
3187 "Detects an org-type table hline.")
3188 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3189 "Detects a table-type table hline.")
3190 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3191 "Searching from within a table (any type) this finds the first line
3192 outside the table.")
3194 ;; Autoload the functions in org-table.el that are needed by functions here.
3196 (eval-and-compile
3197 (org-autoload "org-table"
3198 '(org-table-align org-table-begin org-table-blank-field
3199 org-table-convert org-table-convert-region org-table-copy-down
3200 org-table-copy-region org-table-create
3201 org-table-create-or-convert-from-region
3202 org-table-create-with-table.el org-table-current-dline
3203 org-table-cut-region org-table-delete-column org-table-edit-field
3204 org-table-edit-formulas org-table-end org-table-eval-formula
3205 org-table-export org-table-field-info
3206 org-table-get-stored-formulas org-table-goto-column
3207 org-table-hline-and-move org-table-import org-table-insert-column
3208 org-table-insert-hline org-table-insert-row org-table-iterate
3209 org-table-justify-field-maybe org-table-kill-row
3210 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3211 org-table-move-column org-table-move-column-left
3212 org-table-move-column-right org-table-move-row
3213 org-table-move-row-down org-table-move-row-up
3214 org-table-next-field org-table-next-row org-table-paste-rectangle
3215 org-table-previous-field org-table-recalculate
3216 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3217 org-table-toggle-coordinate-overlays
3218 org-table-toggle-formula-debugger org-table-wrap-region
3219 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3221 (defun org-at-table-p (&optional table-type)
3222 "Return t if the cursor is inside an org-type table.
3223 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3224 (if org-enable-table-editor
3225 (save-excursion
3226 (beginning-of-line 1)
3227 (looking-at (if table-type org-table-any-line-regexp
3228 org-table-line-regexp)))
3229 nil))
3230 (defsubst org-table-p () (org-at-table-p))
3232 (defun org-at-table.el-p ()
3233 "Return t if and only if we are at a table.el table."
3234 (and (org-at-table-p 'any)
3235 (save-excursion
3236 (goto-char (org-table-begin 'any))
3237 (looking-at org-table1-hline-regexp))))
3238 (defun org-table-recognize-table.el ()
3239 "If there is a table.el table nearby, recognize it and move into it."
3240 (if org-table-tab-recognizes-table.el
3241 (if (org-at-table.el-p)
3242 (progn
3243 (beginning-of-line 1)
3244 (if (looking-at org-table-dataline-regexp)
3246 (if (looking-at org-table1-hline-regexp)
3247 (progn
3248 (beginning-of-line 2)
3249 (if (looking-at org-table-any-border-regexp)
3250 (beginning-of-line -1)))))
3251 (if (re-search-forward "|" (org-table-end t) t)
3252 (progn
3253 (require 'table)
3254 (if (table--at-cell-p (point))
3256 (message "recognizing table.el table...")
3257 (table-recognize-table)
3258 (message "recognizing table.el table...done")))
3259 (error "This should not happen..."))
3261 nil)
3262 nil))
3264 (defun org-at-table-hline-p ()
3265 "Return t if the cursor is inside a hline in a table."
3266 (if org-enable-table-editor
3267 (save-excursion
3268 (beginning-of-line 1)
3269 (looking-at org-table-hline-regexp))
3270 nil))
3272 (defvar org-table-clean-did-remove-column nil)
3274 (defun org-table-map-tables (function)
3275 "Apply FUNCTION to the start of all tables in the buffer."
3276 (save-excursion
3277 (save-restriction
3278 (widen)
3279 (goto-char (point-min))
3280 (while (re-search-forward org-table-any-line-regexp nil t)
3281 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3282 (beginning-of-line 1)
3283 (when (looking-at org-table-line-regexp)
3284 (save-excursion (funcall function))
3285 (or (looking-at org-table-line-regexp)
3286 (forward-char 1)))
3287 (re-search-forward org-table-any-border-regexp nil 1))))
3288 (message "Mapping tables: done"))
3290 ;; Declare and autoload functions from org-exp.el & Co
3292 (declare-function org-default-export-plist "org-exp")
3293 (declare-function org-infile-export-plist "org-exp")
3294 (declare-function org-get-current-options "org-exp")
3295 (eval-and-compile
3296 (org-autoload "org-exp"
3297 '(org-export org-export-visible
3298 org-insert-export-options-template
3299 org-table-clean-before-export))
3300 (org-autoload "org-ascii"
3301 '(org-export-as-ascii org-export-ascii-preprocess
3302 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3303 org-export-region-as-ascii))
3304 (org-autoload "org-latex"
3305 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3306 org-replace-region-by-latex org-export-region-as-latex
3307 org-export-as-latex org-export-as-pdf
3308 org-export-as-pdf-and-open))
3309 (org-autoload "org-html"
3310 '(org-export-as-html-and-open
3311 org-export-as-html-batch org-export-as-html-to-buffer
3312 org-replace-region-by-html org-export-region-as-html
3313 org-export-as-html))
3314 (org-autoload "org-docbook"
3315 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3316 org-replace-region-by-docbook org-export-region-as-docbook
3317 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3318 org-export-as-docbook))
3319 (org-autoload "org-icalendar"
3320 '(org-export-icalendar-this-file
3321 org-export-icalendar-all-agenda-files
3322 org-export-icalendar-combine-agenda-files))
3323 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3324 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3326 ;; Declare and autoload functions from org-agenda.el
3328 (eval-and-compile
3329 (org-autoload "org-agenda"
3330 '(org-agenda org-agenda-list org-search-view
3331 org-todo-list org-tags-view org-agenda-list-stuck-projects
3332 org-diary org-agenda-to-appt
3333 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3335 ;; Autoload org-remember
3337 (eval-and-compile
3338 (org-autoload "org-remember"
3339 '(org-remember-insinuate org-remember-annotation
3340 org-remember-apply-template org-remember org-remember-handler)))
3342 ;; Autoload org-clock.el
3345 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3346 (beg end))
3347 (declare-function org-clock-update-mode-line "org-clock" ())
3348 (declare-function org-resolve-clocks "org-clock"
3349 (&optional also-non-dangling-p prompt last-valid))
3350 (defvar org-clock-start-time)
3351 (defvar org-clock-marker (make-marker)
3352 "Marker recording the last clock-in.")
3353 (defvar org-clock-hd-marker (make-marker)
3354 "Marker recording the last clock-in, but the headline position.")
3355 (defvar org-clock-heading ""
3356 "The heading of the current clock entry.")
3357 (defun org-clock-is-active ()
3358 "Return non-nil if clock is currently running.
3359 The return value is actually the clock marker."
3360 (marker-buffer org-clock-marker))
3362 (eval-and-compile
3363 (org-autoload
3364 "org-clock"
3365 '(org-clock-in org-clock-out org-clock-cancel
3366 org-clock-goto org-clock-sum org-clock-display
3367 org-clock-remove-overlays org-clock-report
3368 org-clocktable-shift org-dblock-write:clocktable
3369 org-get-clocktable org-resolve-clocks)))
3371 (defun org-clock-update-time-maybe ()
3372 "If this is a CLOCK line, update it and return t.
3373 Otherwise, return nil."
3374 (interactive)
3375 (save-excursion
3376 (beginning-of-line 1)
3377 (skip-chars-forward " \t")
3378 (when (looking-at org-clock-string)
3379 (let ((re (concat "[ \t]*" org-clock-string
3380 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3381 "\\([ \t]*=>.*\\)?\\)?"))
3382 ts te h m s neg)
3383 (cond
3384 ((not (looking-at re))
3385 nil)
3386 ((not (match-end 2))
3387 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3388 (> org-clock-marker (point))
3389 (<= org-clock-marker (point-at-eol)))
3390 ;; The clock is running here
3391 (setq org-clock-start-time
3392 (apply 'encode-time
3393 (org-parse-time-string (match-string 1))))
3394 (org-clock-update-mode-line)))
3396 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3397 (end-of-line 1)
3398 (setq ts (match-string 1)
3399 te (match-string 3))
3400 (setq s (- (org-float-time
3401 (apply 'encode-time (org-parse-time-string te)))
3402 (org-float-time
3403 (apply 'encode-time (org-parse-time-string ts))))
3404 neg (< s 0)
3405 s (abs s)
3406 h (floor (/ s 3600))
3407 s (- s (* 3600 h))
3408 m (floor (/ s 60))
3409 s (- s (* 60 s)))
3410 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3411 t))))))
3413 (defun org-check-running-clock ()
3414 "Check if the current buffer contains the running clock.
3415 If yes, offer to stop it and to save the buffer with the changes."
3416 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3417 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3418 (buffer-name))))
3419 (org-clock-out)
3420 (when (y-or-n-p "Save changed buffer?")
3421 (save-buffer))))
3423 (defun org-clocktable-try-shift (dir n)
3424 "Check if this line starts a clock table, if yes, shift the time block."
3425 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3426 (org-clocktable-shift dir n)))
3428 ;; Autoload org-timer.el
3430 (eval-and-compile
3431 (org-autoload
3432 "org-timer"
3433 '(org-timer-start org-timer org-timer-item
3434 org-timer-change-times-in-region
3435 org-timer-set-timer
3436 org-timer-reset-timers
3437 org-timer-show-remaining-time)))
3439 ;; Autoload org-feed.el
3441 (eval-and-compile
3442 (org-autoload
3443 "org-feed"
3444 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3447 ;; Autoload org-indent.el
3449 ;; Define the variable already here, to make sure we have it.
3450 (defvar org-indent-mode nil
3451 "Non-nil if Org-Indent mode is enabled.
3452 Use the command `org-indent-mode' to change this variable.")
3454 (eval-and-compile
3455 (org-autoload
3456 "org-indent"
3457 '(org-indent-mode)))
3459 ;; Autoload org-mobile.el
3461 (eval-and-compile
3462 (org-autoload
3463 "org-mobile"
3464 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3466 ;; Autoload archiving code
3467 ;; The stuff that is needed for cycling and tags has to be defined here.
3469 (defgroup org-archive nil
3470 "Options concerning archiving in Org-mode."
3471 :tag "Org Archive"
3472 :group 'org-structure)
3474 (defcustom org-archive-location "%s_archive::"
3475 "The location where subtrees should be archived.
3477 The value of this variable is a string, consisting of two parts,
3478 separated by a double-colon. The first part is a filename and
3479 the second part is a headline.
3481 When the filename is omitted, archiving happens in the same file.
3482 %s in the filename will be replaced by the current file
3483 name (without the directory part). Archiving to a different file
3484 is useful to keep archived entries from contributing to the
3485 Org-mode Agenda.
3487 The archived entries will be filed as subtrees of the specified
3488 headline. When the headline is omitted, the subtrees are simply
3489 filed away at the end of the file, as top-level entries. Also in
3490 the heading you can use %s to represent the file name, this can be
3491 useful when using the same archive for a number of different files.
3493 Here are a few examples:
3494 \"%s_archive::\"
3495 If the current file is Projects.org, archive in file
3496 Projects.org_archive, as top-level trees. This is the default.
3498 \"::* Archived Tasks\"
3499 Archive in the current file, under the top-level headline
3500 \"* Archived Tasks\".
3502 \"~/org/archive.org::\"
3503 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3505 \"~/org/archive.org::From %s\"
3506 Archive in file ~/org/archive.org (absolute path), under headlines
3507 \"From FILENAME\" where file name is the current file name.
3509 \"basement::** Finished Tasks\"
3510 Archive in file ./basement (relative path), as level 3 trees
3511 below the level 2 heading \"** Finished Tasks\".
3513 You may set this option on a per-file basis by adding to the buffer a
3514 line like
3516 #+ARCHIVE: basement::** Finished Tasks
3518 You may also define it locally for a subtree by setting an ARCHIVE property
3519 in the entry. If such a property is found in an entry, or anywhere up
3520 the hierarchy, it will be used."
3521 :group 'org-archive
3522 :type 'string)
3524 (defcustom org-archive-tag "ARCHIVE"
3525 "The tag that marks a subtree as archived.
3526 An archived subtree does not open during visibility cycling, and does
3527 not contribute to the agenda listings.
3528 After changing this, font-lock must be restarted in the relevant buffers to
3529 get the proper fontification."
3530 :group 'org-archive
3531 :group 'org-keywords
3532 :type 'string)
3534 (defcustom org-agenda-skip-archived-trees t
3535 "Non-nil means, the agenda will skip any items located in archived trees.
3536 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3537 variable is no longer recommended, you should leave it at the value t.
3538 Instead, use the key `v' to cycle the archives-mode in the agenda."
3539 :group 'org-archive
3540 :group 'org-agenda-skip
3541 :type 'boolean)
3543 (defcustom org-columns-skip-archived-trees t
3544 "Non-nil means, ignore archived trees when creating column view."
3545 :group 'org-archive
3546 :group 'org-properties
3547 :type 'boolean)
3549 (defcustom org-cycle-open-archived-trees nil
3550 "Non-nil means, `org-cycle' will open archived trees.
3551 An archived tree is a tree marked with the tag ARCHIVE.
3552 When nil, archived trees will stay folded. You can still open them with
3553 normal outline commands like `show-all', but not with the cycling commands."
3554 :group 'org-archive
3555 :group 'org-cycle
3556 :type 'boolean)
3558 (defcustom org-sparse-tree-open-archived-trees nil
3559 "Non-nil means sparse tree construction shows matches in archived trees.
3560 When nil, matches in these trees are highlighted, but the trees are kept in
3561 collapsed state."
3562 :group 'org-archive
3563 :group 'org-sparse-trees
3564 :type 'boolean)
3566 (defun org-cycle-hide-archived-subtrees (state)
3567 "Re-hide all archived subtrees after a visibility state change."
3568 (when (and (not org-cycle-open-archived-trees)
3569 (not (memq state '(overview folded))))
3570 (save-excursion
3571 (let* ((globalp (memq state '(contents all)))
3572 (beg (if globalp (point-min) (point)))
3573 (end (if globalp (point-max) (org-end-of-subtree t))))
3574 (org-hide-archived-subtrees beg end)
3575 (goto-char beg)
3576 (if (looking-at (concat ".*:" org-archive-tag ":"))
3577 (message "%s" (substitute-command-keys
3578 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3580 (defun org-force-cycle-archived ()
3581 "Cycle subtree even if it is archived."
3582 (interactive)
3583 (setq this-command 'org-cycle)
3584 (let ((org-cycle-open-archived-trees t))
3585 (call-interactively 'org-cycle)))
3587 (defun org-hide-archived-subtrees (beg end)
3588 "Re-hide all archived subtrees after a visibility state change."
3589 (save-excursion
3590 (let* ((re (concat ":" org-archive-tag ":")))
3591 (goto-char beg)
3592 (while (re-search-forward re end t)
3593 (and (org-on-heading-p) (org-flag-subtree t))
3594 (org-end-of-subtree t)))))
3596 (defun org-flag-subtree (flag)
3597 (save-excursion
3598 (org-back-to-heading t)
3599 (outline-end-of-heading)
3600 (outline-flag-region (point)
3601 (progn (org-end-of-subtree t) (point))
3602 flag)))
3604 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3606 (eval-and-compile
3607 (org-autoload "org-archive"
3608 '(org-add-archive-files org-archive-subtree
3609 org-archive-to-archive-sibling org-toggle-archive-tag
3610 org-archive-subtree-default
3611 org-archive-subtree-default-with-confirmation)))
3613 ;; Autoload Column View Code
3615 (declare-function org-columns-number-to-string "org-colview")
3616 (declare-function org-columns-get-format-and-top-level "org-colview")
3617 (declare-function org-columns-compute "org-colview")
3619 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3620 '(org-columns-number-to-string org-columns-get-format-and-top-level
3621 org-columns-compute org-agenda-columns org-columns-remove-overlays
3622 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3624 ;; Autoload ID code
3626 (declare-function org-id-store-link "org-id")
3627 (declare-function org-id-locations-load "org-id")
3628 (declare-function org-id-locations-save "org-id")
3629 (defvar org-id-track-globally)
3630 (org-autoload "org-id"
3631 '(org-id-get-create org-id-new org-id-copy org-id-get
3632 org-id-get-with-outline-path-completion
3633 org-id-get-with-outline-drilling
3634 org-id-goto org-id-find org-id-store-link))
3636 ;; Autoload Plotting Code
3638 (org-autoload "org-plot"
3639 '(org-plot/gnuplot))
3641 ;;; Variables for pre-computed regular expressions, all buffer local
3643 (defvar org-drawer-regexp nil
3644 "Matches first line of a hidden block.")
3645 (make-variable-buffer-local 'org-drawer-regexp)
3646 (defvar org-todo-regexp nil
3647 "Matches any of the TODO state keywords.")
3648 (make-variable-buffer-local 'org-todo-regexp)
3649 (defvar org-not-done-regexp nil
3650 "Matches any of the TODO state keywords except the last one.")
3651 (make-variable-buffer-local 'org-not-done-regexp)
3652 (defvar org-not-done-heading-regexp nil
3653 "Matches a TODO headline that is not done.")
3654 (make-variable-buffer-local 'org-not-done-regexp)
3655 (defvar org-todo-line-regexp nil
3656 "Matches a headline and puts TODO state into group 2 if present.")
3657 (make-variable-buffer-local 'org-todo-line-regexp)
3658 (defvar org-complex-heading-regexp nil
3659 "Matches a headline and puts everything into groups:
3660 group 1: the stars
3661 group 2: The todo keyword, maybe
3662 group 3: Priority cookie
3663 group 4: True headline
3664 group 5: Tags")
3665 (make-variable-buffer-local 'org-complex-heading-regexp)
3666 (defvar org-complex-heading-regexp-format nil)
3667 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3668 (defvar org-todo-line-tags-regexp nil
3669 "Matches a headline and puts TODO state into group 2 if present.
3670 Also put tags into group 4 if tags are present.")
3671 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3672 (defvar org-nl-done-regexp nil
3673 "Matches newline followed by a headline with the DONE keyword.")
3674 (make-variable-buffer-local 'org-nl-done-regexp)
3675 (defvar org-looking-at-done-regexp nil
3676 "Matches the DONE keyword a point.")
3677 (make-variable-buffer-local 'org-looking-at-done-regexp)
3678 (defvar org-ds-keyword-length 12
3679 "Maximum length of the Deadline and SCHEDULED keywords.")
3680 (make-variable-buffer-local 'org-ds-keyword-length)
3681 (defvar org-deadline-regexp nil
3682 "Matches the DEADLINE keyword.")
3683 (make-variable-buffer-local 'org-deadline-regexp)
3684 (defvar org-deadline-time-regexp nil
3685 "Matches the DEADLINE keyword together with a time stamp.")
3686 (make-variable-buffer-local 'org-deadline-time-regexp)
3687 (defvar org-deadline-line-regexp nil
3688 "Matches the DEADLINE keyword and the rest of the line.")
3689 (make-variable-buffer-local 'org-deadline-line-regexp)
3690 (defvar org-scheduled-regexp nil
3691 "Matches the SCHEDULED keyword.")
3692 (make-variable-buffer-local 'org-scheduled-regexp)
3693 (defvar org-scheduled-time-regexp nil
3694 "Matches the SCHEDULED keyword together with a time stamp.")
3695 (make-variable-buffer-local 'org-scheduled-time-regexp)
3696 (defvar org-closed-time-regexp nil
3697 "Matches the CLOSED keyword together with a time stamp.")
3698 (make-variable-buffer-local 'org-closed-time-regexp)
3700 (defvar org-keyword-time-regexp nil
3701 "Matches any of the 4 keywords, together with the time stamp.")
3702 (make-variable-buffer-local 'org-keyword-time-regexp)
3703 (defvar org-keyword-time-not-clock-regexp nil
3704 "Matches any of the 3 keywords, together with the time stamp.")
3705 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3706 (defvar org-maybe-keyword-time-regexp nil
3707 "Matches a timestamp, possibly preceeded by a keyword.")
3708 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3709 (defvar org-planning-or-clock-line-re nil
3710 "Matches a line with planning or clock info.")
3711 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3712 (defvar org-all-time-keywords nil
3713 "List of time keywords.")
3714 (make-variable-buffer-local 'org-all-time-keywords)
3716 (defconst org-plain-time-of-day-regexp
3717 (concat
3718 "\\(\\<[012]?[0-9]"
3719 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3720 "\\(--?"
3721 "\\(\\<[012]?[0-9]"
3722 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3723 "\\)?")
3724 "Regular expression to match a plain time or time range.
3725 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3726 groups carry important information:
3727 0 the full match
3728 1 the first time, range or not
3729 8 the second time, if it is a range.")
3731 (defconst org-plain-time-extension-regexp
3732 (concat
3733 "\\(\\<[012]?[0-9]"
3734 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3735 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3736 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3737 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3738 groups carry important information:
3739 0 the full match
3740 7 hours of duration
3741 9 minutes of duration")
3743 (defconst org-stamp-time-of-day-regexp
3744 (concat
3745 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3746 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3747 "\\(--?"
3748 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3749 "Regular expression to match a timestamp time or time range.
3750 After a match, the following groups carry important information:
3751 0 the full match
3752 1 date plus weekday, for back referencing to make sure both times are on the same day
3753 2 the first time, range or not
3754 4 the second time, if it is a range.")
3756 (defconst org-startup-options
3757 '(("fold" org-startup-folded t)
3758 ("overview" org-startup-folded t)
3759 ("nofold" org-startup-folded nil)
3760 ("showall" org-startup-folded nil)
3761 ("showeverything" org-startup-folded showeverything)
3762 ("content" org-startup-folded content)
3763 ("indent" org-startup-indented t)
3764 ("noindent" org-startup-indented nil)
3765 ("hidestars" org-hide-leading-stars t)
3766 ("showstars" org-hide-leading-stars nil)
3767 ("odd" org-odd-levels-only t)
3768 ("oddeven" org-odd-levels-only nil)
3769 ("align" org-startup-align-all-tables t)
3770 ("noalign" org-startup-align-all-tables nil)
3771 ("customtime" org-display-custom-times t)
3772 ("logdone" org-log-done time)
3773 ("lognotedone" org-log-done note)
3774 ("nologdone" org-log-done nil)
3775 ("lognoteclock-out" org-log-note-clock-out t)
3776 ("nolognoteclock-out" org-log-note-clock-out nil)
3777 ("logrepeat" org-log-repeat state)
3778 ("lognoterepeat" org-log-repeat note)
3779 ("nologrepeat" org-log-repeat nil)
3780 ("logreschedule" org-log-reschedule time)
3781 ("lognotereschedule" org-log-reschedule note)
3782 ("nologreschedule" org-log-reschedule nil)
3783 ("logredeadline" org-log-redeadline time)
3784 ("lognoteredeadline" org-log-redeadline note)
3785 ("nologredeadline" org-log-redeadline nil)
3786 ("fninline" org-footnote-define-inline t)
3787 ("nofninline" org-footnote-define-inline nil)
3788 ("fnlocal" org-footnote-section nil)
3789 ("fnauto" org-footnote-auto-label t)
3790 ("fnprompt" org-footnote-auto-label nil)
3791 ("fnconfirm" org-footnote-auto-label confirm)
3792 ("fnplain" org-footnote-auto-label plain)
3793 ("fnadjust" org-footnote-auto-adjust t)
3794 ("nofnadjust" org-footnote-auto-adjust nil)
3795 ("constcgs" constants-unit-system cgs)
3796 ("constSI" constants-unit-system SI)
3797 ("noptag" org-tag-persistent-alist nil)
3798 ("hideblocks" org-hide-block-startup t)
3799 ("nohideblocks" org-hide-block-startup nil)
3800 ("beamer" org-startup-with-beamer-mode t))
3801 "Variable associated with STARTUP options for org-mode.
3802 Each element is a list of three items: The startup options as written
3803 in the #+STARTUP line, the corresponding variable, and the value to
3804 set this variable to if the option is found. An optional forth element PUSH
3805 means to push this value onto the list in the variable.")
3807 (defun org-set-regexps-and-options ()
3808 "Precompute regular expressions for current buffer."
3809 (when (org-mode-p)
3810 (org-set-local 'org-todo-kwd-alist nil)
3811 (org-set-local 'org-todo-key-alist nil)
3812 (org-set-local 'org-todo-key-trigger nil)
3813 (org-set-local 'org-todo-keywords-1 nil)
3814 (org-set-local 'org-done-keywords nil)
3815 (org-set-local 'org-todo-heads nil)
3816 (org-set-local 'org-todo-sets nil)
3817 (org-set-local 'org-todo-log-states nil)
3818 (org-set-local 'org-file-properties nil)
3819 (org-set-local 'org-file-tags nil)
3820 (let ((re (org-make-options-regexp
3821 '("CATEGORY" "TODO" "COLUMNS"
3822 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3823 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3824 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3825 (splitre "[ \t]+")
3826 kwds kws0 kwsa key log value cat arch tags const links hw dws
3827 tail sep kws1 prio props ftags drawers beamer-p
3828 ext-setup-or-nil setup-contents (start 0))
3829 (save-excursion
3830 (save-restriction
3831 (widen)
3832 (goto-char (point-min))
3833 (while (or (and ext-setup-or-nil
3834 (string-match re ext-setup-or-nil start)
3835 (setq start (match-end 0)))
3836 (and (setq ext-setup-or-nil nil start 0)
3837 (re-search-forward re nil t)))
3838 (setq key (upcase (match-string 1 ext-setup-or-nil))
3839 value (org-match-string-no-properties 2 ext-setup-or-nil))
3840 (cond
3841 ((equal key "CATEGORY")
3842 (if (string-match "[ \t]+$" value)
3843 (setq value (replace-match "" t t value)))
3844 (setq cat value))
3845 ((member key '("SEQ_TODO" "TODO"))
3846 (push (cons 'sequence (org-split-string value splitre)) kwds))
3847 ((equal key "TYP_TODO")
3848 (push (cons 'type (org-split-string value splitre)) kwds))
3849 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3850 ;; general TODO-like setup
3851 (push (cons (intern (downcase (match-string 1 key)))
3852 (org-split-string value splitre)) kwds))
3853 ((equal key "TAGS")
3854 (setq tags (append tags (if tags '("\\n") nil)
3855 (org-split-string value splitre))))
3856 ((equal key "COLUMNS")
3857 (org-set-local 'org-columns-default-format value))
3858 ((equal key "LINK")
3859 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3860 (push (cons (match-string 1 value)
3861 (org-trim (match-string 2 value)))
3862 links)))
3863 ((equal key "PRIORITIES")
3864 (setq prio (org-split-string value " +")))
3865 ((equal key "PROPERTY")
3866 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3867 (push (cons (match-string 1 value) (match-string 2 value))
3868 props)))
3869 ((equal key "FILETAGS")
3870 (when (string-match "\\S-" value)
3871 (setq ftags
3872 (append
3873 ftags
3874 (apply 'append
3875 (mapcar (lambda (x) (org-split-string x ":"))
3876 (org-split-string value)))))))
3877 ((equal key "DRAWERS")
3878 (setq drawers (org-split-string value splitre)))
3879 ((equal key "CONSTANTS")
3880 (setq const (append const (org-split-string value splitre))))
3881 ((equal key "STARTUP")
3882 (let ((opts (org-split-string value splitre))
3883 l var val)
3884 (while (setq l (pop opts))
3885 (when (setq l (assoc l org-startup-options))
3886 (setq var (nth 1 l) val (nth 2 l))
3887 (if (not (nth 3 l))
3888 (set (make-local-variable var) val)
3889 (if (not (listp (symbol-value var)))
3890 (set (make-local-variable var) nil))
3891 (set (make-local-variable var) (symbol-value var))
3892 (add-to-list var val))))))
3893 ((equal key "ARCHIVE")
3894 (string-match " *$" value)
3895 (setq arch (replace-match "" t t value))
3896 (remove-text-properties 0 (length arch)
3897 '(face t fontified t) arch))
3898 ((equal key "LATEX_CLASS")
3899 (setq beamer-p (equal value "beamer")))
3900 ((equal key "SETUPFILE")
3901 (setq setup-contents (org-file-contents
3902 (expand-file-name
3903 (org-remove-double-quotes value))
3904 'noerror))
3905 (if (not ext-setup-or-nil)
3906 (setq ext-setup-or-nil setup-contents start 0)
3907 (setq ext-setup-or-nil
3908 (concat (substring ext-setup-or-nil 0 start)
3909 "\n" setup-contents "\n"
3910 (substring ext-setup-or-nil start)))))
3911 ))))
3912 (when cat
3913 (org-set-local 'org-category (intern cat))
3914 (push (cons "CATEGORY" cat) props))
3915 (when prio
3916 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3917 (setq prio (mapcar 'string-to-char prio))
3918 (org-set-local 'org-highest-priority (nth 0 prio))
3919 (org-set-local 'org-lowest-priority (nth 1 prio))
3920 (org-set-local 'org-default-priority (nth 2 prio)))
3921 (and props (org-set-local 'org-file-properties (nreverse props)))
3922 (and ftags (org-set-local 'org-file-tags
3923 (mapcar 'org-add-prop-inherited ftags)))
3924 (and drawers (org-set-local 'org-drawers drawers))
3925 (and arch (org-set-local 'org-archive-location arch))
3926 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3927 ;; Process the TODO keywords
3928 (unless kwds
3929 ;; Use the global values as if they had been given locally.
3930 (setq kwds (default-value 'org-todo-keywords))
3931 (if (stringp (car kwds))
3932 (setq kwds (list (cons org-todo-interpretation
3933 (default-value 'org-todo-keywords)))))
3934 (setq kwds (reverse kwds)))
3935 (setq kwds (nreverse kwds))
3936 (let (inter kws kw)
3937 (while (setq kws (pop kwds))
3938 (let ((kws (or
3939 (run-hook-with-args-until-success
3940 'org-todo-setup-filter-hook kws)
3941 kws)))
3942 (setq inter (pop kws) sep (member "|" kws)
3943 kws0 (delete "|" (copy-sequence kws))
3944 kwsa nil
3945 kws1 (mapcar
3946 (lambda (x)
3947 ;; 1 2
3948 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3949 (progn
3950 (setq kw (match-string 1 x)
3951 key (and (match-end 2) (match-string 2 x))
3952 log (org-extract-log-state-settings x))
3953 (push (cons kw (and key (string-to-char key))) kwsa)
3954 (and log (push log org-todo-log-states))
3956 (error "Invalid TODO keyword %s" x)))
3957 kws0)
3958 kwsa (if kwsa (append '((:startgroup))
3959 (nreverse kwsa)
3960 '((:endgroup))))
3961 hw (car kws1)
3962 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3963 tail (list inter hw (car dws) (org-last dws))))
3964 (add-to-list 'org-todo-heads hw 'append)
3965 (push kws1 org-todo-sets)
3966 (setq org-done-keywords (append org-done-keywords dws nil))
3967 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3968 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3969 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3970 (setq org-todo-sets (nreverse org-todo-sets)
3971 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3972 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3973 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3974 ;; Process the constants
3975 (when const
3976 (let (e cst)
3977 (while (setq e (pop const))
3978 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3979 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3980 (setq org-table-formula-constants-local cst)))
3982 ;; Process the tags.
3983 (when tags
3984 (let (e tgs)
3985 (while (setq e (pop tags))
3986 (cond
3987 ((equal e "{") (push '(:startgroup) tgs))
3988 ((equal e "}") (push '(:endgroup) tgs))
3989 ((equal e "\\n") (push '(:newline) tgs))
3990 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3991 (push (cons (match-string 1 e)
3992 (string-to-char (match-string 2 e)))
3993 tgs))
3994 (t (push (list e) tgs))))
3995 (org-set-local 'org-tag-alist nil)
3996 (while (setq e (pop tgs))
3997 (or (and (stringp (car e))
3998 (assoc (car e) org-tag-alist))
3999 (push e org-tag-alist)))))
4001 ;; Compute the regular expressions and other local variables
4002 (if (not org-done-keywords)
4003 (setq org-done-keywords (and org-todo-keywords-1
4004 (list (org-last org-todo-keywords-1)))))
4005 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4006 (length org-scheduled-string)
4007 (length org-clock-string)
4008 (length org-closed-string)))
4009 org-drawer-regexp
4010 (concat "^[ \t]*:\\("
4011 (mapconcat 'regexp-quote org-drawers "\\|")
4012 "\\):[ \t]*$")
4013 org-not-done-keywords
4014 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4015 org-todo-regexp
4016 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4017 "\\|") "\\)\\>")
4018 org-not-done-regexp
4019 (concat "\\<\\("
4020 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4021 "\\)\\>")
4022 org-not-done-heading-regexp
4023 (concat "^\\(\\*+\\)[ \t]+\\("
4024 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4025 "\\)\\>")
4026 org-todo-line-regexp
4027 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4028 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4029 "\\)\\>\\)?[ \t]*\\(.*\\)")
4030 org-complex-heading-regexp
4031 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4032 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4033 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4034 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4035 org-complex-heading-regexp-format
4036 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4037 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4038 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4039 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4040 org-nl-done-regexp
4041 (concat "\n\\*+[ \t]+"
4042 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4043 "\\)" "\\>")
4044 org-todo-line-tags-regexp
4045 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4046 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4047 (org-re
4048 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4049 org-looking-at-done-regexp
4050 (concat "^" "\\(?:"
4051 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4052 "\\>")
4053 org-deadline-regexp (concat "\\<" org-deadline-string)
4054 org-deadline-time-regexp
4055 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4056 org-deadline-line-regexp
4057 (concat "\\<\\(" org-deadline-string "\\).*")
4058 org-scheduled-regexp
4059 (concat "\\<" org-scheduled-string)
4060 org-scheduled-time-regexp
4061 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4062 org-closed-time-regexp
4063 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4064 org-keyword-time-regexp
4065 (concat "\\<\\(" org-scheduled-string
4066 "\\|" org-deadline-string
4067 "\\|" org-closed-string
4068 "\\|" org-clock-string "\\)"
4069 " *[[<]\\([^]>]+\\)[]>]")
4070 org-keyword-time-not-clock-regexp
4071 (concat "\\<\\(" org-scheduled-string
4072 "\\|" org-deadline-string
4073 "\\|" org-closed-string
4074 "\\)"
4075 " *[[<]\\([^]>]+\\)[]>]")
4076 org-maybe-keyword-time-regexp
4077 (concat "\\(\\<\\(" org-scheduled-string
4078 "\\|" org-deadline-string
4079 "\\|" org-closed-string
4080 "\\|" org-clock-string "\\)\\)?"
4081 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4082 org-planning-or-clock-line-re
4083 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4084 "\\|" org-deadline-string
4085 "\\|" org-closed-string "\\|" org-clock-string
4086 "\\)\\>\\)")
4087 org-all-time-keywords
4088 (mapcar (lambda (w) (substring w 0 -1))
4089 (list org-scheduled-string org-deadline-string
4090 org-clock-string org-closed-string))
4092 (org-compute-latex-and-specials-regexp)
4093 (org-set-font-lock-defaults))))
4095 (defun org-file-contents (file &optional noerror)
4096 "Return the contents of FILE, as a string."
4097 (if (or (not file)
4098 (not (file-readable-p file)))
4099 (if noerror
4100 (progn
4101 (message "Cannot read file %s" file)
4102 (ding) (sit-for 2)
4104 (error "Cannot read file %s" file))
4105 (with-temp-buffer
4106 (insert-file-contents file)
4107 (buffer-string))))
4109 (defun org-extract-log-state-settings (x)
4110 "Extract the log state setting from a TODO keyword string.
4111 This will extract info from a string like \"WAIT(w@/!)\"."
4112 (let (kw key log1 log2)
4113 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4114 (setq kw (match-string 1 x)
4115 key (and (match-end 2) (match-string 2 x))
4116 log1 (and (match-end 3) (match-string 3 x))
4117 log2 (and (match-end 4) (match-string 4 x)))
4118 (and (or log1 log2)
4119 (list kw
4120 (and log1 (if (equal log1 "!") 'time 'note))
4121 (and log2 (if (equal log2 "!") 'time 'note)))))))
4123 (defun org-remove-keyword-keys (list)
4124 "Remove a pair of parenthesis at the end of each string in LIST."
4125 (mapcar (lambda (x)
4126 (if (string-match "(.*)$" x)
4127 (substring x 0 (match-beginning 0))
4129 list))
4131 ;; FIXME: this could be done much better, using second characters etc.
4132 (defun org-assign-fast-keys (alist)
4133 "Assign fast keys to a keyword-key alist.
4134 Respect keys that are already there."
4135 (let (new e k c c1 c2 (char ?a))
4136 (while (setq e (pop alist))
4137 (cond
4138 ((equal e '(:startgroup)) (push e new))
4139 ((equal e '(:endgroup)) (push e new))
4140 ((equal e '(:newline)) (push e new))
4142 (setq k (car e) c2 nil)
4143 (if (cdr e)
4144 (setq c (cdr e))
4145 ;; automatically assign a character.
4146 (setq c1 (string-to-char
4147 (downcase (substring
4148 k (if (= (string-to-char k) ?@) 1 0)))))
4149 (if (or (rassoc c1 new) (rassoc c1 alist))
4150 (while (or (rassoc char new) (rassoc char alist))
4151 (setq char (1+ char)))
4152 (setq c2 c1))
4153 (setq c (or c2 char)))
4154 (push (cons k c) new))))
4155 (nreverse new)))
4157 ;;; Some variables used in various places
4159 (defvar org-window-configuration nil
4160 "Used in various places to store a window configuration.")
4161 (defvar org-selected-window nil
4162 "Used in various places to store a window configuration.")
4163 (defvar org-finish-function nil
4164 "Function to be called when `C-c C-c' is used.
4165 This is for getting out of special buffers like remember.")
4168 ;; FIXME: Occasionally check by commenting these, to make sure
4169 ;; no other functions uses these, forgetting to let-bind them.
4170 (defvar entry)
4171 (defvar last-state)
4172 (defvar date)
4174 ;; Defined somewhere in this file, but used before definition.
4175 (defvar org-html-entities)
4176 (defvar org-struct-menu)
4177 (defvar org-org-menu)
4178 (defvar org-tbl-menu)
4180 ;;;; Define the Org-mode
4182 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4183 (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."))
4186 ;; We use a before-change function to check if a table might need
4187 ;; an update.
4188 (defvar org-table-may-need-update t
4189 "Indicates that a table might need an update.
4190 This variable is set by `org-before-change-function'.
4191 `org-table-align' sets it back to nil.")
4192 (defun org-before-change-function (beg end)
4193 "Every change indicates that a table might need an update."
4194 (setq org-table-may-need-update t))
4195 (defvar org-mode-map)
4196 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4197 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4198 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4199 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4200 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4201 (defvar org-table-buffer-is-an nil)
4202 (defconst org-outline-regexp "\\*+ ")
4204 ;;;###autoload
4205 (define-derived-mode org-mode outline-mode "Org"
4206 "Outline-based notes management and organizer, alias
4207 \"Carsten's outline-mode for keeping track of everything.\"
4209 Org-mode develops organizational tasks around a NOTES file which
4210 contains information about projects as plain text. Org-mode is
4211 implemented on top of outline-mode, which is ideal to keep the content
4212 of large files well structured. It supports ToDo items, deadlines and
4213 time stamps, which magically appear in the diary listing of the Emacs
4214 calendar. Tables are easily created with a built-in table editor.
4215 Plain text URL-like links connect to websites, emails (VM), Usenet
4216 messages (Gnus), BBDB entries, and any files related to the project.
4217 For printing and sharing of notes, an Org-mode file (or a part of it)
4218 can be exported as a structured ASCII or HTML file.
4220 The following commands are available:
4222 \\{org-mode-map}"
4224 ;; Get rid of Outline menus, they are not needed
4225 ;; Need to do this here because define-derived-mode sets up
4226 ;; the keymap so late. Still, it is a waste to call this each time
4227 ;; we switch another buffer into org-mode.
4228 (if (featurep 'xemacs)
4229 (when (boundp 'outline-mode-menu-heading)
4230 ;; Assume this is Greg's port, it used easymenu
4231 (easy-menu-remove outline-mode-menu-heading)
4232 (easy-menu-remove outline-mode-menu-show)
4233 (easy-menu-remove outline-mode-menu-hide))
4234 (define-key org-mode-map [menu-bar headings] 'undefined)
4235 (define-key org-mode-map [menu-bar hide] 'undefined)
4236 (define-key org-mode-map [menu-bar show] 'undefined))
4238 (org-load-modules-maybe)
4239 (easy-menu-add org-org-menu)
4240 (easy-menu-add org-tbl-menu)
4241 (org-install-agenda-files-menu)
4242 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4243 (org-add-to-invisibility-spec '(org-cwidth))
4244 (org-add-to-invisibility-spec '(org-hide-block . t))
4245 (when (featurep 'xemacs)
4246 (org-set-local 'line-move-ignore-invisible t))
4247 (org-set-local 'outline-regexp org-outline-regexp)
4248 (org-set-local 'outline-level 'org-outline-level)
4249 (when (and org-ellipsis
4250 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4251 (fboundp 'make-glyph-code))
4252 (unless org-display-table
4253 (setq org-display-table (make-display-table)))
4254 (set-display-table-slot
4255 org-display-table 4
4256 (vconcat (mapcar
4257 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4258 org-ellipsis)))
4259 (if (stringp org-ellipsis) org-ellipsis "..."))))
4260 (setq buffer-display-table org-display-table))
4261 (org-set-regexps-and-options)
4262 (when (and org-tag-faces (not org-tags-special-faces-re))
4263 ;; tag faces set outside customize.... force initialization.
4264 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4265 ;; Calc embedded
4266 (org-set-local 'calc-embedded-open-mode "# ")
4267 (modify-syntax-entry ?# "<")
4268 (modify-syntax-entry ?@ "w")
4269 (if org-startup-truncated (setq truncate-lines t))
4270 (org-set-local 'font-lock-unfontify-region-function
4271 'org-unfontify-region)
4272 ;; Activate before-change-function
4273 (org-set-local 'org-table-may-need-update t)
4274 (org-add-hook 'before-change-functions 'org-before-change-function nil
4275 'local)
4276 ;; Check for running clock before killing a buffer
4277 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4278 ;; Paragraphs and auto-filling
4279 (org-set-autofill-regexps)
4280 (setq indent-line-function 'org-indent-line-function)
4281 (org-update-radio-target-regexp)
4282 ;; Make sure dependence stuff works reliably, even for users who set it
4283 ;; too late :-(
4284 (if org-enforce-todo-dependencies
4285 (add-hook 'org-blocker-hook
4286 'org-block-todo-from-children-or-siblings-or-parent)
4287 (remove-hook 'org-blocker-hook
4288 'org-block-todo-from-children-or-siblings-or-parent))
4289 (if org-enforce-todo-checkbox-dependencies
4290 (add-hook 'org-blocker-hook
4291 'org-block-todo-from-checkboxes)
4292 (remove-hook 'org-blocker-hook
4293 'org-block-todo-from-checkboxes))
4295 ;; Comment characters
4296 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4297 (org-set-local 'comment-padding " ")
4299 ;; Align options lines
4300 (org-set-local
4301 'align-mode-rules-list
4302 '((org-in-buffer-settings
4303 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4304 (modes . '(org-mode)))))
4306 ;; Imenu
4307 (org-set-local 'imenu-create-index-function
4308 'org-imenu-get-tree)
4310 ;; Make isearch reveal context
4311 (if (or (featurep 'xemacs)
4312 (not (boundp 'outline-isearch-open-invisible-function)))
4313 ;; Emacs 21 and XEmacs make use of the hook
4314 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4315 ;; Emacs 22 deals with this through a special variable
4316 (org-set-local 'outline-isearch-open-invisible-function
4317 (lambda (&rest ignore) (org-show-context 'isearch))))
4319 ;; Turn on org-beamer-mode?
4320 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4322 ;; If empty file that did not turn on org-mode automatically, make it to.
4323 (if (and org-insert-mode-line-in-empty-file
4324 (interactive-p)
4325 (= (point-min) (point-max)))
4326 (insert "# -*- mode: org -*-\n\n"))
4327 (unless org-inhibit-startup
4328 (when org-startup-align-all-tables
4329 (let ((bmp (buffer-modified-p)))
4330 (org-table-map-tables 'org-table-align)
4331 (set-buffer-modified-p bmp)))
4332 (when org-startup-indented
4333 (require 'org-indent)
4334 (org-indent-mode 1))
4335 (unless org-inhibit-startup-visibility-stuff
4336 (org-set-startup-visibility))))
4338 (when (fboundp 'abbrev-table-put)
4339 (abbrev-table-put org-mode-abbrev-table
4340 :parents (list text-mode-abbrev-table)))
4342 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4344 (defun org-current-time ()
4345 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4346 (if (> (car org-time-stamp-rounding-minutes) 1)
4347 (let ((r (car org-time-stamp-rounding-minutes))
4348 (time (decode-time)))
4349 (apply 'encode-time
4350 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4351 (nthcdr 2 time))))
4352 (current-time)))
4354 ;;;; Font-Lock stuff, including the activators
4356 (defvar org-mouse-map (make-sparse-keymap))
4357 (org-defkey org-mouse-map
4358 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4359 (org-defkey org-mouse-map
4360 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4361 (when org-mouse-1-follows-link
4362 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4363 (when org-tab-follows-link
4364 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4365 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4367 (require 'font-lock)
4369 (defconst org-non-link-chars "]\t\n\r<>")
4370 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4371 "shell" "elisp"))
4372 (defvar org-link-types-re nil
4373 "Matches a link that has a url-like prefix like \"http:\"")
4374 (defvar org-link-re-with-space nil
4375 "Matches a link with spaces, optional angular brackets around it.")
4376 (defvar org-link-re-with-space2 nil
4377 "Matches a link with spaces, optional angular brackets around it.")
4378 (defvar org-link-re-with-space3 nil
4379 "Matches a link with spaces, only for internal part in bracket links.")
4380 (defvar org-angle-link-re nil
4381 "Matches link with angular brackets, spaces are allowed.")
4382 (defvar org-plain-link-re nil
4383 "Matches plain link, without spaces.")
4384 (defvar org-bracket-link-regexp nil
4385 "Matches a link in double brackets.")
4386 (defvar org-bracket-link-analytic-regexp nil
4387 "Regular expression used to analyze links.
4388 Here is what the match groups contain after a match:
4389 1: http:
4390 2: http
4391 3: path
4392 4: [desc]
4393 5: desc")
4394 (defvar org-bracket-link-analytic-regexp++ nil
4395 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4396 (defvar org-any-link-re nil
4397 "Regular expression matching any link.")
4399 (defun org-make-link-regexps ()
4400 "Update the link regular expressions.
4401 This should be called after the variable `org-link-types' has changed."
4402 (setq org-link-types-re
4403 (concat
4404 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4405 org-link-re-with-space
4406 (concat
4407 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4408 "\\([^" org-non-link-chars " ]"
4409 "[^" org-non-link-chars "]*"
4410 "[^" org-non-link-chars " ]\\)>?")
4411 org-link-re-with-space2
4412 (concat
4413 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4414 "\\([^" org-non-link-chars " ]"
4415 "[^\t\n\r]*"
4416 "[^" org-non-link-chars " ]\\)>?")
4417 org-link-re-with-space3
4418 (concat
4419 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4420 "\\([^" org-non-link-chars " ]"
4421 "[^\t\n\r]*\\)")
4422 org-angle-link-re
4423 (concat
4424 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4425 "\\([^" org-non-link-chars " ]"
4426 "[^" org-non-link-chars "]*"
4427 "\\)>")
4428 org-plain-link-re
4429 (concat
4430 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4431 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4432 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4433 org-bracket-link-regexp
4434 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4435 org-bracket-link-analytic-regexp
4436 (concat
4437 "\\[\\["
4438 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4439 "\\([^]]+\\)"
4440 "\\]"
4441 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4442 "\\]")
4443 org-bracket-link-analytic-regexp++
4444 (concat
4445 "\\[\\["
4446 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4447 "\\([^]]+\\)"
4448 "\\]"
4449 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4450 "\\]")
4451 org-any-link-re
4452 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4453 org-angle-link-re "\\)\\|\\("
4454 org-plain-link-re "\\)")))
4456 (org-make-link-regexps)
4458 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4459 "Regular expression for fast time stamp matching.")
4460 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4461 "Regular expression for fast time stamp matching.")
4462 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4463 "Regular expression matching time strings for analysis.
4464 This one does not require the space after the date, so it can be used
4465 on a string that terminates immediately after the date.")
4466 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4467 "Regular expression matching time strings for analysis.")
4468 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4469 "Regular expression matching time stamps, with groups.")
4470 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4471 "Regular expression matching time stamps (also [..]), with groups.")
4472 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4473 "Regular expression matching a time stamp range.")
4474 (defconst org-tr-regexp-both
4475 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4476 "Regular expression matching a time stamp range.")
4477 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4478 org-ts-regexp "\\)?")
4479 "Regular expression matching a time stamp or time stamp range.")
4480 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4481 org-ts-regexp-both "\\)?")
4482 "Regular expression matching a time stamp or time stamp range.
4483 The time stamps may be either active or inactive.")
4485 (defvar org-emph-face nil)
4487 (defun org-do-emphasis-faces (limit)
4488 "Run through the buffer and add overlays to links."
4489 (let (rtn a)
4490 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4491 (if (not (= (char-after (match-beginning 3))
4492 (char-after (match-beginning 4))))
4493 (progn
4494 (setq rtn t)
4495 (setq a (assoc (match-string 3) org-emphasis-alist))
4496 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4497 'face
4498 (nth 1 a))
4499 (and (nth 4 a)
4500 (org-remove-flyspell-overlays-in
4501 (match-beginning 0) (match-end 0)))
4502 (add-text-properties (match-beginning 2) (match-end 2)
4503 '(font-lock-multiline t))
4504 (when org-hide-emphasis-markers
4505 (add-text-properties (match-end 4) (match-beginning 5)
4506 '(invisible org-link))
4507 (add-text-properties (match-beginning 3) (match-end 3)
4508 '(invisible org-link)))))
4509 (backward-char 1))
4510 rtn))
4512 (defun org-emphasize (&optional char)
4513 "Insert or change an emphasis, i.e. a font like bold or italic.
4514 If there is an active region, change that region to a new emphasis.
4515 If there is no region, just insert the marker characters and position
4516 the cursor between them.
4517 CHAR should be either the marker character, or the first character of the
4518 HTML tag associated with that emphasis. If CHAR is a space, the means
4519 to remove the emphasis of the selected region.
4520 If char is not given (for example in an interactive call) it
4521 will be prompted for."
4522 (interactive)
4523 (let ((eal org-emphasis-alist) e det
4524 (erc org-emphasis-regexp-components)
4525 (prompt "")
4526 (string "") beg end move tag c s)
4527 (if (org-region-active-p)
4528 (setq beg (region-beginning) end (region-end)
4529 string (buffer-substring beg end))
4530 (setq move t))
4532 (while (setq e (pop eal))
4533 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4534 c (aref tag 0))
4535 (push (cons c (string-to-char (car e))) det)
4536 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4537 (substring tag 1)))))
4538 (setq det (nreverse det))
4539 (unless char
4540 (message "%s" (concat "Emphasis marker or tag:" prompt))
4541 (setq char (read-char-exclusive)))
4542 (setq char (or (cdr (assoc char det)) char))
4543 (if (equal char ?\ )
4544 (setq s "" move nil)
4545 (unless (assoc (char-to-string char) org-emphasis-alist)
4546 (error "No such emphasis marker: \"%c\"" char))
4547 (setq s (char-to-string char)))
4548 (while (and (> (length string) 1)
4549 (equal (substring string 0 1) (substring string -1))
4550 (assoc (substring string 0 1) org-emphasis-alist))
4551 (setq string (substring string 1 -1)))
4552 (setq string (concat s string s))
4553 (if beg (delete-region beg end))
4554 (unless (or (bolp)
4555 (string-match (concat "[" (nth 0 erc) "\n]")
4556 (char-to-string (char-before (point)))))
4557 (insert " "))
4558 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4559 (char-to-string (char-after (point))))
4560 (insert " ") (backward-char 1))
4561 (insert string)
4562 (and move (backward-char 1))))
4564 (defconst org-nonsticky-props
4565 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4567 (defsubst org-rear-nonsticky-at (pos)
4568 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4570 (defun org-activate-plain-links (limit)
4571 "Run through the buffer and add overlays to links."
4572 (catch 'exit
4573 (let (f)
4574 (if (re-search-forward org-plain-link-re limit t)
4575 (progn
4576 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4577 (setq f (get-text-property (match-beginning 0) 'face))
4578 (if (or (eq f 'org-tag)
4579 (and (listp f) (memq 'org-tag f)))
4581 (add-text-properties (match-beginning 0) (match-end 0)
4582 (list 'mouse-face 'highlight
4583 'face 'org-link
4584 'keymap org-mouse-map))
4585 (org-rear-nonsticky-at (match-end 0)))
4586 t)))))
4588 (defun org-activate-code (limit)
4589 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4590 (progn
4591 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4592 (remove-text-properties (match-beginning 0) (match-end 0)
4593 '(display t invisible t intangible t))
4594 t)))
4596 (defun org-fontify-meta-lines-and-blocks (limit)
4597 "Fontify #+ lines and blocks, in the correct ways."
4598 (let ((case-fold-search t))
4599 (if (re-search-forward
4600 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4601 limit t)
4602 (let ((beg (match-beginning 0))
4603 (beg1 (line-beginning-position 2))
4604 (dc1 (downcase (match-string 2)))
4605 (dc3 (downcase (match-string 3)))
4606 end end1 quoting block-type)
4607 (cond
4608 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4609 ;; a single line of backend-specific content
4610 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4611 (remove-text-properties (match-beginning 0) (match-end 0)
4612 '(display t invisible t intangible t))
4613 (add-text-properties (match-beginning 1) (match-end 3)
4614 '(font-lock-fontified t face org-meta-line))
4615 (add-text-properties (match-beginning 6) (match-end 6)
4616 '(font-lock-fontified t face org-block))
4618 ((and (match-end 4) (equal dc3 "begin"))
4619 ;; Truely a block
4620 (setq block-type (downcase (match-string 5))
4621 quoting (member block-type org-protecting-blocks))
4622 (when (re-search-forward
4623 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4624 nil t) ;; on purpose, we look further than LIMIT
4625 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4626 (when quoting
4627 (remove-text-properties beg end
4628 '(display t invisible t intangible t)))
4629 (add-text-properties
4630 beg end
4631 '(font-lock-fontified t font-lock-multiline t))
4632 (add-text-properties beg beg1 '(face org-meta-line))
4633 (add-text-properties end1 end '(face org-meta-line))
4634 (cond
4635 (quoting
4636 (add-text-properties beg1 end1 '(face org-block)))
4637 ((string= block-type "quote")
4638 (add-text-properties beg1 end1 '(face org-quote)))
4639 ((string= block-type "verse")
4640 (add-text-properties beg1 end1 '(face org-verse))))
4642 ((not (member (char-after beg) '(?\ ?\t)))
4643 ;; just any other in-buffer setting, but not indented
4644 (add-text-properties
4645 beg (match-end 0)
4646 '(font-lock-fontified t face org-meta-line))
4648 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4649 "orgtbl:" "tblfm:" "tblname:"))
4650 (and (match-end 4) (equal dc3 "attr")))
4651 (add-text-properties
4652 beg (match-end 0)
4653 '(font-lock-fontified t face org-meta-line))
4655 ((member dc3 '(" " ""))
4656 (add-text-properties
4657 beg (match-end 0)
4658 '(font-lock-fontified t face font-lock-comment-face)))
4659 (t nil))))))
4661 (defun org-activate-angle-links (limit)
4662 "Run through the buffer and add overlays to links."
4663 (if (re-search-forward org-angle-link-re limit t)
4664 (progn
4665 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4666 (add-text-properties (match-beginning 0) (match-end 0)
4667 (list 'mouse-face 'highlight
4668 'keymap org-mouse-map))
4669 (org-rear-nonsticky-at (match-end 0))
4670 t)))
4672 (defun org-activate-footnote-links (limit)
4673 "Run through the buffer and add overlays to links."
4674 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4675 limit t)
4676 (progn
4677 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4678 (add-text-properties (match-beginning 2) (match-end 2)
4679 (list 'mouse-face 'highlight
4680 'keymap org-mouse-map
4681 'help-echo
4682 (if (= (point-at-bol) (match-beginning 2))
4683 "Footnote definition"
4684 "Footnote reference")
4686 (org-rear-nonsticky-at (match-end 2))
4687 t)))
4689 (defun org-activate-bracket-links (limit)
4690 "Run through the buffer and add overlays to bracketed links."
4691 (if (re-search-forward org-bracket-link-regexp limit t)
4692 (let* ((help (concat "LINK: "
4693 (org-match-string-no-properties 1)))
4694 ;; FIXME: above we should remove the escapes.
4695 ;; but that requires another match, protecting match data,
4696 ;; a lot of overhead for font-lock.
4697 (ip (org-maybe-intangible
4698 (list 'invisible 'org-link
4699 'keymap org-mouse-map 'mouse-face 'highlight
4700 'font-lock-multiline t 'help-echo help)))
4701 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4702 'font-lock-multiline t 'help-echo help)))
4703 ;; We need to remove the invisible property here. Table narrowing
4704 ;; may have made some of this invisible.
4705 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4706 (remove-text-properties (match-beginning 0) (match-end 0)
4707 '(invisible nil))
4708 (if (match-end 3)
4709 (progn
4710 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4711 (org-rear-nonsticky-at (match-beginning 3))
4712 (add-text-properties (match-beginning 3) (match-end 3) vp)
4713 (org-rear-nonsticky-at (match-end 3))
4714 (add-text-properties (match-end 3) (match-end 0) ip)
4715 (org-rear-nonsticky-at (match-end 0)))
4716 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4717 (org-rear-nonsticky-at (match-beginning 1))
4718 (add-text-properties (match-beginning 1) (match-end 1) vp)
4719 (org-rear-nonsticky-at (match-end 1))
4720 (add-text-properties (match-end 1) (match-end 0) ip)
4721 (org-rear-nonsticky-at (match-end 0)))
4722 t)))
4724 (defun org-activate-dates (limit)
4725 "Run through the buffer and add overlays to dates."
4726 (if (re-search-forward org-tsr-regexp-both limit t)
4727 (progn
4728 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4729 (add-text-properties (match-beginning 0) (match-end 0)
4730 (list 'mouse-face 'highlight
4731 'keymap org-mouse-map))
4732 (org-rear-nonsticky-at (match-end 0))
4733 (when org-display-custom-times
4734 (if (match-end 3)
4735 (org-display-custom-time (match-beginning 3) (match-end 3)))
4736 (org-display-custom-time (match-beginning 1) (match-end 1)))
4737 t)))
4739 (defvar org-target-link-regexp nil
4740 "Regular expression matching radio targets in plain text.")
4741 (make-variable-buffer-local 'org-target-link-regexp)
4742 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4743 "Regular expression matching a link target.")
4744 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4745 "Regular expression matching a radio target.")
4746 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4747 "Regular expression matching any target.")
4749 (defun org-activate-target-links (limit)
4750 "Run through the buffer and add overlays to target matches."
4751 (when org-target-link-regexp
4752 (let ((case-fold-search t))
4753 (if (re-search-forward org-target-link-regexp limit t)
4754 (progn
4755 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4756 (add-text-properties (match-beginning 0) (match-end 0)
4757 (list 'mouse-face 'highlight
4758 'keymap org-mouse-map
4759 'help-echo "Radio target link"
4760 'org-linked-text t))
4761 (org-rear-nonsticky-at (match-end 0))
4762 t)))))
4764 (defun org-update-radio-target-regexp ()
4765 "Find all radio targets in this file and update the regular expression."
4766 (interactive)
4767 (when (memq 'radio org-activate-links)
4768 (setq org-target-link-regexp
4769 (org-make-target-link-regexp (org-all-targets 'radio)))
4770 (org-restart-font-lock)))
4772 (defun org-hide-wide-columns (limit)
4773 (let (s e)
4774 (setq s (text-property-any (point) (or limit (point-max))
4775 'org-cwidth t))
4776 (when s
4777 (setq e (next-single-property-change s 'org-cwidth))
4778 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4779 (goto-char e)
4780 t)))
4782 (defvar org-latex-and-specials-regexp nil
4783 "Regular expression for highlighting export special stuff.")
4784 (defvar org-match-substring-regexp)
4785 (defvar org-match-substring-with-braces-regexp)
4787 ;; This should be with the exporter code, but we also use if for font-locking
4788 (defconst org-export-html-special-string-regexps
4789 '(("\\\\-" . "&shy;")
4790 ("---\\([^-]\\)" . "&mdash;\\1")
4791 ("--\\([^-]\\)" . "&ndash;\\1")
4792 ("\\.\\.\\." . "&hellip;"))
4793 "Regular expressions for special string conversion.")
4796 (defun org-compute-latex-and-specials-regexp ()
4797 "Compute regular expression for stuff treated specially by exporters."
4798 (if (not org-highlight-latex-fragments-and-specials)
4799 (org-set-local 'org-latex-and-specials-regexp nil)
4800 (require 'org-exp)
4801 (let*
4802 ((matchers (plist-get org-format-latex-options :matchers))
4803 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4804 org-latex-regexps)))
4805 (org-export-allow-BIND nil)
4806 (options (org-combine-plists (org-default-export-plist)
4807 (org-infile-export-plist)))
4808 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4809 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4810 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4811 (org-export-html-expand (plist-get options :expand-quoted-html))
4812 (org-export-with-special-strings (plist-get options :special-strings))
4813 (re-sub
4814 (cond
4815 ((equal org-export-with-sub-superscripts '{})
4816 (list org-match-substring-with-braces-regexp))
4817 (org-export-with-sub-superscripts
4818 (list org-match-substring-regexp))
4819 (t nil)))
4820 (re-latex
4821 (if org-export-with-LaTeX-fragments
4822 (mapcar (lambda (x) (nth 1 x)) latexs)))
4823 (re-macros
4824 (if org-export-with-TeX-macros
4825 (list (concat "\\\\"
4826 (regexp-opt
4827 (append (mapcar 'car org-html-entities)
4828 (if (boundp 'org-latex-entities)
4829 (mapcar (lambda (x)
4830 (or (car-safe x) x))
4831 org-latex-entities)
4832 nil))
4833 'words))) ; FIXME
4835 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4836 (re-special (if org-export-with-special-strings
4837 (mapcar (lambda (x) (car x))
4838 org-export-html-special-string-regexps)))
4839 (re-rest
4840 (delq nil
4841 (list
4842 (if org-export-html-expand "@<[^>\n]+>")
4843 ))))
4844 (org-set-local
4845 'org-latex-and-specials-regexp
4846 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4847 re-rest) "\\|")))))
4849 (defun org-do-latex-and-special-faces (limit)
4850 "Run through the buffer and add overlays to links."
4851 (when org-latex-and-specials-regexp
4852 (let (rtn d)
4853 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4854 limit t))
4855 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4856 'face))
4857 '(org-code org-verbatim underline)))
4858 (progn
4859 (setq rtn t
4860 d (cond ((member (char-after (1+ (match-beginning 0)))
4861 '(?_ ?^)) 1)
4862 (t 0)))
4863 (font-lock-prepend-text-property
4864 (+ d (match-beginning 0)) (match-end 0)
4865 'face 'org-latex-and-export-specials)
4866 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4867 '(font-lock-multiline t)))))
4868 rtn)))
4870 (defun org-restart-font-lock ()
4871 "Restart font-lock-mode, to force refontification."
4872 (when (and (boundp 'font-lock-mode) font-lock-mode)
4873 (font-lock-mode -1)
4874 (font-lock-mode 1)))
4876 (defun org-all-targets (&optional radio)
4877 "Return a list of all targets in this file.
4878 With optional argument RADIO, only find radio targets."
4879 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4880 rtn)
4881 (save-excursion
4882 (goto-char (point-min))
4883 (while (re-search-forward re nil t)
4884 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4885 rtn)))
4887 (defun org-make-target-link-regexp (targets)
4888 "Make regular expression matching all strings in TARGETS.
4889 The regular expression finds the targets also if there is a line break
4890 between words."
4891 (and targets
4892 (concat
4893 "\\<\\("
4894 (mapconcat
4895 (lambda (x)
4896 (while (string-match " +" x)
4897 (setq x (replace-match "\\s-+" t t x)))
4899 targets
4900 "\\|")
4901 "\\)\\>")))
4903 (defun org-activate-tags (limit)
4904 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4905 (progn
4906 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4907 (add-text-properties (match-beginning 1) (match-end 1)
4908 (list 'mouse-face 'highlight
4909 'keymap org-mouse-map))
4910 (org-rear-nonsticky-at (match-end 1))
4911 t)))
4913 (defun org-outline-level ()
4914 "Compute the outline level of the heading at point.
4915 This function assumes that the cursor is at the beginning of a line matched
4916 by outline-regexp. Otherwise it returns garbage.
4917 If this is called at a normal headline, the level is the number of stars.
4918 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4919 For plain list items, if they are matched by `outline-regexp', this returns
4920 1000 plus the line indentation."
4921 (save-excursion
4922 (looking-at outline-regexp)
4923 (if (match-beginning 1)
4924 (+ (org-get-string-indentation (match-string 1)) 1000)
4925 (1- (- (match-end 0) (match-beginning 0))))))
4927 (defvar org-font-lock-keywords nil)
4929 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4930 "Regular expression matching a property line.")
4932 (defvar org-font-lock-hook nil
4933 "Functions to be called for special font lock stuff.")
4935 (defun org-font-lock-hook (limit)
4936 (run-hook-with-args 'org-font-lock-hook limit))
4938 (defun org-set-font-lock-defaults ()
4939 (let* ((em org-fontify-emphasized-text)
4940 (lk org-activate-links)
4941 (org-font-lock-extra-keywords
4942 (list
4943 ;; Call the hook
4944 '(org-font-lock-hook)
4945 ;; Headlines
4946 `(,(if org-fontify-whole-heading-line
4947 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4948 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4949 (1 (org-get-level-face 1))
4950 (2 (org-get-level-face 2))
4951 (3 (org-get-level-face 3)))
4952 ;; Table lines
4953 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4954 (1 'org-table t))
4955 ;; Table internals
4956 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4957 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4958 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4959 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4960 ;; Drawers
4961 (list org-drawer-regexp '(0 'org-special-keyword t))
4962 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4963 ;; Properties
4964 (list org-property-re
4965 '(1 'org-special-keyword t)
4966 '(3 'org-property-value t))
4967 ;; Links
4968 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4969 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4970 (if (memq 'plain lk) '(org-activate-plain-links))
4971 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4972 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4973 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4974 (if (memq 'footnote lk) '(org-activate-footnote-links
4975 (2 'org-footnote t)))
4976 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4977 '(org-hide-wide-columns (0 nil append))
4978 ;; TODO lines
4979 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4980 '(1 (org-get-todo-face 1) t))
4981 ;; DONE
4982 (if org-fontify-done-headline
4983 (list (concat "^[*]+ +\\<\\("
4984 (mapconcat 'regexp-quote org-done-keywords "\\|")
4985 "\\)\\(.*\\)")
4986 '(2 'org-headline-done t))
4987 nil)
4988 ;; Priorities
4989 '(org-font-lock-add-priority-faces)
4990 ;; Tags
4991 '(org-font-lock-add-tag-faces)
4992 ;; Special keywords
4993 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4994 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4995 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4996 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4997 ;; Emphasis
4998 (if em
4999 (if (featurep 'xemacs)
5000 '(org-do-emphasis-faces (0 nil append))
5001 '(org-do-emphasis-faces)))
5002 ;; Checkboxes
5003 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5004 2 'org-checkbox prepend)
5005 (if org-provide-checkbox-statistics
5006 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5007 (0 (org-get-checkbox-statistics-face) t)))
5008 ;; Description list items
5009 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5010 2 'bold prepend)
5011 ;; ARCHIVEd headings
5012 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5013 '(1 'org-archived prepend))
5014 ;; Specials
5015 '(org-do-latex-and-special-faces)
5016 ;; Code
5017 '(org-activate-code (1 'org-code t))
5018 ;; COMMENT
5019 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5020 "\\|" org-quote-string "\\)\\>")
5021 '(1 'org-special-keyword t))
5022 '("^#.*" (0 'font-lock-comment-face t))
5023 ;; Blocks and meta lines
5024 '(org-fontify-meta-lines-and-blocks)
5026 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5027 ;; Now set the full font-lock-keywords
5028 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5029 (org-set-local 'font-lock-defaults
5030 '(org-font-lock-keywords t nil nil backward-paragraph))
5031 (kill-local-variable 'font-lock-keywords) nil))
5033 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5034 "Fontify string S like in Org-mode"
5035 (with-temp-buffer
5036 (insert s)
5037 (let ((org-odd-levels-only odd-levels))
5038 (org-mode)
5039 (font-lock-fontify-buffer)
5040 (buffer-string))))
5042 (defvar org-m nil)
5043 (defvar org-l nil)
5044 (defvar org-f nil)
5045 (defun org-get-level-face (n)
5046 "Get the right face for match N in font-lock matching of headlines."
5047 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5048 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5049 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5050 (cond
5051 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5052 ((eq n 2) org-f)
5053 (t (if org-level-color-stars-only nil org-f))))
5055 (defun org-get-todo-face (kwd)
5056 "Get the right face for a TODO keyword KWD.
5057 If KWD is a number, get the corresponding match group."
5058 (if (numberp kwd) (setq kwd (match-string kwd)))
5059 (or (cdr (assoc kwd org-todo-keyword-faces))
5060 (and (member kwd org-done-keywords) 'org-done)
5061 'org-todo))
5063 (defun org-font-lock-add-tag-faces (limit)
5064 "Add the special tag faces."
5065 (when (and org-tag-faces org-tags-special-faces-re)
5066 (while (re-search-forward org-tags-special-faces-re limit t)
5067 (add-text-properties (match-beginning 1) (match-end 1)
5068 (list 'face (org-get-tag-face 1)
5069 'font-lock-fontified t))
5070 (backward-char 1))))
5072 (defun org-font-lock-add-priority-faces (limit)
5073 "Add the special priority faces."
5074 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5075 (add-text-properties
5076 (match-beginning 0) (match-end 0)
5077 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5078 org-priority-faces))
5079 'org-special-keyword)
5080 'font-lock-fontified t))))
5082 (defun org-get-tag-face (kwd)
5083 "Get the right face for a TODO keyword KWD.
5084 If KWD is a number, get the corresponding match group."
5085 (if (numberp kwd) (setq kwd (match-string kwd)))
5086 (or (cdr (assoc kwd org-tag-faces))
5087 'org-tag))
5089 (defun org-unfontify-region (beg end &optional maybe_loudly)
5090 "Remove fontification and activation overlays from links."
5091 (font-lock-default-unfontify-region beg end)
5092 (let* ((buffer-undo-list t)
5093 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5094 (inhibit-modification-hooks t)
5095 deactivate-mark buffer-file-name buffer-file-truename)
5096 (remove-text-properties
5097 beg end
5098 (if org-indent-mode
5099 ;; also remove line-prefix and wrap-prefix properties
5100 '(mouse-face t keymap t org-linked-text t
5101 invisible t intangible t
5102 line-prefix t wrap-prefix t
5103 org-no-flyspell t)
5104 '(mouse-face t keymap t org-linked-text t
5105 invisible t intangible t
5106 org-no-flyspell t)))))
5108 ;;;; Visibility cycling, including org-goto and indirect buffer
5110 ;;; Cycling
5112 (defvar org-cycle-global-status nil)
5113 (make-variable-buffer-local 'org-cycle-global-status)
5114 (defvar org-cycle-subtree-status nil)
5115 (make-variable-buffer-local 'org-cycle-subtree-status)
5117 ;;;###autoload
5119 (defvar org-inlinetask-min-level)
5121 (defun org-cycle (&optional arg)
5122 "TAB-action and visibility cycling for Org-mode.
5124 This is the command invoked in Org-mode by the TAB key. Its main purpose
5125 is outline visibility cycling, but it also invokes other actions
5126 in special contexts.
5128 - When this function is called with a prefix argument, rotate the entire
5129 buffer through 3 states (global cycling)
5130 1. OVERVIEW: Show only top-level headlines.
5131 2. CONTENTS: Show all headlines of all levels, but no body text.
5132 3. SHOW ALL: Show everything.
5133 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5134 determined by the variable `org-startup-folded', and by any VISIBILITY
5135 properties in the buffer.
5136 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5137 including any drawers.
5139 - When inside a table, re-align the table and move to the next field.
5141 - When point is at the beginning of a headline, rotate the subtree started
5142 by this line through 3 different states (local cycling)
5143 1. FOLDED: Only the main headline is shown.
5144 2. CHILDREN: The main headline and the direct children are shown.
5145 From this state, you can move to one of the children
5146 and zoom in further.
5147 3. SUBTREE: Show the entire subtree, including body text.
5148 If there is no subtree, switch directly from CHILDREN to FOLDED.
5150 - When there is a numeric prefix, go up to a heading with level ARG, do
5151 a `show-subtree' and return to the previous cursor position. If ARG
5152 is negative, go up that many levels.
5154 - When point is not at the beginning of a headline, execute the global
5155 binding for TAB, which is re-indenting the line. See the option
5156 `org-cycle-emulate-tab' for details.
5158 - Special case: if point is at the beginning of the buffer and there is
5159 no headline in line 1, this function will act as if called with prefix arg.
5160 But only if also the variable `org-cycle-global-at-bob' is t."
5161 (interactive "P")
5162 (org-load-modules-maybe)
5163 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5164 (and org-cycle-level-after-item/entry-creation
5165 (or (org-cycle-level)
5166 (org-cycle-item-indentation))))
5167 (let* ((limit-level
5168 (or org-cycle-max-level
5169 (and (boundp 'org-inlinetask-min-level)
5170 org-inlinetask-min-level
5171 (1- org-inlinetask-min-level))))
5172 (nstars (and limit-level
5173 (if org-odd-levels-only
5174 (and limit-level (1- (* limit-level 2)))
5175 limit-level)))
5176 (outline-regexp
5177 (cond
5178 ((not (org-mode-p)) outline-regexp)
5179 ((or (eq org-cycle-include-plain-lists 'integrate)
5180 (and org-cycle-include-plain-lists (org-at-item-p)))
5181 (concat "\\(?:\\*"
5182 (if nstars (format "\\{1,%d\\}" nstars) "+")
5183 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5184 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5185 (bob-special (and org-cycle-global-at-bob (bobp)
5186 (not (looking-at outline-regexp))))
5187 (org-cycle-hook
5188 (if bob-special
5189 (delq 'org-optimize-window-after-visibility-change
5190 (copy-sequence org-cycle-hook))
5191 org-cycle-hook))
5192 (pos (point)))
5194 (if (or bob-special (equal arg '(4)))
5195 ;; special case: use global cycling
5196 (setq arg t))
5198 (cond
5200 ((equal arg '(16))
5201 (org-set-startup-visibility)
5202 (message "Startup visibility, plus VISIBILITY properties"))
5204 ((equal arg '(64))
5205 (show-all)
5206 (message "Entire buffer visible, including drawers"))
5208 ((org-at-table-p 'any)
5209 ;; Enter the table or move to the next field in the table
5210 (or (org-table-recognize-table.el)
5211 (progn
5212 (if arg (org-table-edit-field t)
5213 (org-table-justify-field-maybe)
5214 (call-interactively 'org-table-next-field)))))
5216 ((run-hook-with-args-until-success
5217 'org-tab-after-check-for-table-hook))
5219 ((eq arg t) ;; Global cycling
5220 (org-cycle-internal-global))
5222 ((and org-drawers org-drawer-regexp
5223 (save-excursion
5224 (beginning-of-line 1)
5225 (looking-at org-drawer-regexp)))
5226 ;; Toggle block visibility
5227 (org-flag-drawer
5228 (not (get-char-property (match-end 0) 'invisible))))
5230 ((integerp arg)
5231 ;; Show-subtree, ARG levels up from here.
5232 (save-excursion
5233 (org-back-to-heading)
5234 (outline-up-heading (if (< arg 0) (- arg)
5235 (- (funcall outline-level) arg)))
5236 (org-show-subtree)))
5238 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5239 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5241 (org-cycle-internal-local))
5243 ;; TAB emulation and template completion
5244 (buffer-read-only (org-back-to-heading))
5246 ((run-hook-with-args-until-success
5247 'org-tab-after-check-for-cycling-hook))
5249 ((org-try-structure-completion))
5251 ((org-try-cdlatex-tab))
5253 ((run-hook-with-args-until-success
5254 'org-tab-before-tab-emulation-hook))
5256 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5257 (or (not (bolp))
5258 (not (looking-at outline-regexp))))
5259 (call-interactively (global-key-binding "\t")))
5261 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5262 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5263 (or (and (eq org-cycle-emulate-tab 'white)
5264 (= (match-end 0) (point-at-eol)))
5265 (and (eq org-cycle-emulate-tab 'whitestart)
5266 (>= (match-end 0) pos))))
5268 (eq org-cycle-emulate-tab t))
5269 (call-interactively (global-key-binding "\t")))
5271 (t (save-excursion
5272 (org-back-to-heading)
5273 (org-cycle)))))))
5275 (defun org-cycle-internal-global ()
5276 "Do the global cycling action."
5277 (cond
5278 ((and (eq last-command this-command)
5279 (eq org-cycle-global-status 'overview))
5280 ;; We just created the overview - now do table of contents
5281 ;; This can be slow in very large buffers, so indicate action
5282 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5283 (message "CONTENTS...")
5284 (org-content)
5285 (message "CONTENTS...done")
5286 (setq org-cycle-global-status 'contents)
5287 (run-hook-with-args 'org-cycle-hook 'contents))
5289 ((and (eq last-command this-command)
5290 (eq org-cycle-global-status 'contents))
5291 ;; We just showed the table of contents - now show everything
5292 (run-hook-with-args 'org-pre-cycle-hook 'all)
5293 (show-all)
5294 (message "SHOW ALL")
5295 (setq org-cycle-global-status 'all)
5296 (run-hook-with-args 'org-cycle-hook 'all))
5299 ;; Default action: go to overview
5300 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5301 (org-overview)
5302 (message "OVERVIEW")
5303 (setq org-cycle-global-status 'overview)
5304 (run-hook-with-args 'org-cycle-hook 'overview))))
5306 (defun org-cycle-internal-local ()
5307 "Do the local cycling action."
5308 (org-back-to-heading)
5309 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5310 ;; First, some boundaries
5311 (save-excursion
5312 (org-back-to-heading)
5313 (setq level (funcall outline-level))
5314 (save-excursion
5315 (beginning-of-line 2)
5316 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5317 ; XEmacs does not have `next-single-char-property-change'
5318 ; I'm not sure about Emacs 21.
5319 (while (and (not (eobp)) ;; this is like `next-line'
5320 (get-char-property (1- (point)) 'invisible))
5321 (beginning-of-line 2))
5322 (while (and (not (eobp)) ;; this is like `next-line'
5323 (get-char-property (1- (point)) 'invisible))
5324 (goto-char (next-single-char-property-change (point) 'invisible))
5325 ;;;??? (or (bolp) (beginning-of-line 2))))
5326 (and (eolp) (beginning-of-line 2))))
5327 (setq eol (point)))
5328 (outline-end-of-heading) (setq eoh (point))
5329 (save-excursion
5330 (outline-next-heading)
5331 (setq has-children (and (org-at-heading-p t)
5332 (> (funcall outline-level) level))))
5333 (org-end-of-subtree t)
5334 (unless (eobp)
5335 (skip-chars-forward " \t\n")
5336 (beginning-of-line 1) ; in case this is an item
5338 (setq eos (if (eobp) (point) (1- (point)))))
5339 ;; Find out what to do next and set `this-command'
5340 (cond
5341 ((= eos eoh)
5342 ;; Nothing is hidden behind this heading
5343 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5344 (message "EMPTY ENTRY")
5345 (setq org-cycle-subtree-status nil)
5346 (save-excursion
5347 (goto-char eos)
5348 (outline-next-heading)
5349 (if (org-invisible-p) (org-flag-heading nil))))
5350 ((and (or (>= eol eos)
5351 (not (string-match "\\S-" (buffer-substring eol eos))))
5352 (or has-children
5353 (not (setq children-skipped
5354 org-cycle-skip-children-state-if-no-children))))
5355 ;; Entire subtree is hidden in one line: children view
5356 (run-hook-with-args 'org-pre-cycle-hook 'children)
5357 (org-show-entry)
5358 (show-children)
5359 (message "CHILDREN")
5360 (save-excursion
5361 (goto-char eos)
5362 (outline-next-heading)
5363 (if (org-invisible-p) (org-flag-heading nil)))
5364 (setq org-cycle-subtree-status 'children)
5365 (run-hook-with-args 'org-cycle-hook 'children))
5366 ((or children-skipped
5367 (and (eq last-command this-command)
5368 (eq org-cycle-subtree-status 'children)))
5369 ;; We just showed the children, or no children are there,
5370 ;; now show everything.
5371 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5372 (org-show-subtree)
5373 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5374 (setq org-cycle-subtree-status 'subtree)
5375 (run-hook-with-args 'org-cycle-hook 'subtree))
5377 ;; Default action: hide the subtree.
5378 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5379 (hide-subtree)
5380 (message "FOLDED")
5381 (setq org-cycle-subtree-status 'folded)
5382 (run-hook-with-args 'org-cycle-hook 'folded)))))
5384 ;;;###autoload
5385 (defun org-global-cycle (&optional arg)
5386 "Cycle the global visibility. For details see `org-cycle'.
5387 With C-u prefix arg, switch to startup visibility.
5388 With a numeric prefix, show all headlines up to that level."
5389 (interactive "P")
5390 (let ((org-cycle-include-plain-lists
5391 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5392 (cond
5393 ((integerp arg)
5394 (show-all)
5395 (hide-sublevels arg)
5396 (setq org-cycle-global-status 'contents))
5397 ((equal arg '(4))
5398 (org-set-startup-visibility)
5399 (message "Startup visibility, plus VISIBILITY properties."))
5401 (org-cycle '(4))))))
5403 (defun org-set-startup-visibility ()
5404 "Set the visibility required by startup options and properties."
5405 (cond
5406 ((eq org-startup-folded t)
5407 (org-cycle '(4)))
5408 ((eq org-startup-folded 'content)
5409 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5410 (org-cycle '(4)) (org-cycle '(4)))))
5411 (unless (eq org-startup-folded 'showeverything)
5412 (if org-hide-block-startup (org-hide-block-all))
5413 (org-set-visibility-according-to-property 'no-cleanup)
5414 (org-cycle-hide-archived-subtrees 'all)
5415 (org-cycle-hide-drawers 'all)
5416 (org-cycle-show-empty-lines 'all)))
5418 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5419 "Switch subtree visibilities according to :VISIBILITY: property."
5420 (interactive)
5421 (let (org-show-entry-below state)
5422 (save-excursion
5423 (goto-char (point-min))
5424 (while (re-search-forward
5425 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5426 nil t)
5427 (setq state (match-string 1))
5428 (save-excursion
5429 (org-back-to-heading t)
5430 (hide-subtree)
5431 (org-reveal)
5432 (cond
5433 ((equal state '("fold" "folded"))
5434 (hide-subtree))
5435 ((equal state "children")
5436 (org-show-hidden-entry)
5437 (show-children))
5438 ((equal state "content")
5439 (save-excursion
5440 (save-restriction
5441 (org-narrow-to-subtree)
5442 (org-content))))
5443 ((member state '("all" "showall"))
5444 (show-subtree)))))
5445 (unless no-cleanup
5446 (org-cycle-hide-archived-subtrees 'all)
5447 (org-cycle-hide-drawers 'all)
5448 (org-cycle-show-empty-lines 'all)))))
5450 (defun org-overview ()
5451 "Switch to overview mode, showing only top-level headlines.
5452 Really, this shows all headlines with level equal or greater than the level
5453 of the first headline in the buffer. This is important, because if the
5454 first headline is not level one, then (hide-sublevels 1) gives confusing
5455 results."
5456 (interactive)
5457 (let ((level (save-excursion
5458 (goto-char (point-min))
5459 (if (re-search-forward (concat "^" outline-regexp) nil t)
5460 (progn
5461 (goto-char (match-beginning 0))
5462 (funcall outline-level))))))
5463 (and level (hide-sublevels level))))
5465 (defun org-content (&optional arg)
5466 "Show all headlines in the buffer, like a table of contents.
5467 With numerical argument N, show content up to level N."
5468 (interactive "P")
5469 (save-excursion
5470 ;; Visit all headings and show their offspring
5471 (and (integerp arg) (org-overview))
5472 (goto-char (point-max))
5473 (catch 'exit
5474 (while (and (progn (condition-case nil
5475 (outline-previous-visible-heading 1)
5476 (error (goto-char (point-min))))
5478 (looking-at outline-regexp))
5479 (if (integerp arg)
5480 (show-children (1- arg))
5481 (show-branches))
5482 (if (bobp) (throw 'exit nil))))))
5485 (defun org-optimize-window-after-visibility-change (state)
5486 "Adjust the window after a change in outline visibility.
5487 This function is the default value of the hook `org-cycle-hook'."
5488 (when (get-buffer-window (current-buffer))
5489 (cond
5490 ((eq state 'content) nil)
5491 ((eq state 'all) nil)
5492 ((eq state 'folded) nil)
5493 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5494 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5496 (defun org-remove-empty-overlays-at (pos)
5497 "Remove outline overlays that do not contain non-white stuff."
5498 (mapc
5499 (lambda (o)
5500 (and (eq 'outline (org-overlay-get o 'invisible))
5501 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5502 (org-overlay-end o))))
5503 (org-delete-overlay o)))
5504 (org-overlays-at pos)))
5506 (defun org-clean-visibility-after-subtree-move ()
5507 "Fix visibility issues after moving a subtree."
5508 ;; First, find a reasonable region to look at:
5509 ;; Start two siblings above, end three below
5510 (let* ((beg (save-excursion
5511 (and (org-get-last-sibling)
5512 (org-get-last-sibling))
5513 (point)))
5514 (end (save-excursion
5515 (and (org-get-next-sibling)
5516 (org-get-next-sibling)
5517 (org-get-next-sibling))
5518 (if (org-at-heading-p)
5519 (point-at-eol)
5520 (point))))
5521 (level (looking-at "\\*+"))
5522 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5523 (save-excursion
5524 (save-restriction
5525 (narrow-to-region beg end)
5526 (when re
5527 ;; Properly fold already folded siblings
5528 (goto-char (point-min))
5529 (while (re-search-forward re nil t)
5530 (if (and (not (org-invisible-p))
5531 (save-excursion
5532 (goto-char (point-at-eol)) (org-invisible-p)))
5533 (hide-entry))))
5534 (org-cycle-show-empty-lines 'overview)
5535 (org-cycle-hide-drawers 'overview)))))
5537 (defun org-cycle-show-empty-lines (state)
5538 "Show empty lines above all visible headlines.
5539 The region to be covered depends on STATE when called through
5540 `org-cycle-hook'. Lisp program can use t for STATE to get the
5541 entire buffer covered. Note that an empty line is only shown if there
5542 are at least `org-cycle-separator-lines' empty lines before the headline."
5543 (when (not (= org-cycle-separator-lines 0))
5544 (save-excursion
5545 (let* ((n (abs org-cycle-separator-lines))
5546 (re (cond
5547 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5548 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5549 (t (let ((ns (number-to-string (- n 2))))
5550 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5551 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5552 beg end b e)
5553 (cond
5554 ((memq state '(overview contents t))
5555 (setq beg (point-min) end (point-max)))
5556 ((memq state '(children folded))
5557 (setq beg (point) end (progn (org-end-of-subtree t t)
5558 (beginning-of-line 2)
5559 (point)))))
5560 (when beg
5561 (goto-char beg)
5562 (while (re-search-forward re end t)
5563 (unless (get-char-property (match-end 1) 'invisible)
5564 (setq e (match-end 1))
5565 (if (< org-cycle-separator-lines 0)
5566 (setq b (save-excursion
5567 (goto-char (match-beginning 0))
5568 (org-back-over-empty-lines)
5569 (if (save-excursion
5570 (goto-char (max (point-min) (1- (point))))
5571 (org-on-heading-p))
5572 (1- (point))
5573 (point))))
5574 (setq b (match-beginning 1)))
5575 (outline-flag-region b e nil)))))))
5576 ;; Never hide empty lines at the end of the file.
5577 (save-excursion
5578 (goto-char (point-max))
5579 (outline-previous-heading)
5580 (outline-end-of-heading)
5581 (if (and (looking-at "[ \t\n]+")
5582 (= (match-end 0) (point-max)))
5583 (outline-flag-region (point) (match-end 0) nil))))
5585 (defun org-show-empty-lines-in-parent ()
5586 "Move to the parent and re-show empty lines before visible headlines."
5587 (save-excursion
5588 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5589 (org-cycle-show-empty-lines context))))
5591 (defun org-files-list ()
5592 "Return `org-agenda-files' list, plus all open org-mode files.
5593 This is useful for operations that need to scan all of a user's
5594 open and agenda-wise Org files."
5595 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5596 (dolist (buf (buffer-list))
5597 (with-current-buffer buf
5598 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5599 (let ((file (expand-file-name (buffer-file-name))))
5600 (unless (member file files)
5601 (push file files))))))
5602 files))
5604 (defsubst org-entry-beginning-position ()
5605 "Return the beginning position of the current entry."
5606 (save-excursion (outline-back-to-heading t) (point)))
5608 (defsubst org-entry-end-position ()
5609 "Return the end position of the current entry."
5610 (save-excursion (outline-next-heading) (point)))
5612 (defun org-cycle-hide-drawers (state)
5613 "Re-hide all drawers after a visibility state change."
5614 (when (and (org-mode-p)
5615 (not (memq state '(overview folded contents))))
5616 (save-excursion
5617 (let* ((globalp (memq state '(contents all)))
5618 (beg (if globalp (point-min) (point)))
5619 (end (if globalp (point-max)
5620 (if (eq state 'children)
5621 (save-excursion (outline-next-heading) (point))
5622 (org-end-of-subtree t)))))
5623 (goto-char beg)
5624 (while (re-search-forward org-drawer-regexp end t)
5625 (org-flag-drawer t))))))
5627 (defun org-flag-drawer (flag)
5628 (save-excursion
5629 (beginning-of-line 1)
5630 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5631 (let ((b (match-end 0))
5632 (outline-regexp org-outline-regexp))
5633 (if (re-search-forward
5634 "^[ \t]*:END:"
5635 (save-excursion (outline-next-heading) (point)) t)
5636 (outline-flag-region b (point-at-eol) flag)
5637 (error ":END: line missing at position %s" b))))))
5639 (defun org-subtree-end-visible-p ()
5640 "Is the end of the current subtree visible?"
5641 (pos-visible-in-window-p
5642 (save-excursion (org-end-of-subtree t) (point))))
5644 (defun org-first-headline-recenter (&optional N)
5645 "Move cursor to the first headline and recenter the headline.
5646 Optional argument N means, put the headline into the Nth line of the window."
5647 (goto-char (point-min))
5648 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5649 (beginning-of-line)
5650 (recenter (prefix-numeric-value N))))
5652 ;;; Saving and restoring visibility
5654 (defun org-outline-overlay-data (&optional use-markers)
5655 "Return a list of the locations of all outline overlays.
5656 The are overlays with the `invisible' property value `outline'.
5657 The return valus is a list of cons cells, with start and stop
5658 positions for each overlay.
5659 If USE-MARKERS is set, return the positions as markers."
5660 (let (beg end)
5661 (save-excursion
5662 (save-restriction
5663 (widen)
5664 (delq nil
5665 (mapcar (lambda (o)
5666 (when (eq (org-overlay-get o 'invisible) 'outline)
5667 (setq beg (org-overlay-start o)
5668 end (org-overlay-end o))
5669 (and beg end (> end beg)
5670 (if use-markers
5671 (cons (move-marker (make-marker) beg)
5672 (move-marker (make-marker) end))
5673 (cons beg end)))))
5674 (org-overlays-in (point-min) (point-max))))))))
5676 (defun org-set-outline-overlay-data (data)
5677 "Create visibility overlays for all positions in DATA.
5678 DATA should have been made by `org-outline-overlay-data'."
5679 (let (o)
5680 (save-excursion
5681 (save-restriction
5682 (widen)
5683 (show-all)
5684 (mapc (lambda (c)
5685 (setq o (org-make-overlay (car c) (cdr c)))
5686 (org-overlay-put o 'invisible 'outline))
5687 data)))))
5689 (defmacro org-save-outline-visibility (use-markers &rest body)
5690 "Save and restore outline visibility around BODY.
5691 If USE-MARKERS is non-nil, use markers for the positions.
5692 This means that the buffer may change while running BODY,
5693 but it also means that the buffer should stay alive
5694 during the operation, because otherwise all these markers will
5695 point nowhere."
5696 `(let ((data (org-outline-overlay-data ,use-markers)))
5697 (unwind-protect
5698 (progn
5699 ,@body
5700 (org-set-outline-overlay-data data))
5701 (when ,use-markers
5702 (mapc (lambda (c)
5703 (and (markerp (car c)) (move-marker (car c) nil))
5704 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5705 data)))))
5708 ;;; Folding of blocks
5710 (defconst org-block-regexp
5712 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5713 "Regular expression for hiding blocks.")
5715 (defvar org-hide-block-overlays nil
5716 "Overlays hiding blocks.")
5717 (make-variable-buffer-local 'org-hide-block-overlays)
5719 (defun org-block-map (function &optional start end)
5720 "Call func at the head of all source blocks in the current
5721 buffer. Optional arguments START and END can be used to limit
5722 the range."
5723 (let ((start (or start (point-min)))
5724 (end (or end (point-max))))
5725 (save-excursion
5726 (goto-char start)
5727 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5728 (save-excursion
5729 (save-match-data
5730 (goto-char (match-beginning 0))
5731 (funcall function)))))))
5733 (defun org-hide-block-toggle-all ()
5734 "Toggle the visibility of all blocks in the current buffer."
5735 (org-block-map #'org-hide-block-toggle))
5737 (defun org-hide-block-all ()
5738 "Fold all blocks in the current buffer."
5739 (interactive)
5740 (org-show-block-all)
5741 (org-block-map #'org-hide-block-toggle-maybe))
5743 (defun org-show-block-all ()
5744 "Unfold all blocks in the current buffer."
5745 (mapc 'org-delete-overlay org-hide-block-overlays)
5746 (setq org-hide-block-overlays nil))
5748 (defun org-hide-block-toggle-maybe ()
5749 "Toggle visibility of block at point."
5750 (interactive)
5751 (let ((case-fold-search t))
5752 (if (save-excursion
5753 (beginning-of-line 1)
5754 (looking-at org-block-regexp))
5755 (progn (org-hide-block-toggle)
5756 t) ;; to signal that we took action
5757 nil))) ;; to signal that we did not
5759 (defun org-hide-block-toggle (&optional force)
5760 "Toggle the visibility of the current block."
5761 (interactive)
5762 (save-excursion
5763 (beginning-of-line)
5764 (if (re-search-forward org-block-regexp nil t)
5765 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5766 (end (match-end 0)) ;; end of entire body
5768 (if (memq t (mapcar (lambda (overlay)
5769 (eq (org-overlay-get overlay 'invisible)
5770 'org-hide-block))
5771 (org-overlays-at start)))
5772 (if (or (not force) (eq force 'off))
5773 (mapc (lambda (ov)
5774 (when (member ov org-hide-block-overlays)
5775 (setq org-hide-block-overlays
5776 (delq ov org-hide-block-overlays)))
5777 (when (eq (org-overlay-get ov 'invisible)
5778 'org-hide-block)
5779 (org-delete-overlay ov)))
5780 (org-overlays-at start)))
5781 (setq ov (org-make-overlay start end))
5782 (org-overlay-put ov 'invisible 'org-hide-block)
5783 ;; make the block accessible to isearch
5784 (org-overlay-put
5785 ov 'isearch-open-invisible
5786 (lambda (ov)
5787 (when (member ov org-hide-block-overlays)
5788 (setq org-hide-block-overlays
5789 (delq ov org-hide-block-overlays)))
5790 (when (eq (org-overlay-get ov 'invisible)
5791 'org-hide-block)
5792 (org-delete-overlay ov))))
5793 (push ov org-hide-block-overlays)))
5794 (error "Not looking at a source block"))))
5796 ;; org-tab-after-check-for-cycling-hook
5797 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5798 ;; Remove overlays when changing major mode
5799 (add-hook 'org-mode-hook
5800 (lambda () (org-add-hook 'change-major-mode-hook
5801 'org-show-block-all 'append 'local)))
5803 ;;; Org-goto
5805 (defvar org-goto-window-configuration nil)
5806 (defvar org-goto-marker nil)
5807 (defvar org-goto-map
5808 (let ((map (make-sparse-keymap)))
5809 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5810 (while (setq cmd (pop cmds))
5811 (substitute-key-definition cmd cmd map global-map)))
5812 (suppress-keymap map)
5813 (org-defkey map "\C-m" 'org-goto-ret)
5814 (org-defkey map [(return)] 'org-goto-ret)
5815 (org-defkey map [(left)] 'org-goto-left)
5816 (org-defkey map [(right)] 'org-goto-right)
5817 (org-defkey map [(control ?g)] 'org-goto-quit)
5818 (org-defkey map "\C-i" 'org-cycle)
5819 (org-defkey map [(tab)] 'org-cycle)
5820 (org-defkey map [(down)] 'outline-next-visible-heading)
5821 (org-defkey map [(up)] 'outline-previous-visible-heading)
5822 (if org-goto-auto-isearch
5823 (if (fboundp 'define-key-after)
5824 (define-key-after map [t] 'org-goto-local-auto-isearch)
5825 nil)
5826 (org-defkey map "q" 'org-goto-quit)
5827 (org-defkey map "n" 'outline-next-visible-heading)
5828 (org-defkey map "p" 'outline-previous-visible-heading)
5829 (org-defkey map "f" 'outline-forward-same-level)
5830 (org-defkey map "b" 'outline-backward-same-level)
5831 (org-defkey map "u" 'outline-up-heading))
5832 (org-defkey map "/" 'org-occur)
5833 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5834 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5835 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5836 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5837 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5838 map))
5840 (defconst org-goto-help
5841 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5842 RET=jump to location [Q]uit and return to previous location
5843 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5845 (defvar org-goto-start-pos) ; dynamically scoped parameter
5847 ;; FIXME: Docstring does not mention both interfaces
5848 (defun org-goto (&optional alternative-interface)
5849 "Look up a different location in the current file, keeping current visibility.
5851 When you want look-up or go to a different location in a document, the
5852 fastest way is often to fold the entire buffer and then dive into the tree.
5853 This method has the disadvantage, that the previous location will be folded,
5854 which may not be what you want.
5856 This command works around this by showing a copy of the current buffer
5857 in an indirect buffer, in overview mode. You can dive into the tree in
5858 that copy, use org-occur and incremental search to find a location.
5859 When pressing RET or `Q', the command returns to the original buffer in
5860 which the visibility is still unchanged. After RET is will also jump to
5861 the location selected in the indirect buffer and expose the
5862 the headline hierarchy above."
5863 (interactive "P")
5864 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5865 (org-refile-use-outline-path t)
5866 (org-refile-target-verify-function nil)
5867 (interface
5868 (if (not alternative-interface)
5869 org-goto-interface
5870 (if (eq org-goto-interface 'outline)
5871 'outline-path-completion
5872 'outline)))
5873 (org-goto-start-pos (point))
5874 (selected-point
5875 (if (eq interface 'outline)
5876 (car (org-get-location (current-buffer) org-goto-help))
5877 (nth 3 (org-refile-get-location "Goto: ")))))
5878 (if selected-point
5879 (progn
5880 (org-mark-ring-push org-goto-start-pos)
5881 (goto-char selected-point)
5882 (if (or (org-invisible-p) (org-invisible-p2))
5883 (org-show-context 'org-goto)))
5884 (message "Quit"))))
5886 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5887 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5888 (defvar org-goto-local-auto-isearch-map) ; defined below
5890 (defun org-get-location (buf help)
5891 "Let the user select a location in the Org-mode buffer BUF.
5892 This function uses a recursive edit. It returns the selected position
5893 or nil."
5894 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5895 (isearch-hide-immediately nil)
5896 (isearch-search-fun-function
5897 (lambda () 'org-goto-local-search-headings))
5898 (org-goto-selected-point org-goto-exit-command))
5899 (save-excursion
5900 (save-window-excursion
5901 (delete-other-windows)
5902 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5903 (switch-to-buffer
5904 (condition-case nil
5905 (make-indirect-buffer (current-buffer) "*org-goto*")
5906 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5907 (with-output-to-temp-buffer "*Help*"
5908 (princ help))
5909 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5910 (setq buffer-read-only nil)
5911 (let ((org-startup-truncated t)
5912 (org-startup-folded nil)
5913 (org-startup-align-all-tables nil))
5914 (org-mode)
5915 (org-overview))
5916 (setq buffer-read-only t)
5917 (if (and (boundp 'org-goto-start-pos)
5918 (integer-or-marker-p org-goto-start-pos))
5919 (let ((org-show-hierarchy-above t)
5920 (org-show-siblings t)
5921 (org-show-following-heading t))
5922 (goto-char org-goto-start-pos)
5923 (and (org-invisible-p) (org-show-context)))
5924 (goto-char (point-min)))
5925 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5926 (message "Select location and press RET")
5927 (use-local-map org-goto-map)
5928 (recursive-edit)
5930 (kill-buffer "*org-goto*")
5931 (cons org-goto-selected-point org-goto-exit-command)))
5933 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5934 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5935 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5936 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5938 (defun org-goto-local-search-headings (string bound noerror)
5939 "Search and make sure that any matches are in headlines."
5940 (catch 'return
5941 (while (if isearch-forward
5942 (search-forward string bound noerror)
5943 (search-backward string bound noerror))
5944 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5945 (and (member :headline context)
5946 (not (member :tags context))))
5947 (throw 'return (point))))))
5949 (defun org-goto-local-auto-isearch ()
5950 "Start isearch."
5951 (interactive)
5952 (goto-char (point-min))
5953 (let ((keys (this-command-keys)))
5954 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5955 (isearch-mode t)
5956 (isearch-process-search-char (string-to-char keys)))))
5958 (defun org-goto-ret (&optional arg)
5959 "Finish `org-goto' by going to the new location."
5960 (interactive "P")
5961 (setq org-goto-selected-point (point)
5962 org-goto-exit-command 'return)
5963 (throw 'exit nil))
5965 (defun org-goto-left ()
5966 "Finish `org-goto' by going to the new location."
5967 (interactive)
5968 (if (org-on-heading-p)
5969 (progn
5970 (beginning-of-line 1)
5971 (setq org-goto-selected-point (point)
5972 org-goto-exit-command 'left)
5973 (throw 'exit nil))
5974 (error "Not on a heading")))
5976 (defun org-goto-right ()
5977 "Finish `org-goto' by going to the new location."
5978 (interactive)
5979 (if (org-on-heading-p)
5980 (progn
5981 (setq org-goto-selected-point (point)
5982 org-goto-exit-command 'right)
5983 (throw 'exit nil))
5984 (error "Not on a heading")))
5986 (defun org-goto-quit ()
5987 "Finish `org-goto' without cursor motion."
5988 (interactive)
5989 (setq org-goto-selected-point nil)
5990 (setq org-goto-exit-command 'quit)
5991 (throw 'exit nil))
5993 ;;; Indirect buffer display of subtrees
5995 (defvar org-indirect-dedicated-frame nil
5996 "This is the frame being used for indirect tree display.")
5997 (defvar org-last-indirect-buffer nil)
5999 (defun org-tree-to-indirect-buffer (&optional arg)
6000 "Create indirect buffer and narrow it to current subtree.
6001 With numerical prefix ARG, go up to this level and then take that tree.
6002 If ARG is negative, go up that many levels.
6003 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6004 indirect buffer previously made with this command, to avoid proliferation of
6005 indirect buffers. However, when you call the command with a `C-u' prefix, or
6006 when `org-indirect-buffer-display' is `new-frame', the last buffer
6007 is kept so that you can work with several indirect buffers at the same time.
6008 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6009 requests that a new frame be made for the new buffer, so that the dedicated
6010 frame is not changed."
6011 (interactive "P")
6012 (let ((cbuf (current-buffer))
6013 (cwin (selected-window))
6014 (pos (point))
6015 beg end level heading ibuf)
6016 (save-excursion
6017 (org-back-to-heading t)
6018 (when (numberp arg)
6019 (setq level (org-outline-level))
6020 (if (< arg 0) (setq arg (+ level arg)))
6021 (while (> (setq level (org-outline-level)) arg)
6022 (outline-up-heading 1 t)))
6023 (setq beg (point)
6024 heading (org-get-heading))
6025 (org-end-of-subtree t t) (setq end (point)))
6026 (if (and (buffer-live-p org-last-indirect-buffer)
6027 (not (eq org-indirect-buffer-display 'new-frame))
6028 (not arg))
6029 (kill-buffer org-last-indirect-buffer))
6030 (setq ibuf (org-get-indirect-buffer cbuf)
6031 org-last-indirect-buffer ibuf)
6032 (cond
6033 ((or (eq org-indirect-buffer-display 'new-frame)
6034 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6035 (select-frame (make-frame))
6036 (delete-other-windows)
6037 (switch-to-buffer ibuf)
6038 (org-set-frame-title heading))
6039 ((eq org-indirect-buffer-display 'dedicated-frame)
6040 (raise-frame
6041 (select-frame (or (and org-indirect-dedicated-frame
6042 (frame-live-p org-indirect-dedicated-frame)
6043 org-indirect-dedicated-frame)
6044 (setq org-indirect-dedicated-frame (make-frame)))))
6045 (delete-other-windows)
6046 (switch-to-buffer ibuf)
6047 (org-set-frame-title (concat "Indirect: " heading)))
6048 ((eq org-indirect-buffer-display 'current-window)
6049 (switch-to-buffer ibuf))
6050 ((eq org-indirect-buffer-display 'other-window)
6051 (pop-to-buffer ibuf))
6052 (t (error "Invalid value")))
6053 (if (featurep 'xemacs)
6054 (save-excursion (org-mode) (turn-on-font-lock)))
6055 (narrow-to-region beg end)
6056 (show-all)
6057 (goto-char pos)
6058 (and (window-live-p cwin) (select-window cwin))))
6060 (defun org-get-indirect-buffer (&optional buffer)
6061 (setq buffer (or buffer (current-buffer)))
6062 (let ((n 1) (base (buffer-name buffer)) bname)
6063 (while (buffer-live-p
6064 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6065 (setq n (1+ n)))
6066 (condition-case nil
6067 (make-indirect-buffer buffer bname 'clone)
6068 (error (make-indirect-buffer buffer bname)))))
6070 (defun org-set-frame-title (title)
6071 "Set the title of the current frame to the string TITLE."
6072 ;; FIXME: how to name a single frame in XEmacs???
6073 (unless (featurep 'xemacs)
6074 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6076 ;;;; Structure editing
6078 ;;; Inserting headlines
6080 (defun org-previous-line-empty-p ()
6081 (save-excursion
6082 (and (not (bobp))
6083 (or (beginning-of-line 0) t)
6084 (save-match-data
6085 (looking-at "[ \t]*$")))))
6087 (defun org-insert-heading (&optional force-heading)
6088 "Insert a new heading or item with same depth at point.
6089 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6090 If point is at the beginning of a headline, insert a sibling before the
6091 current headline. If point is not at the beginning, do not split the line,
6092 but create the new headline after the current line."
6093 (interactive "P")
6094 (if (or (= (buffer-size) 0)
6095 (and (not (save-excursion (and (ignore-errors (org-back-to-heading))
6096 (org-on-heading-p))))
6097 (not (org-in-item-p))))
6098 (insert "\n* ")
6099 (when (or force-heading (not (org-insert-item)))
6100 (let* ((empty-line-p nil)
6101 (head (save-excursion
6102 (condition-case nil
6103 (progn
6104 (org-back-to-heading)
6105 (setq empty-line-p (org-previous-line-empty-p))
6106 (match-string 0))
6107 (error "*"))))
6108 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6109 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6110 pos hide-previous previous-pos)
6111 (cond
6112 ((and (org-on-heading-p) (bolp)
6113 (or (bobp)
6114 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6115 ;; insert before the current line
6116 (open-line (if blank 2 1)))
6117 ((and (bolp)
6118 (not org-insert-heading-respect-content)
6119 (or (bobp)
6120 (save-excursion
6121 (backward-char 1) (not (org-invisible-p)))))
6122 ;; insert right here
6123 nil)
6125 ;; somewhere in the line
6126 (save-excursion
6127 (setq previous-pos (point-at-bol))
6128 (end-of-line)
6129 (setq hide-previous (org-invisible-p)))
6130 (and org-insert-heading-respect-content (org-show-subtree))
6131 (let ((split
6132 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6133 (save-excursion
6134 (let ((p (point)))
6135 (goto-char (point-at-bol))
6136 (and (looking-at org-complex-heading-regexp)
6137 (> p (match-beginning 4)))))))
6138 tags pos)
6139 (cond
6140 (org-insert-heading-respect-content
6141 (org-end-of-subtree nil t)
6142 (or (bolp) (newline))
6143 (or (org-previous-line-empty-p)
6144 (and blank (newline)))
6145 (open-line 1))
6146 ((org-on-heading-p)
6147 (when hide-previous
6148 (show-children)
6149 (org-show-entry))
6150 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6151 (setq tags (and (match-end 2) (match-string 2)))
6152 (and (match-end 1)
6153 (delete-region (match-beginning 1) (match-end 1)))
6154 (setq pos (point-at-bol))
6155 (or split (end-of-line 1))
6156 (delete-horizontal-space)
6157 (newline (if blank 2 1))
6158 (when tags
6159 (save-excursion
6160 (goto-char pos)
6161 (end-of-line 1)
6162 (insert " " tags)
6163 (org-set-tags nil 'align))))
6165 (or split (end-of-line 1))
6166 (newline (if blank 2 1)))))))
6167 (insert head) (just-one-space)
6168 (setq pos (point))
6169 (end-of-line 1)
6170 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6171 (when (and org-insert-heading-respect-content hide-previous)
6172 (save-excursion
6173 (goto-char previous-pos)
6174 (hide-subtree)))
6175 (run-hooks 'org-insert-heading-hook)))))
6177 (defun org-get-heading (&optional no-tags)
6178 "Return the heading of the current entry, without the stars."
6179 (save-excursion
6180 (org-back-to-heading t)
6181 (if (looking-at
6182 (if no-tags
6183 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6184 "\\*+[ \t]+\\([^\r\n]*\\)"))
6185 (match-string 1) "")))
6187 (defun org-heading-components ()
6188 "Return the components of the current heading.
6189 This is a list with the following elements:
6190 - the level as an integer
6191 - the reduced level, different if `org-odd-levels-only' is set.
6192 - the TODO keyword, or nil
6193 - the priority character, like ?A, or nil if no priority is given
6194 - the headline text itself, or the tags string if no headline text
6195 - the tags string, or nil."
6196 (save-excursion
6197 (org-back-to-heading t)
6198 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6199 (list (length (match-string 1))
6200 (org-reduced-level (length (match-string 1)))
6201 (org-match-string-no-properties 2)
6202 (and (match-end 3) (aref (match-string 3) 2))
6203 (org-match-string-no-properties 4)
6204 (org-match-string-no-properties 5)))))
6206 (defun org-get-entry ()
6207 "Get the entry text, after heading, entire subtree."
6208 (save-excursion
6209 (org-back-to-heading t)
6210 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6212 (defun org-insert-heading-after-current ()
6213 "Insert a new heading with same level as current, after current subtree."
6214 (interactive)
6215 (org-back-to-heading)
6216 (org-insert-heading)
6217 (org-move-subtree-down)
6218 (end-of-line 1))
6220 (defun org-insert-heading-respect-content ()
6221 (interactive)
6222 (let ((org-insert-heading-respect-content t))
6223 (org-insert-heading t)))
6225 (defun org-insert-todo-heading-respect-content (&optional force-state)
6226 (interactive "P")
6227 (let ((org-insert-heading-respect-content t))
6228 (org-insert-todo-heading force-state t)))
6230 (defun org-insert-todo-heading (arg &optional force-heading)
6231 "Insert a new heading with the same level and TODO state as current heading.
6232 If the heading has no TODO state, or if the state is DONE, use the first
6233 state (TODO by default). Also with prefix arg, force first state."
6234 (interactive "P")
6235 (when (or force-heading (not (org-insert-item 'checkbox)))
6236 (org-insert-heading force-heading)
6237 (save-excursion
6238 (org-back-to-heading)
6239 (outline-previous-heading)
6240 (looking-at org-todo-line-regexp))
6241 (let*
6242 ((new-mark-x
6243 (if (or arg
6244 (not (match-beginning 2))
6245 (member (match-string 2) org-done-keywords))
6246 (car org-todo-keywords-1)
6247 (match-string 2)))
6248 (new-mark
6250 (run-hook-with-args-until-success
6251 'org-todo-get-default-hook new-mark-x nil)
6252 new-mark-x)))
6253 (beginning-of-line 1)
6254 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6255 (if org-treat-insert-todo-heading-as-state-change
6256 (org-todo new-mark)
6257 (insert new-mark " "))))
6258 (when org-provide-todo-statistics
6259 (org-update-parent-todo-statistics))))
6261 (defun org-insert-subheading (arg)
6262 "Insert a new subheading and demote it.
6263 Works for outline headings and for plain lists alike."
6264 (interactive "P")
6265 (org-insert-heading arg)
6266 (cond
6267 ((org-on-heading-p) (org-do-demote))
6268 ((org-at-item-p) (org-indent-item 1))))
6270 (defun org-insert-todo-subheading (arg)
6271 "Insert a new subheading with TODO keyword or checkbox and demote it.
6272 Works for outline headings and for plain lists alike."
6273 (interactive "P")
6274 (org-insert-todo-heading arg)
6275 (cond
6276 ((org-on-heading-p) (org-do-demote))
6277 ((org-at-item-p) (org-indent-item 1))))
6279 ;;; Promotion and Demotion
6281 (defvar org-after-demote-entry-hook nil
6282 "Hook run after an entry has been demoted.
6283 The cursor will be at the beginning of the entry.
6284 When a subtree is being demoted, the hook will be called for each node.")
6286 (defvar org-after-promote-entry-hook nil
6287 "Hook run after an entry has been promoted.
6288 The cursor will be at the beginning of the entry.
6289 When a subtree is being promoted, the hook will be called for each node.")
6291 (defun org-promote-subtree ()
6292 "Promote the entire subtree.
6293 See also `org-promote'."
6294 (interactive)
6295 (save-excursion
6296 (org-map-tree 'org-promote))
6297 (org-fix-position-after-promote))
6299 (defun org-demote-subtree ()
6300 "Demote the entire subtree. See `org-demote'.
6301 See also `org-promote'."
6302 (interactive)
6303 (save-excursion
6304 (org-map-tree 'org-demote))
6305 (org-fix-position-after-promote))
6308 (defun org-do-promote ()
6309 "Promote the current heading higher up the tree.
6310 If the region is active in `transient-mark-mode', promote all headings
6311 in the region."
6312 (interactive)
6313 (save-excursion
6314 (if (org-region-active-p)
6315 (org-map-region 'org-promote (region-beginning) (region-end))
6316 (org-promote)))
6317 (org-fix-position-after-promote))
6319 (defun org-do-demote ()
6320 "Demote the current heading lower down the tree.
6321 If the region is active in `transient-mark-mode', demote all headings
6322 in the region."
6323 (interactive)
6324 (save-excursion
6325 (if (org-region-active-p)
6326 (org-map-region 'org-demote (region-beginning) (region-end))
6327 (org-demote)))
6328 (org-fix-position-after-promote))
6330 (defun org-fix-position-after-promote ()
6331 "Make sure that after pro/demotion cursor position is right."
6332 (let ((pos (point)))
6333 (when (save-excursion
6334 (beginning-of-line 1)
6335 (looking-at org-todo-line-regexp)
6336 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6337 (cond ((eobp) (insert " "))
6338 ((eolp) (insert " "))
6339 ((equal (char-after) ?\ ) (forward-char 1))))))
6341 (defun org-current-level ()
6342 "Return the level of the current entry, or nil if before the first headline.
6343 The level is the number of stars at the beginning of the headline."
6344 (save-excursion
6345 (condition-case nil
6346 (progn
6347 (org-back-to-heading t)
6348 (funcall outline-level))
6349 (error nil))))
6351 (defun org-reduced-level (l)
6352 "Compute the effective level of a heading.
6353 This takes into account the setting of `org-odd-levels-only'."
6354 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6356 (defun org-get-valid-level (level &optional change)
6357 "Rectify a level change under the influence of `org-odd-levels-only'
6358 LEVEL is a current level, CHANGE is by how much the level should be
6359 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6360 even level numbers will become the next higher odd number."
6361 (if org-odd-levels-only
6362 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6363 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6364 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6365 (max 1 (+ level (or change 0)))))
6367 (if (boundp 'define-obsolete-function-alias)
6368 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6369 (define-obsolete-function-alias 'org-get-legal-level
6370 'org-get-valid-level)
6371 (define-obsolete-function-alias 'org-get-legal-level
6372 'org-get-valid-level "23.1")))
6374 (defun org-promote ()
6375 "Promote the current heading higher up the tree.
6376 If the region is active in `transient-mark-mode', promote all headings
6377 in the region."
6378 (org-back-to-heading t)
6379 (let* ((level (save-match-data (funcall outline-level)))
6380 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6381 (diff (abs (- level (length up-head) -1))))
6382 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6383 (replace-match up-head nil t)
6384 ;; Fixup tag positioning
6385 (and org-auto-align-tags (org-set-tags nil t))
6386 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6387 (run-hooks 'org-after-promote-entry-hook)))
6389 (defun org-demote ()
6390 "Demote the current heading lower down the tree.
6391 If the region is active in `transient-mark-mode', demote all headings
6392 in the region."
6393 (org-back-to-heading t)
6394 (let* ((level (save-match-data (funcall outline-level)))
6395 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6396 (diff (abs (- level (length down-head) -1))))
6397 (replace-match down-head nil t)
6398 ;; Fixup tag positioning
6399 (and org-auto-align-tags (org-set-tags nil t))
6400 (if org-adapt-indentation (org-fixup-indentation diff))
6401 (run-hooks 'org-after-demote-entry-hook)))
6403 (defvar org-tab-ind-state nil)
6405 (defun org-cycle-level ()
6406 (let ((org-adapt-indentation nil))
6407 (when (and (looking-at "[ \t]*$")
6408 (org-looking-back
6409 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6410 (setq this-command 'org-cycle-level)
6411 (if (eq last-command 'org-cycle-level)
6412 (condition-case nil
6413 (progn (org-do-promote)
6414 (if (equal org-tab-ind-state (org-current-level))
6415 (org-do-promote)))
6416 (error
6417 (progn
6418 (save-excursion
6419 (beginning-of-line 1)
6420 (and (looking-at "\\*+")
6421 (replace-match
6422 (make-string org-tab-ind-state ?*))))
6423 (setq this-command 'org-cycle))))
6424 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6425 (org-do-demote))
6426 t)))
6428 (defun org-map-tree (fun)
6429 "Call FUN for every heading underneath the current one."
6430 (org-back-to-heading)
6431 (let ((level (funcall outline-level)))
6432 (save-excursion
6433 (funcall fun)
6434 (while (and (progn
6435 (outline-next-heading)
6436 (> (funcall outline-level) level))
6437 (not (eobp)))
6438 (funcall fun)))))
6440 (defun org-map-region (fun beg end)
6441 "Call FUN for every heading between BEG and END."
6442 (let ((org-ignore-region t))
6443 (save-excursion
6444 (setq end (copy-marker end))
6445 (goto-char beg)
6446 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6447 (< (point) end))
6448 (funcall fun))
6449 (while (and (progn
6450 (outline-next-heading)
6451 (< (point) end))
6452 (not (eobp)))
6453 (funcall fun)))))
6455 (defun org-fixup-indentation (diff)
6456 "Change the indentation in the current entry by DIFF
6457 However, if any line in the current entry has no indentation, or if it
6458 would end up with no indentation after the change, nothing at all is done."
6459 (save-excursion
6460 (let ((end (save-excursion (outline-next-heading)
6461 (point-marker)))
6462 (prohibit (if (> diff 0)
6463 "^\\S-"
6464 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6465 col)
6466 (unless (save-excursion (end-of-line 1)
6467 (re-search-forward prohibit end t))
6468 (while (and (< (point) end)
6469 (re-search-forward "^[ \t]+" end t))
6470 (goto-char (match-end 0))
6471 (setq col (current-column))
6472 (if (< diff 0) (replace-match ""))
6473 (org-indent-to-column (+ diff col))))
6474 (move-marker end nil))))
6476 (defun org-convert-to-odd-levels ()
6477 "Convert an org-mode file with all levels allowed to one with odd levels.
6478 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6479 level 5 etc."
6480 (interactive)
6481 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6482 (let ((outline-regexp org-outline-regexp)
6483 (outline-level 'org-outline-level)
6484 (org-odd-levels-only nil) n)
6485 (save-excursion
6486 (goto-char (point-min))
6487 (while (re-search-forward "^\\*\\*+ " nil t)
6488 (setq n (- (length (match-string 0)) 2))
6489 (while (>= (setq n (1- n)) 0)
6490 (org-demote))
6491 (end-of-line 1))))))
6493 (defun org-convert-to-oddeven-levels ()
6494 "Convert an org-mode file with only odd levels to one with odd and even levels.
6495 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6496 section with an even level, conversion would destroy the structure of the file. An error
6497 is signaled in this case."
6498 (interactive)
6499 (goto-char (point-min))
6500 ;; First check if there are no even levels
6501 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6502 (org-show-context t)
6503 (error "Not all levels are odd in this file. Conversion not possible"))
6504 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6505 (let ((outline-regexp org-outline-regexp)
6506 (outline-level 'org-outline-level)
6507 (org-odd-levels-only nil) n)
6508 (save-excursion
6509 (goto-char (point-min))
6510 (while (re-search-forward "^\\*\\*+ " nil t)
6511 (setq n (/ (1- (length (match-string 0))) 2))
6512 (while (>= (setq n (1- n)) 0)
6513 (org-promote))
6514 (end-of-line 1))))))
6516 (defun org-tr-level (n)
6517 "Make N odd if required."
6518 (if org-odd-levels-only (1+ (/ n 2)) n))
6520 ;;; Vertical tree motion, cutting and pasting of subtrees
6522 (defun org-move-subtree-up (&optional arg)
6523 "Move the current subtree up past ARG headlines of the same level."
6524 (interactive "p")
6525 (org-move-subtree-down (- (prefix-numeric-value arg))))
6527 (defun org-move-subtree-down (&optional arg)
6528 "Move the current subtree down past ARG headlines of the same level."
6529 (interactive "p")
6530 (setq arg (prefix-numeric-value arg))
6531 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6532 'org-get-last-sibling))
6533 (ins-point (make-marker))
6534 (cnt (abs arg))
6535 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6536 ;; Select the tree
6537 (org-back-to-heading)
6538 (setq beg0 (point))
6539 (save-excursion
6540 (setq ne-beg (org-back-over-empty-lines))
6541 (setq beg (point)))
6542 (save-match-data
6543 (save-excursion (outline-end-of-heading)
6544 (setq folded (org-invisible-p)))
6545 (outline-end-of-subtree))
6546 (outline-next-heading)
6547 (setq ne-end (org-back-over-empty-lines))
6548 (setq end (point))
6549 (goto-char beg0)
6550 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6551 ;; include less whitespace
6552 (save-excursion
6553 (goto-char beg)
6554 (forward-line (- ne-beg ne-end))
6555 (setq beg (point))))
6556 ;; Find insertion point, with error handling
6557 (while (> cnt 0)
6558 (or (and (funcall movfunc) (looking-at outline-regexp))
6559 (progn (goto-char beg0)
6560 (error "Cannot move past superior level or buffer limit")))
6561 (setq cnt (1- cnt)))
6562 (if (> arg 0)
6563 ;; Moving forward - still need to move over subtree
6564 (progn (org-end-of-subtree t t)
6565 (save-excursion
6566 (org-back-over-empty-lines)
6567 (or (bolp) (newline)))))
6568 (setq ne-ins (org-back-over-empty-lines))
6569 (move-marker ins-point (point))
6570 (setq txt (buffer-substring beg end))
6571 (org-save-markers-in-region beg end)
6572 (delete-region beg end)
6573 (org-remove-empty-overlays-at beg)
6574 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6575 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6576 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6577 (let ((bbb (point)))
6578 (insert-before-markers txt)
6579 (org-reinstall-markers-in-region bbb)
6580 (move-marker ins-point bbb))
6581 (or (bolp) (insert "\n"))
6582 (setq ins-end (point))
6583 (goto-char ins-point)
6584 (org-skip-whitespace)
6585 (when (and (< arg 0)
6586 (org-first-sibling-p)
6587 (> ne-ins ne-beg))
6588 ;; Move whitespace back to beginning
6589 (save-excursion
6590 (goto-char ins-end)
6591 (let ((kill-whole-line t))
6592 (kill-line (- ne-ins ne-beg)) (point)))
6593 (insert (make-string (- ne-ins ne-beg) ?\n)))
6594 (move-marker ins-point nil)
6595 (if folded
6596 (hide-subtree)
6597 (org-show-entry)
6598 (show-children)
6599 (org-cycle-hide-drawers 'children))
6600 (org-clean-visibility-after-subtree-move)))
6602 (defvar org-subtree-clip ""
6603 "Clipboard for cut and paste of subtrees.
6604 This is actually only a copy of the kill, because we use the normal kill
6605 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6607 (defvar org-subtree-clip-folded nil
6608 "Was the last copied subtree folded?
6609 This is used to fold the tree back after pasting.")
6611 (defun org-cut-subtree (&optional n)
6612 "Cut the current subtree into the clipboard.
6613 With prefix arg N, cut this many sequential subtrees.
6614 This is a short-hand for marking the subtree and then cutting it."
6615 (interactive "p")
6616 (org-copy-subtree n 'cut))
6618 (defun org-copy-subtree (&optional n cut force-store-markers)
6619 "Cut the current subtree into the clipboard.
6620 With prefix arg N, cut this many sequential subtrees.
6621 This is a short-hand for marking the subtree and then copying it.
6622 If CUT is non-nil, actually cut the subtree.
6623 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6624 of some markers in the region, even if CUT is non-nil. This is
6625 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6626 (interactive "p")
6627 (let (beg end folded (beg0 (point)))
6628 (if (interactive-p)
6629 (org-back-to-heading nil) ; take what looks like a subtree
6630 (org-back-to-heading t)) ; take what is really there
6631 (org-back-over-empty-lines)
6632 (setq beg (point))
6633 (skip-chars-forward " \t\r\n")
6634 (save-match-data
6635 (save-excursion (outline-end-of-heading)
6636 (setq folded (org-invisible-p)))
6637 (condition-case nil
6638 (org-forward-same-level (1- n) t)
6639 (error nil))
6640 (org-end-of-subtree t t))
6641 (org-back-over-empty-lines)
6642 (setq end (point))
6643 (goto-char beg0)
6644 (when (> end beg)
6645 (setq org-subtree-clip-folded folded)
6646 (when (or cut force-store-markers)
6647 (org-save-markers-in-region beg end))
6648 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6649 (setq org-subtree-clip (current-kill 0))
6650 (message "%s: Subtree(s) with %d characters"
6651 (if cut "Cut" "Copied")
6652 (length org-subtree-clip)))))
6654 (defun org-paste-subtree (&optional level tree for-yank)
6655 "Paste the clipboard as a subtree, with modification of headline level.
6656 The entire subtree is promoted or demoted in order to match a new headline
6657 level.
6659 If the cursor is at the beginning of a headline, the same level as
6660 that headline is used to paste the tree
6662 If not, the new level is derived from the *visible* headings
6663 before and after the insertion point, and taken to be the inferior headline
6664 level of the two. So if the previous visible heading is level 3 and the
6665 next is level 4 (or vice versa), level 4 will be used for insertion.
6666 This makes sure that the subtree remains an independent subtree and does
6667 not swallow low level entries.
6669 You can also force a different level, either by using a numeric prefix
6670 argument, or by inserting the heading marker by hand. For example, if the
6671 cursor is after \"*****\", then the tree will be shifted to level 5.
6673 If optional TREE is given, use this text instead of the kill ring.
6675 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6676 move back over whitespace before inserting, and move point to the end of
6677 the inserted text when done."
6678 (interactive "P")
6679 (setq tree (or tree (and kill-ring (current-kill 0))))
6680 (unless (org-kill-is-subtree-p tree)
6681 (error "%s"
6682 (substitute-command-keys
6683 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6684 (let* ((visp (not (org-invisible-p)))
6685 (txt tree)
6686 (^re (concat "^\\(" outline-regexp "\\)"))
6687 (re (concat "\\(" outline-regexp "\\)"))
6688 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6690 (old-level (if (string-match ^re txt)
6691 (- (match-end 0) (match-beginning 0) 1)
6692 -1))
6693 (force-level (cond (level (prefix-numeric-value level))
6694 ((and (looking-at "[ \t]*$")
6695 (string-match
6696 ^re_ (buffer-substring
6697 (point-at-bol) (point))))
6698 (- (match-end 1) (match-beginning 1)))
6699 ((and (bolp)
6700 (looking-at org-outline-regexp))
6701 (- (match-end 0) (point) 1))
6702 (t nil)))
6703 (previous-level (save-excursion
6704 (condition-case nil
6705 (progn
6706 (outline-previous-visible-heading 1)
6707 (if (looking-at re)
6708 (- (match-end 0) (match-beginning 0) 1)
6710 (error 1))))
6711 (next-level (save-excursion
6712 (condition-case nil
6713 (progn
6714 (or (looking-at outline-regexp)
6715 (outline-next-visible-heading 1))
6716 (if (looking-at re)
6717 (- (match-end 0) (match-beginning 0) 1)
6719 (error 1))))
6720 (new-level (or force-level (max previous-level next-level)))
6721 (shift (if (or (= old-level -1)
6722 (= new-level -1)
6723 (= old-level new-level))
6725 (- new-level old-level)))
6726 (delta (if (> shift 0) -1 1))
6727 (func (if (> shift 0) 'org-demote 'org-promote))
6728 (org-odd-levels-only nil)
6729 beg end newend)
6730 ;; Remove the forced level indicator
6731 (if force-level
6732 (delete-region (point-at-bol) (point)))
6733 ;; Paste
6734 (beginning-of-line 1)
6735 (unless for-yank (org-back-over-empty-lines))
6736 (setq beg (point))
6737 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6738 (insert-before-markers txt)
6739 (unless (string-match "\n\\'" txt) (insert "\n"))
6740 (setq newend (point))
6741 (org-reinstall-markers-in-region beg)
6742 (setq end (point))
6743 (goto-char beg)
6744 (skip-chars-forward " \t\n\r")
6745 (setq beg (point))
6746 (if (and (org-invisible-p) visp)
6747 (save-excursion (outline-show-heading)))
6748 ;; Shift if necessary
6749 (unless (= shift 0)
6750 (save-restriction
6751 (narrow-to-region beg end)
6752 (while (not (= shift 0))
6753 (org-map-region func (point-min) (point-max))
6754 (setq shift (+ delta shift)))
6755 (goto-char (point-min))
6756 (setq newend (point-max))))
6757 (when (or (interactive-p) for-yank)
6758 (message "Clipboard pasted as level %d subtree" new-level))
6759 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6760 kill-ring
6761 (eq org-subtree-clip (current-kill 0))
6762 org-subtree-clip-folded)
6763 ;; The tree was folded before it was killed/copied
6764 (hide-subtree))
6765 (and for-yank (goto-char newend))))
6767 (defun org-kill-is-subtree-p (&optional txt)
6768 "Check if the current kill is an outline subtree, or a set of trees.
6769 Returns nil if kill does not start with a headline, or if the first
6770 headline level is not the largest headline level in the tree.
6771 So this will actually accept several entries of equal levels as well,
6772 which is OK for `org-paste-subtree'.
6773 If optional TXT is given, check this string instead of the current kill."
6774 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6775 (start-level (and kill
6776 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6777 org-outline-regexp "\\)")
6778 kill)
6779 (- (match-end 2) (match-beginning 2) 1)))
6780 (re (concat "^" org-outline-regexp))
6781 (start (1+ (or (match-beginning 2) -1))))
6782 (if (not start-level)
6783 (progn
6784 nil) ;; does not even start with a heading
6785 (catch 'exit
6786 (while (setq start (string-match re kill (1+ start)))
6787 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6788 (throw 'exit nil)))
6789 t))))
6791 (defvar org-markers-to-move nil
6792 "Markers that should be moved with a cut-and-paste operation.
6793 Those markers are stored together with their positions relative to
6794 the start of the region.")
6796 (defun org-save-markers-in-region (beg end)
6797 "Check markers in region.
6798 If these markers are between BEG and END, record their position relative
6799 to BEG, so that after moving the block of text, we can put the markers back
6800 into place.
6801 This function gets called just before an entry or tree gets cut from the
6802 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6803 called immediately, to move the markers with the entries."
6804 (setq org-markers-to-move nil)
6805 (when (featurep 'org-clock)
6806 (org-clock-save-markers-for-cut-and-paste beg end))
6807 (when (featurep 'org-agenda)
6808 (org-agenda-save-markers-for-cut-and-paste beg end)))
6810 (defun org-check-and-save-marker (marker beg end)
6811 "Check if MARKER is between BEG and END.
6812 If yes, remember the marker and the distance to BEG."
6813 (when (and (marker-buffer marker)
6814 (equal (marker-buffer marker) (current-buffer)))
6815 (if (and (>= marker beg) (< marker end))
6816 (push (cons marker (- marker beg)) org-markers-to-move))))
6818 (defun org-reinstall-markers-in-region (beg)
6819 "Move all remembered markers to their position relative to BEG."
6820 (mapc (lambda (x)
6821 (move-marker (car x) (+ beg (cdr x))))
6822 org-markers-to-move)
6823 (setq org-markers-to-move nil))
6825 (defun org-narrow-to-subtree ()
6826 "Narrow buffer to the current subtree."
6827 (interactive)
6828 (save-excursion
6829 (save-match-data
6830 (narrow-to-region
6831 (progn (org-back-to-heading t) (point))
6832 (progn (org-end-of-subtree t t) (point))))))
6834 (defun org-clone-subtree-with-time-shift (n &optional shift)
6835 "Clone the task (subtree) at point N times.
6836 The clones will be inserted as siblings.
6838 In interactive use, the user will be prompted for the number of clones
6839 to be produced, and for a time SHIFT, which may be a repeater as used
6840 in time stamps, for example `+3d'.
6842 When a valid repeater is given and the entry contains any time stamps,
6843 the clones will become a sequence in time, with time stamps in the
6844 subtree shifted for each clone produced. If SHIFT is nil or the
6845 empty string, time stamps will be left alone.
6847 If the original subtree did contain time stamps with a repeater,
6848 the following will happen:
6849 - the repeater will be removed in each clone
6850 - an additional clone will be produced, with the current, unshifted
6851 date(s) in the entry.
6852 - the original entry will be placed *after* all the clones, with
6853 repeater intact.
6854 - the start days in the repeater in the original entry will be shifted
6855 to past the last clone.
6856 I this way you can spell out a number of instances of a repeating task,
6857 and still retain the repeater to cover future instances of the task."
6858 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6859 (let (beg end template task
6860 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6861 (if (not (and (integerp n) (> n 0)))
6862 (error "Invalid number of replications %s" n))
6863 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6864 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6865 shift)))
6866 (error "Invalid shift specification %s" shift))
6867 (when doshift
6868 (setq shift-n (string-to-number (match-string 1 shift))
6869 shift-what (cdr (assoc (match-string 2 shift)
6870 '(("d" . day) ("w" . week)
6871 ("m" . month) ("y" . year))))))
6872 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6873 (setq nmin 1 nmax n)
6874 (org-back-to-heading t)
6875 (setq beg (point))
6876 (org-end-of-subtree t t)
6877 (or (bolp) (insert "\n"))
6878 (setq end (point))
6879 (setq template (buffer-substring beg end))
6880 (when (and doshift
6881 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6882 (delete-region beg end)
6883 (setq end beg)
6884 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6885 (goto-char end)
6886 (loop for n from nmin to nmax do
6887 (if (not doshift)
6888 (setq task template)
6889 (with-temp-buffer
6890 (insert template)
6891 (org-mode)
6892 (goto-char (point-min))
6893 (while (re-search-forward org-ts-regexp-both nil t)
6894 (org-timestamp-change (* n shift-n) shift-what))
6895 (unless (= n n-no-remove)
6896 (goto-char (point-min))
6897 (while (re-search-forward org-ts-regexp nil t)
6898 (save-excursion
6899 (goto-char (match-beginning 0))
6900 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6901 (delete-region (match-beginning 1) (match-end 1))))))
6902 (setq task (buffer-string))))
6903 (insert task))
6904 (goto-char beg)))
6906 ;;; Outline Sorting
6908 (defun org-sort (with-case)
6909 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6910 Optional argument WITH-CASE means sort case-sensitively.
6911 With a double prefix argument, also remove duplicate entries."
6912 (interactive "P")
6913 (if (org-at-table-p)
6914 (org-call-with-arg 'org-table-sort-lines with-case)
6915 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6917 (defun org-sort-remove-invisible (s)
6918 (remove-text-properties 0 (length s) org-rm-props s)
6919 (while (string-match org-bracket-link-regexp s)
6920 (setq s (replace-match (if (match-end 2)
6921 (match-string 3 s)
6922 (match-string 1 s)) t t s)))
6925 (defvar org-priority-regexp) ; defined later in the file
6927 (defvar org-after-sorting-entries-or-items-hook nil
6928 "Hook that is run after a bunch of entries or items have been sorted.
6929 When children are sorted, the cursor is in the parent line when this
6930 hook gets called. When a region or a plain list is sorted, the cursor
6931 will be in the first entry of the sorted region/list.")
6933 (defun org-sort-entries-or-items
6934 (&optional with-case sorting-type getkey-func compare-func property)
6935 "Sort entries on a certain level of an outline tree, or plain list items.
6936 If there is an active region, the entries in the region are sorted.
6937 Else, if the cursor is before the first entry, sort the top-level items.
6938 Else, the children of the entry at point are sorted.
6939 If the cursor is at the first item in a plain list, the list items will be
6940 sorted.
6942 Sorting can be alphabetically, numerically, by date/time as given by
6943 a time stamp, by a property or by priority.
6945 The command prompts for the sorting type unless it has been given to the
6946 function through the SORTING-TYPE argument, which needs to a character,
6947 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6948 precise meaning of each character:
6950 n Numerically, by converting the beginning of the entry/item to a number.
6951 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6952 t By date/time, either the first active time stamp in the entry, or, if
6953 none exist, by the first inactive one.
6954 In items, only the first line will be checked.
6955 s By the scheduled date/time.
6956 d By deadline date/time.
6957 c By creation time, which is assumed to be the first inactive time stamp
6958 at the beginning of a line.
6959 p By priority according to the cookie.
6960 r By the value of a property.
6962 Capital letters will reverse the sort order.
6964 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6965 called with point at the beginning of the record. It must return either
6966 a string or a number that should serve as the sorting key for that record.
6968 Comparing entries ignores case by default. However, with an optional argument
6969 WITH-CASE, the sorting considers case as well."
6970 (interactive "P")
6971 (let ((case-func (if with-case 'identity 'downcase))
6972 start beg end stars re re2
6973 txt what tmp plain-list-p)
6974 ;; Find beginning and end of region to sort
6975 (cond
6976 ((org-region-active-p)
6977 ;; we will sort the region
6978 (setq end (region-end)
6979 what "region")
6980 (goto-char (region-beginning))
6981 (if (not (org-on-heading-p)) (outline-next-heading))
6982 (setq start (point)))
6983 ((org-at-item-p)
6984 ;; we will sort this plain list
6985 (org-beginning-of-item-list) (setq start (point))
6986 (org-end-of-item-list)
6987 (or (bolp) (insert "\n"))
6988 (setq end (point))
6989 (goto-char start)
6990 (setq plain-list-p t
6991 what "plain list"))
6992 ((or (org-on-heading-p)
6993 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6994 ;; we will sort the children of the current headline
6995 (org-back-to-heading)
6996 (setq start (point)
6997 end (progn (org-end-of-subtree t t)
6998 (or (bolp) (insert "\n"))
6999 (org-back-over-empty-lines)
7000 (point))
7001 what "children")
7002 (goto-char start)
7003 (show-subtree)
7004 (outline-next-heading))
7006 ;; we will sort the top-level entries in this file
7007 (goto-char (point-min))
7008 (or (org-on-heading-p) (outline-next-heading))
7009 (setq start (point))
7010 (goto-char (point-max))
7011 (beginning-of-line 1)
7012 (when (looking-at ".*?\\S-")
7013 ;; File ends in a non-white line
7014 (end-of-line 1)
7015 (insert "\n"))
7016 (setq end (point-max))
7017 (setq what "top-level")
7018 (goto-char start)
7019 (show-all)))
7021 (setq beg (point))
7022 (if (>= beg end) (error "Nothing to sort"))
7024 (unless plain-list-p
7025 (looking-at "\\(\\*+\\)")
7026 (setq stars (match-string 1)
7027 re (concat "^" (regexp-quote stars) " +")
7028 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7029 txt (buffer-substring beg end))
7030 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7031 (if (and (not (equal stars "*")) (string-match re2 txt))
7032 (error "Region to sort contains a level above the first entry")))
7034 (unless sorting-type
7035 (message
7036 (if plain-list-p
7037 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7038 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7039 [t]ime [s]cheduled [d]eadline [c]reated
7040 A/N/T/S/D/C/P/O/F means reversed:")
7041 what)
7042 (setq sorting-type (read-char-exclusive))
7044 (and (= (downcase sorting-type) ?f)
7045 (setq getkey-func
7046 (org-icompleting-read "Sort using function: "
7047 obarray 'fboundp t nil nil))
7048 (setq getkey-func (intern getkey-func)))
7050 (and (= (downcase sorting-type) ?r)
7051 (setq property
7052 (org-icompleting-read "Property: "
7053 (mapcar 'list (org-buffer-property-keys t))
7054 nil t))))
7056 (message "Sorting entries...")
7058 (save-restriction
7059 (narrow-to-region start end)
7061 (let ((dcst (downcase sorting-type))
7062 (case-fold-search nil)
7063 (now (current-time)))
7064 (sort-subr
7065 (/= dcst sorting-type)
7066 ;; This function moves to the beginning character of the "record" to
7067 ;; be sorted.
7068 (if plain-list-p
7069 (lambda nil
7070 (if (org-at-item-p) t (goto-char (point-max))))
7071 (lambda nil
7072 (if (re-search-forward re nil t)
7073 (goto-char (match-beginning 0))
7074 (goto-char (point-max)))))
7075 ;; This function moves to the last character of the "record" being
7076 ;; sorted.
7077 (if plain-list-p
7078 'org-end-of-item
7079 (lambda nil
7080 (save-match-data
7081 (condition-case nil
7082 (outline-forward-same-level 1)
7083 (error
7084 (goto-char (point-max)))))))
7086 ;; This function returns the value that gets sorted against.
7087 (if plain-list-p
7088 (lambda nil
7089 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7090 (cond
7091 ((= dcst ?n)
7092 (string-to-number (buffer-substring (match-end 0)
7093 (point-at-eol))))
7094 ((= dcst ?a)
7095 (buffer-substring (match-end 0) (point-at-eol)))
7096 ((= dcst ?t)
7097 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7098 (re-search-forward org-ts-regexp-both
7099 (point-at-eol) t))
7100 (org-time-string-to-seconds (match-string 0))
7101 (org-float-time now)))
7102 ((= dcst ?f)
7103 (if getkey-func
7104 (progn
7105 (setq tmp (funcall getkey-func))
7106 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7107 tmp)
7108 (error "Invalid key function `%s'" getkey-func)))
7109 (t (error "Invalid sorting type `%c'" sorting-type)))))
7110 (lambda nil
7111 (cond
7112 ((= dcst ?n)
7113 (if (looking-at org-complex-heading-regexp)
7114 (string-to-number (match-string 4))
7115 nil))
7116 ((= dcst ?a)
7117 (if (looking-at org-complex-heading-regexp)
7118 (funcall case-func (match-string 4))
7119 nil))
7120 ((= dcst ?t)
7121 (let ((end (save-excursion (outline-next-heading) (point))))
7122 (if (or (re-search-forward org-ts-regexp end t)
7123 (re-search-forward org-ts-regexp-both end t))
7124 (org-time-string-to-seconds (match-string 0))
7125 (org-float-time now))))
7126 ((= dcst ?c)
7127 (let ((end (save-excursion (outline-next-heading) (point))))
7128 (if (re-search-forward
7129 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7130 end t)
7131 (org-time-string-to-seconds (match-string 0))
7132 (org-float-time now))))
7133 ((= dcst ?s)
7134 (let ((end (save-excursion (outline-next-heading) (point))))
7135 (if (re-search-forward org-scheduled-time-regexp end t)
7136 (org-time-string-to-seconds (match-string 1))
7137 (org-float-time now))))
7138 ((= dcst ?d)
7139 (let ((end (save-excursion (outline-next-heading) (point))))
7140 (if (re-search-forward org-deadline-time-regexp end t)
7141 (org-time-string-to-seconds (match-string 1))
7142 (org-float-time now))))
7143 ((= dcst ?p)
7144 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7145 (string-to-char (match-string 2))
7146 org-default-priority))
7147 ((= dcst ?r)
7148 (or (org-entry-get nil property) ""))
7149 ((= dcst ?o)
7150 (if (looking-at org-complex-heading-regexp)
7151 (- 9999 (length (member (match-string 2)
7152 org-todo-keywords-1)))))
7153 ((= dcst ?f)
7154 (if getkey-func
7155 (progn
7156 (setq tmp (funcall getkey-func))
7157 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7158 tmp)
7159 (error "Invalid key function `%s'" getkey-func)))
7160 (t (error "Invalid sorting type `%c'" sorting-type)))))
7162 (cond
7163 ((= dcst ?a) 'string<)
7164 ((= dcst ?f) compare-func)
7165 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7166 (t nil)))))
7167 (run-hooks 'org-after-sorting-entries-or-items-hook)
7168 (message "Sorting entries...done")))
7170 (defun org-do-sort (table what &optional with-case sorting-type)
7171 "Sort TABLE of WHAT according to SORTING-TYPE.
7172 The user will be prompted for the SORTING-TYPE if the call to this
7173 function does not specify it. WHAT is only for the prompt, to indicate
7174 what is being sorted. The sorting key will be extracted from
7175 the car of the elements of the table.
7176 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7177 (unless sorting-type
7178 (message
7179 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7180 what)
7181 (setq sorting-type (read-char-exclusive)))
7182 (let ((dcst (downcase sorting-type))
7183 extractfun comparefun)
7184 ;; Define the appropriate functions
7185 (cond
7186 ((= dcst ?n)
7187 (setq extractfun 'string-to-number
7188 comparefun (if (= dcst sorting-type) '< '>)))
7189 ((= dcst ?a)
7190 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7191 (lambda(x) (downcase (org-sort-remove-invisible x))))
7192 comparefun (if (= dcst sorting-type)
7193 'string<
7194 (lambda (a b) (and (not (string< a b))
7195 (not (string= a b)))))))
7196 ((= dcst ?t)
7197 (setq extractfun
7198 (lambda (x)
7199 (if (or (string-match org-ts-regexp x)
7200 (string-match org-ts-regexp-both x))
7201 (org-float-time
7202 (org-time-string-to-time (match-string 0 x)))
7204 comparefun (if (= dcst sorting-type) '< '>)))
7205 (t (error "Invalid sorting type `%c'" sorting-type)))
7207 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7208 table)
7209 (lambda (a b) (funcall comparefun (car a) (car b))))))
7212 ;;; The orgstruct minor mode
7214 ;; Define a minor mode which can be used in other modes in order to
7215 ;; integrate the org-mode structure editing commands.
7217 ;; This is really a hack, because the org-mode structure commands use
7218 ;; keys which normally belong to the major mode. Here is how it
7219 ;; works: The minor mode defines all the keys necessary to operate the
7220 ;; structure commands, but wraps the commands into a function which
7221 ;; tests if the cursor is currently at a headline or a plain list
7222 ;; item. If that is the case, the structure command is used,
7223 ;; temporarily setting many Org-mode variables like regular
7224 ;; expressions for filling etc. However, when any of those keys is
7225 ;; used at a different location, function uses `key-binding' to look
7226 ;; up if the key has an associated command in another currently active
7227 ;; keymap (minor modes, major mode, global), and executes that
7228 ;; command. There might be problems if any of the keys is otherwise
7229 ;; used as a prefix key.
7231 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7232 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7233 ;; addresses this by checking explicitly for both bindings.
7235 (defvar orgstruct-mode-map (make-sparse-keymap)
7236 "Keymap for the minor `orgstruct-mode'.")
7238 (defvar org-local-vars nil
7239 "List of local variables, for use by `orgstruct-mode'")
7241 ;;;###autoload
7242 (define-minor-mode orgstruct-mode
7243 "Toggle the minor more `orgstruct-mode'.
7244 This mode is for using Org-mode structure commands in other modes.
7245 The following key behave as if Org-mode was active, if the cursor
7246 is on a headline, or on a plain list item (both in the definition
7247 of Org-mode).
7249 M-up Move entry/item up
7250 M-down Move entry/item down
7251 M-left Promote
7252 M-right Demote
7253 M-S-up Move entry/item up
7254 M-S-down Move entry/item down
7255 M-S-left Promote subtree
7256 M-S-right Demote subtree
7257 M-q Fill paragraph and items like in Org-mode
7258 C-c ^ Sort entries
7259 C-c - Cycle list bullet
7260 TAB Cycle item visibility
7261 M-RET Insert new heading/item
7262 S-M-RET Insert new TODO heading / Checkbox item
7263 C-c C-c Set tags / toggle checkbox"
7264 nil " OrgStruct" nil
7265 (org-load-modules-maybe)
7266 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7268 ;;;###autoload
7269 (defun turn-on-orgstruct ()
7270 "Unconditionally turn on `orgstruct-mode'."
7271 (orgstruct-mode 1))
7273 (defun orgstruct++-mode (&optional arg)
7274 "Toggle `orgstruct-mode', the enhanced version of it.
7275 In addition to setting orgstruct-mode, this also exports all indentation
7276 and autofilling variables from org-mode into the buffer. It will also
7277 recognize item context in multiline items.
7278 Note that turning off orgstruct-mode will *not* remove the
7279 indentation/paragraph settings. This can only be done by refreshing the
7280 major mode, for example with \\[normal-mode]."
7281 (interactive "P")
7282 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7283 (if (< arg 1)
7284 (orgstruct-mode -1)
7285 (orgstruct-mode 1)
7286 (let (var val)
7287 (mapc
7288 (lambda (x)
7289 (when (string-match
7290 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7291 (symbol-name (car x)))
7292 (setq var (car x) val (nth 1 x))
7293 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7294 org-local-vars)
7295 (org-set-local 'orgstruct-is-++ t))))
7297 (defvar orgstruct-is-++ nil
7298 "Is orgstruct-mode in ++ version in the current-buffer?")
7299 (make-variable-buffer-local 'orgstruct-is-++)
7301 ;;;###autoload
7302 (defun turn-on-orgstruct++ ()
7303 "Unconditionally turn on `orgstruct++-mode'."
7304 (orgstruct++-mode 1))
7306 (defun orgstruct-error ()
7307 "Error when there is no default binding for a structure key."
7308 (interactive)
7309 (error "This key has no function outside structure elements"))
7311 (defun orgstruct-setup ()
7312 "Setup orgstruct keymaps."
7313 (let ((nfunc 0)
7314 (bindings
7315 (list
7316 '([(meta up)] org-metaup)
7317 '([(meta down)] org-metadown)
7318 '([(meta left)] org-metaleft)
7319 '([(meta right)] org-metaright)
7320 '([(meta shift up)] org-shiftmetaup)
7321 '([(meta shift down)] org-shiftmetadown)
7322 '([(meta shift left)] org-shiftmetaleft)
7323 '([(meta shift right)] org-shiftmetaright)
7324 '([?\e (up)] org-metaup)
7325 '([?\e (down)] org-metadown)
7326 '([?\e (left)] org-metaleft)
7327 '([?\e (right)] org-metaright)
7328 '([?\e (shift up)] org-shiftmetaup)
7329 '([?\e (shift down)] org-shiftmetadown)
7330 '([?\e (shift left)] org-shiftmetaleft)
7331 '([?\e (shift right)] org-shiftmetaright)
7332 '([(shift up)] org-shiftup)
7333 '([(shift down)] org-shiftdown)
7334 '([(shift left)] org-shiftleft)
7335 '([(shift right)] org-shiftright)
7336 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7337 '("\M-q" fill-paragraph)
7338 '("\C-c^" org-sort)
7339 '("\C-c-" org-cycle-list-bullet)))
7340 elt key fun cmd)
7341 (while (setq elt (pop bindings))
7342 (setq nfunc (1+ nfunc))
7343 (setq key (org-key (car elt))
7344 fun (nth 1 elt)
7345 cmd (orgstruct-make-binding fun nfunc key))
7346 (org-defkey orgstruct-mode-map key cmd))
7348 ;; Special treatment needed for TAB and RET
7349 (org-defkey orgstruct-mode-map [(tab)]
7350 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7351 (org-defkey orgstruct-mode-map "\C-i"
7352 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7354 (org-defkey orgstruct-mode-map "\M-\C-m"
7355 (orgstruct-make-binding 'org-insert-heading 105
7356 "\M-\C-m" [(meta return)]))
7357 (org-defkey orgstruct-mode-map [(meta return)]
7358 (orgstruct-make-binding 'org-insert-heading 106
7359 [(meta return)] "\M-\C-m"))
7361 (org-defkey orgstruct-mode-map [(shift meta return)]
7362 (orgstruct-make-binding 'org-insert-todo-heading 107
7363 [(meta return)] "\M-\C-m"))
7365 (org-defkey orgstruct-mode-map "\e\C-m"
7366 (orgstruct-make-binding 'org-insert-heading 108
7367 "\e\C-m" [?\e (return)]))
7368 (org-defkey orgstruct-mode-map [?\e (return)]
7369 (orgstruct-make-binding 'org-insert-heading 109
7370 [?\e (return)] "\e\C-m"))
7371 (org-defkey orgstruct-mode-map [?\e (shift return)]
7372 (orgstruct-make-binding 'org-insert-todo-heading 110
7373 [?\e (return)] "\e\C-m"))
7375 (unless org-local-vars
7376 (setq org-local-vars (org-get-local-variables)))
7380 (defun orgstruct-make-binding (fun n &rest keys)
7381 "Create a function for binding in the structure minor mode.
7382 FUN is the command to call inside a table. N is used to create a unique
7383 command name. KEYS are keys that should be checked in for a command
7384 to execute outside of tables."
7385 (eval
7386 (list 'defun
7387 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7388 '(arg)
7389 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7390 "Outside of structure, run the binding of `"
7391 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7392 "'.")
7393 '(interactive "p")
7394 (list 'if
7395 `(org-context-p 'headline 'item
7396 (and orgstruct-is-++
7397 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7398 'item-body))
7399 (list 'org-run-like-in-org-mode (list 'quote fun))
7400 (list 'let '(orgstruct-mode)
7401 (list 'call-interactively
7402 (append '(or)
7403 (mapcar (lambda (k)
7404 (list 'key-binding k))
7405 keys)
7406 '('orgstruct-error))))))))
7408 (defun org-context-p (&rest contexts)
7409 "Check if local context is any of CONTEXTS.
7410 Possible values in the list of contexts are `table', `headline', and `item'."
7411 (let ((pos (point)))
7412 (goto-char (point-at-bol))
7413 (prog1 (or (and (memq 'table contexts)
7414 (looking-at "[ \t]*|"))
7415 (and (memq 'headline contexts)
7416 ;;????????? (looking-at "\\*+"))
7417 (looking-at outline-regexp))
7418 (and (memq 'item contexts)
7419 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7420 (and (memq 'item-body contexts)
7421 (org-in-item-p)))
7422 (goto-char pos))))
7424 (defun org-get-local-variables ()
7425 "Return a list of all local variables in an org-mode buffer."
7426 (let (varlist)
7427 (with-current-buffer (get-buffer-create "*Org tmp*")
7428 (erase-buffer)
7429 (org-mode)
7430 (setq varlist (buffer-local-variables)))
7431 (kill-buffer "*Org tmp*")
7432 (delq nil
7433 (mapcar
7434 (lambda (x)
7435 (setq x
7436 (if (symbolp x)
7437 (list x)
7438 (list (car x) (list 'quote (cdr x)))))
7439 (if (string-match
7440 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7441 (symbol-name (car x)))
7442 x nil))
7443 varlist))))
7445 ;;;###autoload
7446 (defun org-run-like-in-org-mode (cmd)
7447 "Run a command, pretending that the current buffer is in Org-mode.
7448 This will temporarily bind local variables that are typically bound in
7449 Org-mode to the values they have in Org-mode, and then interactively
7450 call CMD."
7451 (org-load-modules-maybe)
7452 (unless org-local-vars
7453 (setq org-local-vars (org-get-local-variables)))
7454 (eval (list 'let org-local-vars
7455 (list 'call-interactively (list 'quote cmd)))))
7457 ;;;; Archiving
7459 (defun org-get-category (&optional pos)
7460 "Get the category applying to position POS."
7461 (get-text-property (or pos (point)) 'org-category))
7463 (defun org-refresh-category-properties ()
7464 "Refresh category text properties in the buffer."
7465 (let ((def-cat (cond
7466 ((null org-category)
7467 (if buffer-file-name
7468 (file-name-sans-extension
7469 (file-name-nondirectory buffer-file-name))
7470 "???"))
7471 ((symbolp org-category) (symbol-name org-category))
7472 (t org-category)))
7473 beg end cat pos optionp)
7474 (org-unmodified
7475 (save-excursion
7476 (save-restriction
7477 (widen)
7478 (goto-char (point-min))
7479 (put-text-property (point) (point-max) 'org-category def-cat)
7480 (while (re-search-forward
7481 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7482 (setq pos (match-end 0)
7483 optionp (equal (char-after (match-beginning 0)) ?#)
7484 cat (org-trim (match-string 2)))
7485 (if optionp
7486 (setq beg (point-at-bol) end (point-max))
7487 (org-back-to-heading t)
7488 (setq beg (point) end (org-end-of-subtree t t)))
7489 (put-text-property beg end 'org-category cat)
7490 (goto-char pos)))))))
7493 ;;;; Link Stuff
7495 ;;; Link abbreviations
7497 (defun org-link-expand-abbrev (link)
7498 "Apply replacements as defined in `org-link-abbrev-alist."
7499 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7500 (let* ((key (match-string 1 link))
7501 (as (or (assoc key org-link-abbrev-alist-local)
7502 (assoc key org-link-abbrev-alist)))
7503 (tag (and (match-end 2) (match-string 3 link)))
7504 rpl)
7505 (if (not as)
7506 link
7507 (setq rpl (cdr as))
7508 (cond
7509 ((symbolp rpl) (funcall rpl tag))
7510 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7511 ((string-match "%h" rpl)
7512 (replace-match (url-hexify-string (or tag "")) t t rpl))
7513 (t (concat rpl tag)))))
7514 link))
7516 ;;; Storing and inserting links
7518 (defvar org-insert-link-history nil
7519 "Minibuffer history for links inserted with `org-insert-link'.")
7521 (defvar org-stored-links nil
7522 "Contains the links stored with `org-store-link'.")
7524 (defvar org-store-link-plist nil
7525 "Plist with info about the most recently link created with `org-store-link'.")
7527 (defvar org-link-protocols nil
7528 "Link protocols added to Org-mode using `org-add-link-type'.")
7530 (defvar org-store-link-functions nil
7531 "List of functions that are called to create and store a link.
7532 Each function will be called in turn until one returns a non-nil
7533 value. Each function should check if it is responsible for creating
7534 this link (for example by looking at the major mode).
7535 If not, it must exit and return nil.
7536 If yes, it should return a non-nil value after a calling
7537 `org-store-link-props' with a list of properties and values.
7538 Special properties are:
7540 :type The link prefix. like \"http\". This must be given.
7541 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7542 This is obligatory as well.
7543 :description Optional default description for the second pair
7544 of brackets in an Org-mode link. The user can still change
7545 this when inserting this link into an Org-mode buffer.
7547 In addition to these, any additional properties can be specified
7548 and then used in remember templates.")
7550 (defun org-add-link-type (type &optional follow export)
7551 "Add TYPE to the list of `org-link-types'.
7552 Re-compute all regular expressions depending on `org-link-types'
7554 FOLLOW and EXPORT are two functions.
7556 FOLLOW should take the link path as the single argument and do whatever
7557 is necessary to follow the link, for example find a file or display
7558 a mail message.
7560 EXPORT should format the link path for export to one of the export formats.
7561 It should be a function accepting three arguments:
7563 path the path of the link, the text after the prefix (like \"http:\")
7564 desc the description of the link, if any, nil if there was no description
7565 format the export format, a symbol like `html' or `latex'.
7567 The function may use the FORMAT information to return different values
7568 depending on the format. The return value will be put literally into
7569 the exported file.
7570 Org-mode has a built-in default for exporting links. If you are happy with
7571 this default, there is no need to define an export function for the link
7572 type. For a simple example of an export function, see `org-bbdb.el'."
7573 (add-to-list 'org-link-types type t)
7574 (org-make-link-regexps)
7575 (if (assoc type org-link-protocols)
7576 (setcdr (assoc type org-link-protocols) (list follow export))
7577 (push (list type follow export) org-link-protocols)))
7579 (defvar org-agenda-buffer-name)
7581 ;;;###autoload
7582 (defun org-store-link (arg)
7583 "\\<org-mode-map>Store an org-link to the current location.
7584 This link is added to `org-stored-links' and can later be inserted
7585 into an org-buffer with \\[org-insert-link].
7587 For some link types, a prefix arg is interpreted:
7588 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7589 For file links, arg negates `org-context-in-file-links'."
7590 (interactive "P")
7591 (org-load-modules-maybe)
7592 (setq org-store-link-plist nil) ; reset
7593 (let ((outline-regexp (org-get-limited-outline-regexp))
7594 link cpltxt desc description search txt custom-id)
7595 (cond
7597 ((run-hook-with-args-until-success 'org-store-link-functions)
7598 (setq link (plist-get org-store-link-plist :link)
7599 desc (or (plist-get org-store-link-plist :description) link)))
7601 ((equal (buffer-name) "*Org Edit Src Example*")
7602 (let (label gc)
7603 (while (or (not label)
7604 (save-excursion
7605 (save-restriction
7606 (widen)
7607 (goto-char (point-min))
7608 (re-search-forward
7609 (regexp-quote (format org-coderef-label-format label))
7610 nil t))))
7611 (when label (message "Label exists already") (sit-for 2))
7612 (setq label (read-string "Code line label: " label)))
7613 (end-of-line 1)
7614 (setq link (format org-coderef-label-format label))
7615 (setq gc (- 79 (length link)))
7616 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7617 (insert link)
7618 (setq link (concat "(" label ")") desc nil)))
7620 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7621 ;; We are in the agenda, link to referenced location
7622 (let ((m (or (get-text-property (point) 'org-hd-marker)
7623 (get-text-property (point) 'org-marker))))
7624 (when m
7625 (org-with-point-at m
7626 (call-interactively 'org-store-link)))))
7628 ((eq major-mode 'calendar-mode)
7629 (let ((cd (calendar-cursor-to-date)))
7630 (setq link
7631 (format-time-string
7632 (car org-time-stamp-formats)
7633 (apply 'encode-time
7634 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7635 nil nil nil))))
7636 (org-store-link-props :type "calendar" :date cd)))
7638 ((eq major-mode 'w3-mode)
7639 (setq cpltxt (if (and (buffer-name)
7640 (not (string-match "Untitled" (buffer-name))))
7641 (buffer-name)
7642 (url-view-url t))
7643 link (org-make-link (url-view-url t)))
7644 (org-store-link-props :type "w3" :url (url-view-url t)))
7646 ((eq major-mode 'w3m-mode)
7647 (setq cpltxt (or w3m-current-title w3m-current-url)
7648 link (org-make-link w3m-current-url))
7649 (org-store-link-props :type "w3m" :url (url-view-url t)))
7651 ((setq search (run-hook-with-args-until-success
7652 'org-create-file-search-functions))
7653 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7654 "::" search))
7655 (setq cpltxt (or description link)))
7657 ((eq major-mode 'image-mode)
7658 (setq cpltxt (concat "file:"
7659 (abbreviate-file-name buffer-file-name))
7660 link (org-make-link cpltxt))
7661 (org-store-link-props :type "image" :file buffer-file-name))
7663 ((eq major-mode 'dired-mode)
7664 ;; link to the file in the current line
7665 (setq cpltxt (concat "file:"
7666 (abbreviate-file-name
7667 (expand-file-name
7668 (dired-get-filename nil t))))
7669 link (org-make-link cpltxt)))
7671 ((and buffer-file-name (org-mode-p))
7672 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7673 (cond
7674 ((org-in-regexp "<<\\(.*?\\)>>")
7675 (setq cpltxt
7676 (concat "file:"
7677 (abbreviate-file-name buffer-file-name)
7678 "::" (match-string 1))
7679 link (org-make-link cpltxt)))
7680 ((and (featurep 'org-id)
7681 (or (eq org-link-to-org-use-id t)
7682 (and (eq org-link-to-org-use-id 'create-if-interactive)
7683 (interactive-p))
7684 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7685 (interactive-p)
7686 (not custom-id))
7687 (and org-link-to-org-use-id
7688 (condition-case nil
7689 (org-entry-get nil "ID")
7690 (error nil)))))
7691 ;; We can make a link using the ID.
7692 (setq link (condition-case nil
7693 (prog1 (org-id-store-link)
7694 (setq desc (plist-get org-store-link-plist
7695 :description)))
7696 (error
7697 ;; probably before first headline, link to file only
7698 (concat "file:"
7699 (abbreviate-file-name buffer-file-name))))))
7701 ;; Just link to current headline
7702 (setq cpltxt (concat "file:"
7703 (abbreviate-file-name buffer-file-name)))
7704 ;; Add a context search string
7705 (when (org-xor org-context-in-file-links arg)
7706 (setq txt (cond
7707 ((org-on-heading-p) nil)
7708 ((org-region-active-p)
7709 (buffer-substring (region-beginning) (region-end)))
7710 (t nil)))
7711 (when (or (null txt) (string-match "\\S-" txt))
7712 (setq cpltxt
7713 (concat cpltxt "::"
7714 (condition-case nil
7715 (org-make-org-heading-search-string txt)
7716 (error "")))
7717 desc (or (nth 4 (ignore-errors
7718 (org-heading-components))) "NONE"))))
7719 (if (string-match "::\\'" cpltxt)
7720 (setq cpltxt (substring cpltxt 0 -2)))
7721 (setq link (org-make-link cpltxt)))))
7723 ((buffer-file-name (buffer-base-buffer))
7724 ;; Just link to this file here.
7725 (setq cpltxt (concat "file:"
7726 (abbreviate-file-name
7727 (buffer-file-name (buffer-base-buffer)))))
7728 ;; Add a context string
7729 (when (org-xor org-context-in-file-links arg)
7730 (setq txt (if (org-region-active-p)
7731 (buffer-substring (region-beginning) (region-end))
7732 (buffer-substring (point-at-bol) (point-at-eol))))
7733 ;; Only use search option if there is some text.
7734 (when (string-match "\\S-" txt)
7735 (setq cpltxt
7736 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7737 desc "NONE")))
7738 (setq link (org-make-link cpltxt)))
7740 ((interactive-p)
7741 (error "Cannot link to a buffer which is not visiting a file"))
7743 (t (setq link nil)))
7745 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7746 (setq link (or link cpltxt)
7747 desc (or desc cpltxt))
7748 (if (equal desc "NONE") (setq desc nil))
7750 (if (and (or (interactive-p) executing-kbd-macro) link)
7751 (progn
7752 (setq org-stored-links
7753 (cons (list link desc) org-stored-links))
7754 (message "Stored: %s" (or desc link))
7755 (when custom-id
7756 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7757 "::#" custom-id))
7758 (setq org-stored-links
7759 (cons (list link desc) org-stored-links))))
7760 (and link (org-make-link-string link desc)))))
7762 (defun org-store-link-props (&rest plist)
7763 "Store link properties, extract names and addresses."
7764 (let (x adr)
7765 (when (setq x (plist-get plist :from))
7766 (setq adr (mail-extract-address-components x))
7767 (setq plist (plist-put plist :fromname (car adr)))
7768 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7769 (when (setq x (plist-get plist :to))
7770 (setq adr (mail-extract-address-components x))
7771 (setq plist (plist-put plist :toname (car adr)))
7772 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7773 (let ((from (plist-get plist :from))
7774 (to (plist-get plist :to)))
7775 (when (and from to org-from-is-user-regexp)
7776 (setq plist
7777 (plist-put plist :fromto
7778 (if (string-match org-from-is-user-regexp from)
7779 (concat "to %t")
7780 (concat "from %f"))))))
7781 (setq org-store-link-plist plist))
7783 (defun org-add-link-props (&rest plist)
7784 "Add these properties to the link property list."
7785 (let (key value)
7786 (while plist
7787 (setq key (pop plist) value (pop plist))
7788 (setq org-store-link-plist
7789 (plist-put org-store-link-plist key value)))))
7791 (defun org-email-link-description (&optional fmt)
7792 "Return the description part of an email link.
7793 This takes information from `org-store-link-plist' and formats it
7794 according to FMT (default from `org-email-link-description-format')."
7795 (setq fmt (or fmt org-email-link-description-format))
7796 (let* ((p org-store-link-plist)
7797 (to (plist-get p :toaddress))
7798 (from (plist-get p :fromaddress))
7799 (table
7800 (list
7801 (cons "%c" (plist-get p :fromto))
7802 (cons "%F" (plist-get p :from))
7803 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7804 (cons "%T" (plist-get p :to))
7805 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7806 (cons "%s" (plist-get p :subject))
7807 (cons "%m" (plist-get p :message-id)))))
7808 (when (string-match "%c" fmt)
7809 ;; Check if the user wrote this message
7810 (if (and org-from-is-user-regexp from to
7811 (save-match-data (string-match org-from-is-user-regexp from)))
7812 (setq fmt (replace-match "to %t" t t fmt))
7813 (setq fmt (replace-match "from %f" t t fmt))))
7814 (org-replace-escapes fmt table)))
7816 (defun org-make-org-heading-search-string (&optional string heading)
7817 "Make search string for STRING or current headline."
7818 (interactive)
7819 (let ((s (or string (org-get-heading))))
7820 (unless (and string (not heading))
7821 ;; We are using a headline, clean up garbage in there.
7822 (if (string-match org-todo-regexp s)
7823 (setq s (replace-match "" t t s)))
7824 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7825 (setq s (replace-match "" t t s)))
7826 (setq s (org-trim s))
7827 (if (string-match (concat "^\\(" org-quote-string "\\|"
7828 org-comment-string "\\)") s)
7829 (setq s (replace-match "" t t s)))
7830 (while (string-match org-ts-regexp s)
7831 (setq s (replace-match "" t t s))))
7832 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7833 (setq s (replace-match " " t t s)))
7834 (or string (setq s (concat "*" s))) ; Add * for headlines
7835 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7837 (defun org-make-link (&rest strings)
7838 "Concatenate STRINGS."
7839 (apply 'concat strings))
7841 (defun org-make-link-string (link &optional description)
7842 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7843 (unless (string-match "\\S-" link)
7844 (error "Empty link"))
7845 (when (and description
7846 (stringp description)
7847 (not (string-match "\\S-" description)))
7848 (setq description nil))
7849 (when (stringp description)
7850 ;; Remove brackets from the description, they are fatal.
7851 (while (string-match "\\[" description)
7852 (setq description (replace-match "{" t t description)))
7853 (while (string-match "\\]" description)
7854 (setq description (replace-match "}" t t description))))
7855 (when (equal (org-link-escape link) description)
7856 ;; No description needed, it is identical
7857 (setq description nil))
7858 (when (and (not description)
7859 (not (equal link (org-link-escape link))))
7860 (setq description (org-extract-attributes link)))
7861 (concat "[[" (org-link-escape link) "]"
7862 (if description (concat "[" description "]") "")
7863 "]"))
7865 (defconst org-link-escape-chars
7866 '((?\ . "%20")
7867 (?\[ . "%5B")
7868 (?\] . "%5D")
7869 (?\340 . "%E0") ; `a
7870 (?\342 . "%E2") ; ^a
7871 (?\347 . "%E7") ; ,c
7872 (?\350 . "%E8") ; `e
7873 (?\351 . "%E9") ; 'e
7874 (?\352 . "%EA") ; ^e
7875 (?\356 . "%EE") ; ^i
7876 (?\364 . "%F4") ; ^o
7877 (?\371 . "%F9") ; `u
7878 (?\373 . "%FB") ; ^u
7879 (?\; . "%3B")
7880 (?? . "%3F")
7881 (?= . "%3D")
7882 (?+ . "%2B")
7884 "Association list of escapes for some characters problematic in links.
7885 This is the list that is used for internal purposes.")
7887 (defvar org-url-encoding-use-url-hexify nil)
7889 (defconst org-link-escape-chars-browser
7890 '((?\ . "%20")) ; 32 for the SPC char
7891 "Association list of escapes for some characters problematic in links.
7892 This is the list that is used before handing over to the browser.")
7894 (defun org-link-escape (text &optional table)
7895 "Escape characters in TEXT that are problematic for links."
7896 (if org-url-encoding-use-url-hexify
7897 (url-hexify-string text)
7898 (setq table (or table org-link-escape-chars))
7899 (when text
7900 (let ((re (mapconcat (lambda (x) (regexp-quote
7901 (char-to-string (car x))))
7902 table "\\|")))
7903 (while (string-match re text)
7904 (setq text
7905 (replace-match
7906 (cdr (assoc (string-to-char (match-string 0 text))
7907 table))
7908 t t text)))
7909 text))))
7911 (defun org-link-unescape (text &optional table)
7912 "Reverse the action of `org-link-escape'."
7913 (if org-url-encoding-use-url-hexify
7914 (url-unhex-string text)
7915 (setq table (or table org-link-escape-chars))
7916 (when text
7917 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7918 table "\\|")))
7919 (while (string-match re text)
7920 (setq text
7921 (replace-match
7922 (char-to-string (car (rassoc (match-string 0 text) table)))
7923 t t text)))
7924 text))))
7926 (defun org-xor (a b)
7927 "Exclusive or."
7928 (if a (not b) b))
7930 (defun org-fixup-message-id-for-http (s)
7931 "Replace special characters in a message id, so it can be used in an http query."
7932 (while (string-match "<" s)
7933 (setq s (replace-match "%3C" t t s)))
7934 (while (string-match ">" s)
7935 (setq s (replace-match "%3E" t t s)))
7936 (while (string-match "@" s)
7937 (setq s (replace-match "%40" t t s)))
7940 ;;;###autoload
7941 (defun org-insert-link-global ()
7942 "Insert a link like Org-mode does.
7943 This command can be called in any mode to insert a link in Org-mode syntax."
7944 (interactive)
7945 (org-load-modules-maybe)
7946 (org-run-like-in-org-mode 'org-insert-link))
7948 (defun org-insert-link (&optional complete-file link-location)
7949 "Insert a link. At the prompt, enter the link.
7951 Completion can be used to insert any of the link protocol prefixes like
7952 http or ftp in use.
7954 The history can be used to select a link previously stored with
7955 `org-store-link'. When the empty string is entered (i.e. if you just
7956 press RET at the prompt), the link defaults to the most recently
7957 stored link. As SPC triggers completion in the minibuffer, you need to
7958 use M-SPC or C-q SPC to force the insertion of a space character.
7960 You will also be prompted for a description, and if one is given, it will
7961 be displayed in the buffer instead of the link.
7963 If there is already a link at point, this command will allow you to edit link
7964 and description parts.
7966 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7967 be selected using completion. The path to the file will be relative to the
7968 current directory if the file is in the current directory or a subdirectory.
7969 Otherwise, the link will be the absolute path as completed in the minibuffer
7970 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7971 option `org-link-file-path-type'.
7973 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7974 the current directory or below.
7976 With three \\[universal-argument] prefixes, negate the meaning of
7977 `org-keep-stored-link-after-insertion'.
7979 If `org-make-link-description-function' is non-nil, this function will be
7980 called with the link target, and the result will be the default
7981 link description.
7983 If the LINK-LOCATION parameter is non-nil, this value will be
7984 used as the link location instead of reading one interactively."
7985 (interactive "P")
7986 (let* ((wcf (current-window-configuration))
7987 (region (if (org-region-active-p)
7988 (buffer-substring (region-beginning) (region-end))))
7989 (remove (and region (list (region-beginning) (region-end))))
7990 (desc region)
7991 tmphist ; byte-compile incorrectly complains about this
7992 (link link-location)
7993 entry file all-prefixes)
7994 (cond
7995 (link-location) ; specified by arg, just use it.
7996 ((org-in-regexp org-bracket-link-regexp 1)
7997 ;; We do have a link at point, and we are going to edit it.
7998 (setq remove (list (match-beginning 0) (match-end 0)))
7999 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8000 (setq link (read-string "Link: "
8001 (org-link-unescape
8002 (org-match-string-no-properties 1)))))
8003 ((or (org-in-regexp org-angle-link-re)
8004 (org-in-regexp org-plain-link-re))
8005 ;; Convert to bracket link
8006 (setq remove (list (match-beginning 0) (match-end 0))
8007 link (read-string "Link: "
8008 (org-remove-angle-brackets (match-string 0)))))
8009 ((member complete-file '((4) (16)))
8010 ;; Completing read for file names.
8011 (setq link (org-file-complete-link complete-file)))
8013 ;; Read link, with completion for stored links.
8014 (with-output-to-temp-buffer "*Org Links*"
8015 (princ "Insert a link.
8016 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8017 (when org-stored-links
8018 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8019 (princ (mapconcat
8020 (lambda (x)
8021 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8022 (reverse org-stored-links) "\n"))))
8023 (let ((cw (selected-window)))
8024 (select-window (get-buffer-window "*Org Links*"))
8025 (setq truncate-lines t)
8026 (unless (pos-visible-in-window-p (point-max))
8027 (org-fit-window-to-buffer))
8028 (and (window-live-p cw) (select-window cw)))
8029 ;; Fake a link history, containing the stored links.
8030 (setq tmphist (append (mapcar 'car org-stored-links)
8031 org-insert-link-history))
8032 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8033 (mapcar 'car org-link-abbrev-alist)
8034 org-link-types))
8035 (unwind-protect
8036 (progn
8037 (setq link
8038 (let ((org-completion-use-ido nil)
8039 (org-completion-use-iswitchb nil))
8040 (org-completing-read
8041 "Link: "
8042 (append
8043 (mapcar (lambda (x) (list (concat x ":")))
8044 all-prefixes)
8045 (mapcar 'car org-stored-links))
8046 nil nil nil
8047 'tmphist
8048 (car (car org-stored-links)))))
8049 (if (not (string-match "\\S-" link))
8050 (error "No link selected"))
8051 (if (or (member link all-prefixes)
8052 (and (equal ":" (substring link -1))
8053 (member (substring link 0 -1) all-prefixes)
8054 (setq link (substring link 0 -1))))
8055 (setq link (org-link-try-special-completion link))))
8056 (set-window-configuration wcf)
8057 (kill-buffer "*Org Links*"))
8058 (setq entry (assoc link org-stored-links))
8059 (or entry (push link org-insert-link-history))
8060 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8061 (not org-keep-stored-link-after-insertion))
8062 (setq org-stored-links (delq (assoc link org-stored-links)
8063 org-stored-links)))
8064 (setq desc (or desc (nth 1 entry)))))
8066 (if (string-match org-plain-link-re link)
8067 ;; URL-like link, normalize the use of angular brackets.
8068 (setq link (org-make-link (org-remove-angle-brackets link))))
8070 ;; Check if we are linking to the current file with a search option
8071 ;; If yes, simplify the link by using only the search option.
8072 (when (and buffer-file-name
8073 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8074 (let* ((path (match-string 1 link))
8075 (case-fold-search nil)
8076 (search (match-string 2 link)))
8077 (save-match-data
8078 (if (equal (file-truename buffer-file-name) (file-truename path))
8079 ;; We are linking to this same file, with a search option
8080 (setq link search)))))
8082 ;; Check if we can/should use a relative path. If yes, simplify the link
8083 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8084 (let* ((type (match-string 1 link))
8085 (path (match-string 2 link))
8086 (origpath path)
8087 (case-fold-search nil))
8088 (cond
8089 ((or (eq org-link-file-path-type 'absolute)
8090 (equal complete-file '(16)))
8091 (setq path (abbreviate-file-name (expand-file-name path))))
8092 ((eq org-link-file-path-type 'noabbrev)
8093 (setq path (expand-file-name path)))
8094 ((eq org-link-file-path-type 'relative)
8095 (setq path (file-relative-name path)))
8097 (save-match-data
8098 (if (string-match (concat "^" (regexp-quote
8099 (file-name-as-directory
8100 (expand-file-name "."))))
8101 (expand-file-name path))
8102 ;; We are linking a file with relative path name.
8103 (setq path (substring (expand-file-name path)
8104 (match-end 0)))
8105 (setq path (abbreviate-file-name (expand-file-name path)))))))
8106 (setq link (concat type path))
8107 (if (equal desc origpath)
8108 (setq desc path))))
8110 (if org-make-link-description-function
8111 (setq desc (funcall org-make-link-description-function link desc)))
8113 (setq desc (read-string "Description: " desc))
8114 (unless (string-match "\\S-" desc) (setq desc nil))
8115 (if remove (apply 'delete-region remove))
8116 (insert (org-make-link-string link desc))))
8118 (defun org-link-try-special-completion (type)
8119 "If there is completion support for link type TYPE, offer it."
8120 (let ((fun (intern (concat "org-" type "-complete-link"))))
8121 (if (functionp fun)
8122 (funcall fun)
8123 (read-string "Link (no completion support): " (concat type ":")))))
8125 (defun org-file-complete-link (&optional arg)
8126 "Create a file link using completion."
8127 (let (file link)
8128 (setq file (read-file-name "File: "))
8129 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8130 (pwd1 (file-name-as-directory (abbreviate-file-name
8131 (expand-file-name ".")))))
8132 (cond
8133 ((equal arg '(16))
8134 (setq link (org-make-link
8135 "file:"
8136 (abbreviate-file-name (expand-file-name file)))))
8137 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8138 (setq link (org-make-link "file:" (match-string 1 file))))
8139 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8140 (expand-file-name file))
8141 (setq link (org-make-link
8142 "file:" (match-string 1 (expand-file-name file)))))
8143 (t (setq link (org-make-link "file:" file)))))
8144 link))
8146 (defun org-completing-read (&rest args)
8147 "Completing-read with SPACE being a normal character."
8148 (let ((minibuffer-local-completion-map
8149 (copy-keymap minibuffer-local-completion-map)))
8150 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8151 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8152 (apply 'org-icompleting-read args)))
8154 (defun org-completing-read-no-i (&rest args)
8155 (let (org-completion-use-ido org-completion-use-iswitchb)
8156 (apply 'org-completing-read args)))
8158 (defun org-iswitchb-completing-read (prompt choices &rest args)
8159 "Use iswitch as a completing-read replacement to choose from choices.
8160 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8161 from."
8162 (let* ((iswitchb-use-virtual-buffers nil)
8163 (iswitchb-make-buflist-hook
8164 (lambda ()
8165 (setq iswitchb-temp-buflist choices))))
8166 (iswitchb-read-buffer prompt)))
8168 (defun org-icompleting-read (&rest args)
8169 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8170 (org-without-partial-completion
8171 (if (and org-completion-use-ido
8172 (fboundp 'ido-completing-read)
8173 (boundp 'ido-mode) ido-mode
8174 (listp (second args)))
8175 (let ((ido-enter-matching-directory nil))
8176 (apply 'ido-completing-read (concat (car args))
8177 (if (consp (car (nth 1 args)))
8178 (mapcar (lambda (x) (car x)) (nth 1 args))
8179 (nth 1 args))
8180 (cddr args)))
8181 (if (and org-completion-use-iswitchb
8182 (boundp 'iswitchb-mode) iswitchb-mode
8183 (listp (second args)))
8184 (apply 'org-iswitchb-completing-read (concat (car args))
8185 (if (consp (car (nth 1 args)))
8186 (mapcar (lambda (x) (car x)) (nth 1 args))
8187 (nth 1 args))
8188 (cddr args))
8189 (apply 'completing-read args)))))
8191 (defun org-extract-attributes (s)
8192 "Extract the attributes cookie from a string and set as text property."
8193 (let (a attr (start 0) key value)
8194 (save-match-data
8195 (when (string-match "{{\\([^}]+\\)}}$" s)
8196 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8197 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8198 (setq key (match-string 1 a) value (match-string 2 a)
8199 start (match-end 0)
8200 attr (plist-put attr (intern key) value))))
8201 (org-add-props s nil 'org-attr attr))
8204 (defun org-extract-attributes-from-string (tag)
8205 (let (key value attr)
8206 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8207 (setq key (match-string 1 tag) value (match-string 2 tag)
8208 tag (replace-match "" t t tag)
8209 attr (plist-put attr (intern key) value)))
8210 (cons tag attr)))
8212 (defun org-attributes-to-string (plist)
8213 "Format a property list into an HTML attribute list."
8214 (let ((s "") key value)
8215 (while plist
8216 (setq key (pop plist) value (pop plist))
8217 (and value
8218 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8221 ;;; Opening/following a link
8223 (defvar org-link-search-failed nil)
8225 (defvar org-open-link-functions nil
8226 "Hook for functions finding a plain text link.
8227 These functions must take a single argument, the link content.
8228 They will be called for links that look like [[link text][description]]
8229 when LINK TEXT does not have a protocol like \"http:\" and does not look
8230 like a filename (e.g. \"./blue.png\").
8232 These functions will be called *before* Org attempts to resolve the
8233 link by doing text searches in the current buffer - so if you want a
8234 link \"[[target]]\" to still find \"<<target>>\", your function should
8235 handle this as a special case.
8237 When the function does handle the link, it must return a non-nil value.
8238 If it decides that it is not responsible for this link, it must return
8239 nil to indicate that that Org-mode can continue with other options
8240 like exact and fuzzy text search.")
8242 (defun org-next-link ()
8243 "Move forward to the next link.
8244 If the link is in hidden text, expose it."
8245 (interactive)
8246 (when (and org-link-search-failed (eq this-command last-command))
8247 (goto-char (point-min))
8248 (message "Link search wrapped back to beginning of buffer"))
8249 (setq org-link-search-failed nil)
8250 (let* ((pos (point))
8251 (ct (org-context))
8252 (a (assoc :link ct)))
8253 (if a (goto-char (nth 2 a)))
8254 (if (re-search-forward org-any-link-re nil t)
8255 (progn
8256 (goto-char (match-beginning 0))
8257 (if (org-invisible-p) (org-show-context)))
8258 (goto-char pos)
8259 (setq org-link-search-failed t)
8260 (error "No further link found"))))
8262 (defun org-previous-link ()
8263 "Move backward to the previous link.
8264 If the link is in hidden text, expose it."
8265 (interactive)
8266 (when (and org-link-search-failed (eq this-command last-command))
8267 (goto-char (point-max))
8268 (message "Link search wrapped back to end of buffer"))
8269 (setq org-link-search-failed nil)
8270 (let* ((pos (point))
8271 (ct (org-context))
8272 (a (assoc :link ct)))
8273 (if a (goto-char (nth 1 a)))
8274 (if (re-search-backward org-any-link-re nil t)
8275 (progn
8276 (goto-char (match-beginning 0))
8277 (if (org-invisible-p) (org-show-context)))
8278 (goto-char pos)
8279 (setq org-link-search-failed t)
8280 (error "No further link found"))))
8282 (defun org-translate-link (s)
8283 "Translate a link string if a translation function has been defined."
8284 (if (and org-link-translation-function
8285 (fboundp org-link-translation-function)
8286 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8287 (progn
8288 (setq s (funcall org-link-translation-function
8289 (match-string 1) (match-string 2)))
8290 (concat (car s) ":" (cdr s)))
8293 (defun org-translate-link-from-planner (type path)
8294 "Translate a link from Emacs Planner syntax so that Org can follow it.
8295 This is still an experimental function, your mileage may vary."
8296 (cond
8297 ((member type '("http" "https" "news" "ftp"))
8298 ;; standard Internet links are the same.
8299 nil)
8300 ((and (equal type "irc") (string-match "^//" path))
8301 ;; Planner has two / at the beginning of an irc link, we have 1.
8302 ;; We should have zero, actually....
8303 (setq path (substring path 1)))
8304 ((and (equal type "lisp") (string-match "^/" path))
8305 ;; Planner has a slash, we do not.
8306 (setq type "elisp" path (substring path 1)))
8307 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8308 ;; A typical message link. Planner has the id after the final slash,
8309 ;; we separate it with a hash mark
8310 (setq path (concat (match-string 1 path) "#"
8311 (org-remove-angle-brackets (match-string 2 path)))))
8313 (cons type path))
8315 (defun org-find-file-at-mouse (ev)
8316 "Open file link or URL at mouse."
8317 (interactive "e")
8318 (mouse-set-point ev)
8319 (org-open-at-point 'in-emacs))
8321 (defun org-open-at-mouse (ev)
8322 "Open file link or URL at mouse."
8323 (interactive "e")
8324 (mouse-set-point ev)
8325 (if (eq major-mode 'org-agenda-mode)
8326 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8327 (org-open-at-point))
8329 (defvar org-window-config-before-follow-link nil
8330 "The window configuration before following a link.
8331 This is saved in case the need arises to restore it.")
8333 (defvar org-open-link-marker (make-marker)
8334 "Marker pointing to the location where `org-open-at-point; was called.")
8336 ;;;###autoload
8337 (defun org-open-at-point-global ()
8338 "Follow a link like Org-mode does.
8339 This command can be called in any mode to follow a link that has
8340 Org-mode syntax."
8341 (interactive)
8342 (org-run-like-in-org-mode 'org-open-at-point))
8344 ;;;###autoload
8345 (defun org-open-link-from-string (s &optional arg reference-buffer)
8346 "Open a link in the string S, as if it was in Org-mode."
8347 (interactive "sLink: \nP")
8348 (let ((reference-buffer (or reference-buffer (current-buffer))))
8349 (with-temp-buffer
8350 (let ((org-inhibit-startup t))
8351 (org-mode)
8352 (insert s)
8353 (goto-char (point-min))
8354 (org-open-at-point arg reference-buffer)))))
8356 (defun org-open-at-point (&optional in-emacs reference-buffer)
8357 "Open link at or after point.
8358 If there is no link at point, this function will search forward up to
8359 the end of the current line.
8360 Normally, files will be opened by an appropriate application. If the
8361 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8362 With a double prefix argument, try to open outside of Emacs, in the
8363 application the system uses for this file type."
8364 (interactive "P")
8365 (org-load-modules-maybe)
8366 (move-marker org-open-link-marker (point))
8367 (setq org-window-config-before-follow-link (current-window-configuration))
8368 (org-remove-occur-highlights nil nil t)
8369 (cond
8370 ((and (org-on-heading-p)
8371 (not (org-in-regexp
8372 (concat org-plain-link-re "\\|"
8373 org-bracket-link-regexp "\\|"
8374 org-angle-link-re "\\|"
8375 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8376 (or (org-offer-links-in-entry in-emacs)
8377 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8378 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8379 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8380 (org-footnote-action))
8382 (let (type path link line search (pos (point)))
8383 (catch 'match
8384 (save-excursion
8385 (skip-chars-forward "^]\n\r")
8386 (when (org-in-regexp org-bracket-link-regexp 1)
8387 (setq link (org-extract-attributes
8388 (org-link-unescape (org-match-string-no-properties 1))))
8389 (while (string-match " *\n *" link)
8390 (setq link (replace-match " " t t link)))
8391 (setq link (org-link-expand-abbrev link))
8392 (cond
8393 ((or (file-name-absolute-p link)
8394 (string-match "^\\.\\.?/" link))
8395 (setq type "file" path link))
8396 ((string-match org-link-re-with-space3 link)
8397 (setq type (match-string 1 link) path (match-string 2 link)))
8398 (t (setq type "thisfile" path link)))
8399 (throw 'match t)))
8401 (when (get-text-property (point) 'org-linked-text)
8402 (setq type "thisfile"
8403 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8404 (1+ (point)) (point))
8405 path (buffer-substring
8406 (previous-single-property-change pos 'org-linked-text)
8407 (next-single-property-change pos 'org-linked-text)))
8408 (throw 'match t))
8410 (save-excursion
8411 (when (or (org-in-regexp org-angle-link-re)
8412 (org-in-regexp org-plain-link-re))
8413 (setq type (match-string 1) path (match-string 2))
8414 (throw 'match t)))
8415 (save-excursion
8416 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8417 (setq type "tags"
8418 path (match-string 1))
8419 (while (string-match ":" path)
8420 (setq path (replace-match "+" t t path)))
8421 (throw 'match t)))
8422 (when (org-in-regexp "<\\([^><\n]+\\)>")
8423 (setq type "tree-match"
8424 path (match-string 1))
8425 (throw 'match t)))
8426 (unless path
8427 (error "No link found"))
8429 ;; switch back to reference buffer
8430 ;; needed when if called in a temporary buffer through
8431 ;; org-open-link-from-string
8432 (with-current-buffer (or reference-buffer (current-buffer))
8434 ;; Remove any trailing spaces in path
8435 (if (string-match " +\\'" path)
8436 (setq path (replace-match "" t t path)))
8437 (if (and org-link-translation-function
8438 (fboundp org-link-translation-function))
8439 ;; Check if we need to translate the link
8440 (let ((tmp (funcall org-link-translation-function type path)))
8441 (setq type (car tmp) path (cdr tmp))))
8443 (cond
8445 ((assoc type org-link-protocols)
8446 (funcall (nth 1 (assoc type org-link-protocols)) path))
8448 ((equal type "mailto")
8449 (let ((cmd (car org-link-mailto-program))
8450 (args (cdr org-link-mailto-program)) args1
8451 (address path) (subject "") a)
8452 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8453 (setq address (match-string 1 path)
8454 subject (org-link-escape (match-string 2 path))))
8455 (while args
8456 (cond
8457 ((not (stringp (car args))) (push (pop args) args1))
8458 (t (setq a (pop args))
8459 (if (string-match "%a" a)
8460 (setq a (replace-match address t t a)))
8461 (if (string-match "%s" a)
8462 (setq a (replace-match subject t t a)))
8463 (push a args1))))
8464 (apply cmd (nreverse args1))))
8466 ((member type '("http" "https" "ftp" "news"))
8467 (browse-url (concat type ":" (org-link-escape
8468 path org-link-escape-chars-browser))))
8470 ((member type '("message"))
8471 (browse-url (concat type ":" path)))
8473 ((string= type "tags")
8474 (org-tags-view in-emacs path))
8476 ((string= type "tree-match")
8477 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8479 ((string= type "file")
8480 (if (string-match "::\\([0-9]+\\)\\'" path)
8481 (setq line (string-to-number (match-string 1 path))
8482 path (substring path 0 (match-beginning 0)))
8483 (if (string-match "::\\(.+\\)\\'" path)
8484 (setq search (match-string 1 path)
8485 path (substring path 0 (match-beginning 0)))))
8486 (if (string-match "[*?{]" (file-name-nondirectory path))
8487 (dired path)
8488 (org-open-file path in-emacs line search)))
8490 ((string= type "news")
8491 (require 'org-gnus)
8492 (org-gnus-follow-link path))
8494 ((string= type "shell")
8495 (let ((cmd path))
8496 (if (or (not org-confirm-shell-link-function)
8497 (funcall org-confirm-shell-link-function
8498 (format "Execute \"%s\" in shell? "
8499 (org-add-props cmd nil
8500 'face 'org-warning))))
8501 (progn
8502 (message "Executing %s" cmd)
8503 (shell-command cmd))
8504 (error "Abort"))))
8506 ((string= type "elisp")
8507 (let ((cmd path))
8508 (if (or (not org-confirm-elisp-link-function)
8509 (funcall org-confirm-elisp-link-function
8510 (format "Execute \"%s\" as elisp? "
8511 (org-add-props cmd nil
8512 'face 'org-warning))))
8513 (message "%s => %s" cmd
8514 (if (equal (string-to-char cmd) ?\()
8515 (eval (read cmd))
8516 (call-interactively (read cmd))))
8517 (error "Abort"))))
8519 ((and (string= type "thisfile")
8520 (run-hook-with-args-until-success
8521 'org-open-link-functions path)))
8523 ((string= type "thisfile")
8524 (if in-emacs
8525 (switch-to-buffer-other-window
8526 (org-get-buffer-for-internal-link (current-buffer)))
8527 (org-mark-ring-push))
8528 (let ((cmd `(org-link-search
8529 ,path
8530 ,(cond ((equal in-emacs '(4)) 'occur)
8531 ((equal in-emacs '(16)) 'org-occur)
8532 (t nil))
8533 ,pos)))
8534 (condition-case nil (eval cmd)
8535 (error (progn (widen) (eval cmd))))))
8538 (browse-url-at-point)))))))
8539 (move-marker org-open-link-marker nil)
8540 (run-hook-with-args 'org-follow-link-hook))
8542 (defun org-offer-links-in-entry (&optional nth zero)
8543 "Offer links in the current entry and follow the selected link.
8544 If there is only one link, follow it immediately as well.
8545 If NTH is an integer, immediately pick the NTH link found.
8546 If ZERO is a string, check also this string for a link, and if
8547 there is one, offer it as link number zero."
8548 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8549 "\\(" org-angle-link-re "\\)\\|"
8550 "\\(" org-plain-link-re "\\)"))
8551 (cnt ?0)
8552 (in-emacs (if (integerp nth) nil nth))
8553 have-zero end links link c)
8554 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8555 (push (match-string 0 zero) links)
8556 (setq cnt (1- cnt) have-zero t))
8557 (save-excursion
8558 (org-back-to-heading t)
8559 (setq end (save-excursion (outline-next-heading) (point)))
8560 (while (re-search-forward re end t)
8561 (push (match-string 0) links))
8562 (setq links (org-uniquify (reverse links))))
8564 (cond
8565 ((null links)
8566 (message "No links"))
8567 ((equal (length links) 1)
8568 (setq link (list (car links))))
8569 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8570 (setq link (nth (if have-zero nth (1- nth)) links)))
8571 (t ; we have to select a link
8572 (save-excursion
8573 (save-window-excursion
8574 (delete-other-windows)
8575 (with-output-to-temp-buffer "*Select Link*"
8576 (mapc (lambda (l)
8577 (if (not (string-match org-bracket-link-regexp l))
8578 (princ (format "[%c] %s\n" (incf cnt)
8579 (org-remove-angle-brackets l)))
8580 (if (match-end 3)
8581 (princ (format "[%c] %s (%s)\n" (incf cnt)
8582 (match-string 3 l) (match-string 1 l)))
8583 (princ (format "[%c] %s\n" (incf cnt)
8584 (match-string 1 l))))))
8585 links))
8586 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8587 (message "Select link to open, RET to open all:")
8588 (setq c (read-char-exclusive))
8589 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8590 (when (equal c ?q) (error "Abort"))
8591 (if (equal c ?\C-m)
8592 (setq link links)
8593 (setq nth (- c ?0))
8594 (if have-zero (setq nth (1+ nth)))
8595 (unless (and (integerp nth) (>= (length links) nth))
8596 (error "Invalid link selection"))
8597 (setq link (list (nth (1- nth) links))))))
8598 (if link
8599 (let ((buf (current-buffer)))
8600 (dolist (l link)
8601 (org-open-link-from-string l in-emacs buf))
8603 nil)))
8605 ;; Add special file links that specify the way of opening
8607 (org-add-link-type "file+sys" 'org-open-file-with-system)
8608 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8609 (defun org-open-file-with-system (path)
8610 "Open file at PATH using the system way of opeing it."
8611 (org-open-file path 'system))
8612 (defun org-open-file-with-emacs (path)
8613 "Open file at PATH in emacs."
8614 (org-open-file path 'emacs))
8615 (defun org-remove-file-link-modifiers ()
8616 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8617 (goto-char (point-min))
8618 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8619 (org-if-unprotected
8620 (replace-match "file:" t t))))
8621 (eval-after-load "org-exp"
8622 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8623 'org-remove-file-link-modifiers))
8625 ;;;; Time estimates
8627 (defun org-get-effort (&optional pom)
8628 "Get the effort estimate for the current entry."
8629 (org-entry-get pom org-effort-property))
8631 ;;; File search
8633 (defvar org-create-file-search-functions nil
8634 "List of functions to construct the right search string for a file link.
8635 These functions are called in turn with point at the location to
8636 which the link should point.
8638 A function in the hook should first test if it would like to
8639 handle this file type, for example by checking the major-mode or
8640 the file extension. If it decides not to handle this file, it
8641 should just return nil to give other functions a chance. If it
8642 does handle the file, it must return the search string to be used
8643 when following the link. The search string will be part of the
8644 file link, given after a double colon, and `org-open-at-point'
8645 will automatically search for it. If special measures must be
8646 taken to make the search successful, another function should be
8647 added to the companion hook `org-execute-file-search-functions',
8648 which see.
8650 A function in this hook may also use `setq' to set the variable
8651 `description' to provide a suggestion for the descriptive text to
8652 be used for this link when it gets inserted into an Org-mode
8653 buffer with \\[org-insert-link].")
8655 (defvar org-execute-file-search-functions nil
8656 "List of functions to execute a file search triggered by a link.
8658 Functions added to this hook must accept a single argument, the
8659 search string that was part of the file link, the part after the
8660 double colon. The function must first check if it would like to
8661 handle this search, for example by checking the major-mode or the
8662 file extension. If it decides not to handle this search, it
8663 should just return nil to give other functions a chance. If it
8664 does handle the search, it must return a non-nil value to keep
8665 other functions from trying.
8667 Each function can access the current prefix argument through the
8668 variable `current-prefix-argument'. Note that a single prefix is
8669 used to force opening a link in Emacs, so it may be good to only
8670 use a numeric or double prefix to guide the search function.
8672 In case this is needed, a function in this hook can also restore
8673 the window configuration before `org-open-at-point' was called using:
8675 (set-window-configuration org-window-config-before-follow-link)")
8677 (defun org-link-search (s &optional type avoid-pos)
8678 "Search for a link search option.
8679 If S is surrounded by forward slashes, it is interpreted as a
8680 regular expression. In org-mode files, this will create an `org-occur'
8681 sparse tree. In ordinary files, `occur' will be used to list matches.
8682 If the current buffer is in `dired-mode', grep will be used to search
8683 in all files. If AVOID-POS is given, ignore matches near that position."
8684 (let ((case-fold-search t)
8685 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8686 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8687 (append '(("") (" ") ("\t") ("\n"))
8688 org-emphasis-alist)
8689 "\\|") "\\)"))
8690 (pos (point))
8691 (pre nil) (post nil)
8692 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8693 (cond
8694 ;; First check if there are any special
8695 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8696 ;; Now try the builtin stuff
8697 ((and (equal (string-to-char s0) ?#)
8698 (> (length s0) 1)
8699 (save-excursion
8700 (goto-char (point-min))
8701 (and
8702 (re-search-forward
8703 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8704 (setq type 'dedicated
8705 pos (match-beginning 0))))
8706 ;; There is an exact target for this
8707 (goto-char pos)
8708 (org-back-to-heading t)))
8709 ((save-excursion
8710 (goto-char (point-min))
8711 (and
8712 (re-search-forward
8713 (concat "<<" (regexp-quote s0) ">>") nil t)
8714 (setq type 'dedicated
8715 pos (match-beginning 0))))
8716 ;; There is an exact target for this
8717 (goto-char pos))
8718 ((and (string-match "^(\\(.*\\))$" s0)
8719 (save-excursion
8720 (goto-char (point-min))
8721 (and
8722 (re-search-forward
8723 (concat "[^[]" (regexp-quote
8724 (format org-coderef-label-format
8725 (match-string 1 s0))))
8726 nil t)
8727 (setq type 'dedicated
8728 pos (1+ (match-beginning 0))))))
8729 ;; There is a coderef target for this
8730 (goto-char pos))
8731 ((string-match "^/\\(.*\\)/$" s)
8732 ;; A regular expression
8733 (cond
8734 ((org-mode-p)
8735 (org-occur (match-string 1 s)))
8736 ;;((eq major-mode 'dired-mode)
8737 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8738 (t (org-do-occur (match-string 1 s)))))
8740 ;; A normal search strings
8741 (when (equal (string-to-char s) ?*)
8742 ;; Anchor on headlines, post may include tags.
8743 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8744 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8745 s (substring s 1)))
8746 (remove-text-properties
8747 0 (length s)
8748 '(face nil mouse-face nil keymap nil fontified nil) s)
8749 ;; Make a series of regular expressions to find a match
8750 (setq words (org-split-string s "[ \n\r\t]+")
8752 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8753 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8754 "\\)" markers)
8755 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8756 re2a (concat "[ \t\r\n]" re2a_)
8757 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8758 re4 (concat "[^a-zA-Z_]" re4_)
8760 re1 (concat pre re2 post)
8761 re3 (concat pre (if pre re4_ re4) post)
8762 re5 (concat pre ".*" re4)
8763 re2 (concat pre re2)
8764 re2a (concat pre (if pre re2a_ re2a))
8765 re4 (concat pre (if pre re4_ re4))
8766 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8767 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8768 re5 "\\)"
8770 (cond
8771 ((eq type 'org-occur) (org-occur reall))
8772 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8773 (t (goto-char (point-min))
8774 (setq type 'fuzzy)
8775 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8776 (org-search-not-self 1 re1 nil t)
8777 (org-search-not-self 1 re2 nil t)
8778 (org-search-not-self 1 re2a nil t)
8779 (org-search-not-self 1 re3 nil t)
8780 (org-search-not-self 1 re4 nil t)
8781 (org-search-not-self 1 re5 nil t)
8783 (goto-char (match-beginning 1))
8784 (goto-char pos)
8785 (error "No match")))))
8787 ;; Normal string-search
8788 (goto-char (point-min))
8789 (if (search-forward s nil t)
8790 (goto-char (match-beginning 0))
8791 (error "No match"))))
8792 (and (org-mode-p) (org-show-context 'link-search))
8793 type))
8795 (defun org-search-not-self (group &rest args)
8796 "Execute `re-search-forward', but only accept matches that do not
8797 enclose the position of `org-open-link-marker'."
8798 (let ((m org-open-link-marker))
8799 (catch 'exit
8800 (while (apply 're-search-forward args)
8801 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8802 (goto-char (match-end group))
8803 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8804 (> (match-beginning 0) (marker-position m))
8805 (< (match-end 0) (marker-position m)))
8806 (save-match-data
8807 (or (not (org-in-regexp
8808 org-bracket-link-analytic-regexp 1))
8809 (not (match-end 4)) ; no description
8810 (and (<= (match-beginning 4) (point))
8811 (>= (match-end 4) (point))))))
8812 (throw 'exit (point))))))))
8814 (defun org-get-buffer-for-internal-link (buffer)
8815 "Return a buffer to be used for displaying the link target of internal links."
8816 (cond
8817 ((not org-display-internal-link-with-indirect-buffer)
8818 buffer)
8819 ((string-match "(Clone)$" (buffer-name buffer))
8820 (message "Buffer is already a clone, not making another one")
8821 ;; we also do not modify visibility in this case
8822 buffer)
8823 (t ; make a new indirect buffer for displaying the link
8824 (let* ((bn (buffer-name buffer))
8825 (ibn (concat bn "(Clone)"))
8826 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8827 (with-current-buffer ib (org-overview))
8828 ib))))
8830 (defun org-do-occur (regexp &optional cleanup)
8831 "Call the Emacs command `occur'.
8832 If CLEANUP is non-nil, remove the printout of the regular expression
8833 in the *Occur* buffer. This is useful if the regex is long and not useful
8834 to read."
8835 (occur regexp)
8836 (when cleanup
8837 (let ((cwin (selected-window)) win beg end)
8838 (when (setq win (get-buffer-window "*Occur*"))
8839 (select-window win))
8840 (goto-char (point-min))
8841 (when (re-search-forward "match[a-z]+" nil t)
8842 (setq beg (match-end 0))
8843 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8844 (setq end (1- (match-beginning 0)))))
8845 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8846 (goto-char (point-min))
8847 (select-window cwin))))
8849 ;;; The mark ring for links jumps
8851 (defvar org-mark-ring nil
8852 "Mark ring for positions before jumps in Org-mode.")
8853 (defvar org-mark-ring-last-goto nil
8854 "Last position in the mark ring used to go back.")
8855 ;; Fill and close the ring
8856 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8857 (loop for i from 1 to org-mark-ring-length do
8858 (push (make-marker) org-mark-ring))
8859 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8860 org-mark-ring)
8862 (defun org-mark-ring-push (&optional pos buffer)
8863 "Put the current position or POS into the mark ring and rotate it."
8864 (interactive)
8865 (setq pos (or pos (point)))
8866 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8867 (move-marker (car org-mark-ring)
8868 (or pos (point))
8869 (or buffer (current-buffer)))
8870 (message "%s"
8871 (substitute-command-keys
8872 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8874 (defun org-mark-ring-goto (&optional n)
8875 "Jump to the previous position in the mark ring.
8876 With prefix arg N, jump back that many stored positions. When
8877 called several times in succession, walk through the entire ring.
8878 Org-mode commands jumping to a different position in the current file,
8879 or to another Org-mode file, automatically push the old position
8880 onto the ring."
8881 (interactive "p")
8882 (let (p m)
8883 (if (eq last-command this-command)
8884 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8885 (setq p org-mark-ring))
8886 (setq org-mark-ring-last-goto p)
8887 (setq m (car p))
8888 (switch-to-buffer (marker-buffer m))
8889 (goto-char m)
8890 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8892 (defun org-remove-angle-brackets (s)
8893 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8894 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8896 (defun org-add-angle-brackets (s)
8897 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8898 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8900 (defun org-remove-double-quotes (s)
8901 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8902 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8905 ;;; Following specific links
8907 (defun org-follow-timestamp-link ()
8908 (cond
8909 ((org-at-date-range-p t)
8910 (let ((org-agenda-start-on-weekday)
8911 (t1 (match-string 1))
8912 (t2 (match-string 2)))
8913 (setq t1 (time-to-days (org-time-string-to-time t1))
8914 t2 (time-to-days (org-time-string-to-time t2)))
8915 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8916 ((org-at-timestamp-p t)
8917 (org-agenda-list nil (time-to-days (org-time-string-to-time
8918 (substring (match-string 1) 0 10)))
8920 (t (error "This should not happen"))))
8923 ;;; Following file links
8924 (defvar org-wait nil)
8925 (defun org-open-file (path &optional in-emacs line search)
8926 "Open the file at PATH.
8927 First, this expands any special file name abbreviations. Then the
8928 configuration variable `org-file-apps' is checked if it contains an
8929 entry for this file type, and if yes, the corresponding command is launched.
8931 If no application is found, Emacs simply visits the file.
8933 With optional prefix argument IN-EMACS, Emacs will visit the file.
8934 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8935 and to use an external application to visit the file.
8937 Optional LINE specifies a line to go to, optional SEARCH a string to
8938 search for. If LINE or SEARCH is given, the file will always be
8939 opened in Emacs.
8940 If the file does not exist, an error is thrown."
8941 (setq in-emacs (or in-emacs line search))
8942 (let* ((file (if (equal path "")
8943 buffer-file-name
8944 (substitute-in-file-name (expand-file-name path))))
8945 (apps (append org-file-apps (org-default-apps)))
8946 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8947 (dirp (if remp nil (file-directory-p file)))
8948 (file (if (and dirp org-open-directory-means-index-dot-org)
8949 (concat (file-name-as-directory file) "index.org")
8950 file))
8951 (a-m-a-p (assq 'auto-mode apps))
8952 (dfile (downcase file))
8953 (old-buffer (current-buffer))
8954 (old-pos (point))
8955 (old-mode major-mode)
8956 ext cmd)
8957 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8958 (setq ext (match-string 1 dfile))
8959 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8960 (setq ext (match-string 1 dfile))))
8961 (cond
8962 ((member in-emacs '((16) system))
8963 (setq cmd (cdr (assoc 'system apps))))
8964 (in-emacs (setq cmd 'emacs))
8966 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8967 (and dirp (cdr (assoc 'directory apps)))
8968 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8969 'string-match)
8970 (cdr (assoc ext apps))
8971 (cdr (assoc t apps))))))
8972 (when (eq cmd 'system)
8973 (setq cmd (cdr (assoc 'system apps))))
8974 (when (eq cmd 'default)
8975 (setq cmd (cdr (assoc t apps))))
8976 (when (eq cmd 'mailcap)
8977 (require 'mailcap)
8978 (mailcap-parse-mailcaps)
8979 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8980 (command (mailcap-mime-info mime-type)))
8981 (if (stringp command)
8982 (setq cmd command)
8983 (setq cmd 'emacs))))
8984 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8985 (not (file-exists-p file))
8986 (not org-open-non-existing-files))
8987 (error "No such file: %s" file))
8988 (cond
8989 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8990 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8991 (while (string-match "['\"]%s['\"]" cmd)
8992 (setq cmd (replace-match "%s" t t cmd)))
8993 (while (string-match "%s" cmd)
8994 (setq cmd (replace-match
8995 (save-match-data
8996 (shell-quote-argument
8997 (convert-standard-filename file)))
8998 t t cmd)))
8999 (save-window-excursion
9000 (start-process-shell-command cmd nil cmd)
9001 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9003 ((or (stringp cmd)
9004 (eq cmd 'emacs))
9005 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9006 (widen)
9007 (if line (org-goto-line line)
9008 (if search (org-link-search search))))
9009 ((consp cmd)
9010 (let ((file (convert-standard-filename file)))
9011 (eval cmd)))
9012 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9013 (and (org-mode-p) (eq old-mode 'org-mode)
9014 (or (not (equal old-buffer (current-buffer)))
9015 (not (equal old-pos (point))))
9016 (org-mark-ring-push old-pos old-buffer))))
9018 (defun org-default-apps ()
9019 "Return the default applications for this operating system."
9020 (cond
9021 ((eq system-type 'darwin)
9022 org-file-apps-defaults-macosx)
9023 ((eq system-type 'windows-nt)
9024 org-file-apps-defaults-windowsnt)
9025 (t org-file-apps-defaults-gnu)))
9027 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9028 "Convert extensions to regular expressions in the cars of LIST.
9029 Also, weed out any non-string entries, because the return value is used
9030 only for regexp matching.
9031 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9032 point to the symbol `emacs', indicating that the file should
9033 be opened in Emacs."
9034 (append
9035 (delq nil
9036 (mapcar (lambda (x)
9037 (if (not (stringp (car x)))
9039 (if (string-match "\\W" (car x))
9041 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9042 list))
9043 (if add-auto-mode
9044 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9046 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9047 (defun org-file-remote-p (file)
9048 "Test whether FILE specifies a location on a remote system.
9049 Return non-nil if the location is indeed remote.
9051 For example, the filename \"/user@host:/foo\" specifies a location
9052 on the system \"/user@host:\"."
9053 (cond ((fboundp 'file-remote-p)
9054 (file-remote-p file))
9055 ((fboundp 'tramp-handle-file-remote-p)
9056 (tramp-handle-file-remote-p file))
9057 ((and (boundp 'ange-ftp-name-format)
9058 (string-match (car ange-ftp-name-format) file))
9060 (t nil)))
9063 ;;;; Refiling
9065 (defun org-get-org-file ()
9066 "Read a filename, with default directory `org-directory'."
9067 (let ((default (or org-default-notes-file remember-data-file)))
9068 (read-file-name (format "File name [%s]: " default)
9069 (file-name-as-directory org-directory)
9070 default)))
9072 (defun org-notes-order-reversed-p ()
9073 "Check if the current file should receive notes in reversed order."
9074 (cond
9075 ((not org-reverse-note-order) nil)
9076 ((eq t org-reverse-note-order) t)
9077 ((not (listp org-reverse-note-order)) nil)
9078 (t (catch 'exit
9079 (let ((all org-reverse-note-order)
9080 entry)
9081 (while (setq entry (pop all))
9082 (if (string-match (car entry) buffer-file-name)
9083 (throw 'exit (cdr entry))))
9084 nil)))))
9086 (defvar org-refile-target-table nil
9087 "The list of refile targets, created by `org-refile'.")
9089 (defvar org-agenda-new-buffers nil
9090 "Buffers created to visit agenda files.")
9092 (defun org-get-refile-targets (&optional default-buffer)
9093 "Produce a table with refile targets."
9094 (let ((case-fold-search nil)
9095 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9096 (entries (or org-refile-targets '((nil . (:level . 1)))))
9097 targets txt re files f desc descre fast-path-p level pos0)
9098 (message "Getting targets...")
9099 (with-current-buffer (or default-buffer (current-buffer))
9100 (while (setq entry (pop entries))
9101 (setq files (car entry) desc (cdr entry))
9102 (setq fast-path-p nil)
9103 (cond
9104 ((null files) (setq files (list (current-buffer))))
9105 ((eq files 'org-agenda-files)
9106 (setq files (org-agenda-files 'unrestricted)))
9107 ((and (symbolp files) (fboundp files))
9108 (setq files (funcall files)))
9109 ((and (symbolp files) (boundp files))
9110 (setq files (symbol-value files))))
9111 (if (stringp files) (setq files (list files)))
9112 (cond
9113 ((eq (car desc) :tag)
9114 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9115 ((eq (car desc) :todo)
9116 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9117 ((eq (car desc) :regexp)
9118 (setq descre (cdr desc)))
9119 ((eq (car desc) :level)
9120 (setq descre (concat "^\\*\\{" (number-to-string
9121 (if org-odd-levels-only
9122 (1- (* 2 (cdr desc)))
9123 (cdr desc)))
9124 "\\}[ \t]")))
9125 ((eq (car desc) :maxlevel)
9126 (setq fast-path-p t)
9127 (setq descre (concat "^\\*\\{1," (number-to-string
9128 (if org-odd-levels-only
9129 (1- (* 2 (cdr desc)))
9130 (cdr desc)))
9131 "\\}[ \t]")))
9132 (t (error "Bad refiling target description %s" desc)))
9133 (while (setq f (pop files))
9134 (with-current-buffer
9135 (if (bufferp f) f (org-get-agenda-file-buffer f))
9136 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9137 (setq f (and f (expand-file-name f)))
9138 (if (eq org-refile-use-outline-path 'file)
9139 (push (list (file-name-nondirectory f) f nil nil) targets))
9140 (save-excursion
9141 (save-restriction
9142 (widen)
9143 (goto-char (point-min))
9144 (while (re-search-forward descre nil t)
9145 (goto-char (setq pos0 (point-at-bol)))
9146 (catch 'next
9147 (when org-refile-target-verify-function
9148 (save-match-data
9149 (or (funcall org-refile-target-verify-function)
9150 (throw 'next t))))
9151 (when (looking-at org-complex-heading-regexp)
9152 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9153 txt (org-link-display-format (match-string 4))
9154 re (concat "^" (regexp-quote
9155 (buffer-substring (match-beginning 1)
9156 (match-end 4)))))
9157 (if (match-end 5) (setq re (concat re "[ \t]+"
9158 (regexp-quote
9159 (match-string 5)))))
9160 (setq re (concat re "[ \t]*$"))
9161 (when org-refile-use-outline-path
9162 (setq txt (mapconcat 'org-protect-slash
9163 (append
9164 (if (eq org-refile-use-outline-path 'file)
9165 (list (file-name-nondirectory
9166 (buffer-file-name (buffer-base-buffer))))
9167 (if (eq org-refile-use-outline-path 'full-file-path)
9168 (list (buffer-file-name (buffer-base-buffer)))))
9169 (org-get-outline-path fast-path-p level txt)
9170 (list txt))
9171 "/")))
9172 (push (list txt f re (point)) targets)))
9173 (when (= (point) pos0)
9174 ;; verification function has not moved point
9175 (goto-char (point-at-eol))))))))))
9176 (message "Getting targets...done")
9177 (nreverse targets)))
9179 (defun org-protect-slash (s)
9180 (while (string-match "/" s)
9181 (setq s (replace-match "\\" t t s)))
9184 (defvar org-olpa (make-vector 20 nil))
9186 (defun org-get-outline-path (&optional fastp level heading)
9187 "Return the outline path to the current entry, as a list.
9188 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9189 routine which makes outline path derivations for an entire file,
9190 avoiding backtracing."
9191 (if fastp
9192 (progn
9193 (if (> level 19)
9194 (error "Outline path failure, more than 19 levels."))
9195 (loop for i from level upto 19 do
9196 (aset org-olpa i nil))
9197 (prog1
9198 (delq nil (append org-olpa nil))
9199 (aset org-olpa level heading)))
9200 (let (rtn case-fold-search)
9201 (save-excursion
9202 (save-restriction
9203 (widen)
9204 (while (org-up-heading-safe)
9205 (when (looking-at org-complex-heading-regexp)
9206 (push (org-match-string-no-properties 4) rtn)))
9207 rtn)))))
9209 (defun org-format-outline-path (path &optional width prefix)
9210 "Format the outlie path PATH for display.
9211 Width is the maximum number of characters that is available.
9212 Prefix is a prefix to be included in the returned string,
9213 such as the file name."
9214 (setq width (or width 79))
9215 (if prefix (setq width (- width (length prefix))))
9216 (if (not path)
9217 (or prefix "")
9218 (let* ((nsteps (length path))
9219 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9220 (maxwidth (if (<= total-width width)
9221 10000 ;; everything fits
9222 ;; we need to shorten the level headings
9223 (/ (- width nsteps) nsteps)))
9224 (org-odd-levels-only nil)
9225 (n 0)
9226 (total (1+ (length prefix))))
9227 (setq maxwidth (max maxwidth 10))
9228 (concat prefix
9229 (mapconcat
9230 (lambda (h)
9231 (setq n (1+ n))
9232 (if (and (= n nsteps) (< maxwidth 10000))
9233 (setq maxwidth (- total-width total)))
9234 (if (< (length h) maxwidth)
9235 (progn (setq total (+ total (length h) 1)) h)
9236 (setq h (substring h 0 (- maxwidth 2))
9237 total (+ total maxwidth 1))
9238 (if (string-match "[ \t]+\\'" h)
9239 (setq h (substring h 0 (match-beginning 0))))
9240 (setq h (concat h "..")))
9241 (org-add-props h nil 'face
9242 (nth (% (1- n) org-n-level-faces)
9243 org-level-faces))
9245 path "/")))))
9247 (defun org-display-outline-path (&optional file current)
9248 "Display the current outline path in the echo area."
9249 (interactive "P")
9250 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9251 (case-fold-search nil)
9252 (path (and (org-mode-p) (org-get-outline-path))))
9253 (if current (setq path (append path
9254 (save-excursion
9255 (org-back-to-heading t)
9256 (if (looking-at org-complex-heading-regexp)
9257 (list (match-string 4)))))))
9258 (message "%s"
9259 (org-format-outline-path
9260 path
9261 (1- (frame-width))
9262 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9264 (defvar org-refile-history nil
9265 "History for refiling operations.")
9267 (defvar org-after-refile-insert-hook nil
9268 "Hook run after `org-refile' has inserted its stuff at the new location.
9269 Note that this is still *before* the stuff will be removed from
9270 the *old* location.")
9272 (defun org-refile (&optional goto default-buffer rfloc)
9273 "Move the entry at point to another heading.
9274 The list of target headings is compiled using the information in
9275 `org-refile-targets', which see. This list is created before each use
9276 and will therefore always be up-to-date.
9278 At the target location, the entry is filed as a subitem of the target heading.
9279 Depending on `org-reverse-note-order', the new subitem will either be the
9280 first or the last subitem.
9282 If there is an active region, all entries in that region will be moved.
9283 However, the region must fulfil the requirement that the first heading
9284 is the first one sets the top-level of the moved text - at most siblings
9285 below it are allowed.
9287 With prefix arg GOTO, the command will only visit the target location,
9288 not actually move anything.
9289 With a double prefix `C-u C-u', go to the location where the last refiling
9290 operation has put the subtree.
9291 With a prefix argument of `2', refile to the running clock.
9293 RFLOC can be a refile location obtained in a different way.
9295 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9296 (interactive "P")
9297 (let* ((cbuf (current-buffer))
9298 (regionp (org-region-active-p))
9299 (region-start (and regionp (region-beginning)))
9300 (region-end (and regionp (region-end)))
9301 (region-length (and regionp (- region-end region-start)))
9302 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9303 pos it nbuf file re level reversed)
9304 (setq last-command nil)
9305 (when regionp
9306 (goto-char region-start)
9307 (or (bolp) (goto-char (point-at-bol)))
9308 (setq region-start (point))
9309 (unless (org-kill-is-subtree-p
9310 (buffer-substring region-start region-end))
9311 (error "The region is not a (sequence of) subtree(s)")))
9312 (if (equal goto '(16))
9313 (org-refile-goto-last-stored)
9314 (when (or
9315 (and (equal goto 2)
9316 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9317 (prog1
9318 (setq it (list (or org-clock-heading "running clock")
9319 (buffer-file-name
9320 (marker-buffer org-clock-hd-marker))
9322 (marker-position org-clock-hd-marker)))
9323 (setq goto nil)))
9324 (setq it (or rfloc
9325 (save-excursion
9326 (org-refile-get-location
9327 (if goto "Goto: " "Refile to: ") default-buffer
9328 org-refile-allow-creating-parent-nodes)))))
9329 (setq file (nth 1 it)
9330 re (nth 2 it)
9331 pos (nth 3 it))
9332 (if (and (not goto)
9334 (equal (buffer-file-name) file)
9335 (if regionp
9336 (and (>= pos region-start)
9337 (<= pos region-end))
9338 (and (>= pos (point))
9339 (< pos (save-excursion
9340 (org-end-of-subtree t t))))))
9341 (error "Cannot refile to position inside the tree or region"))
9343 (setq nbuf (or (find-buffer-visiting file)
9344 (find-file-noselect file)))
9345 (if goto
9346 (progn
9347 (switch-to-buffer nbuf)
9348 (goto-char pos)
9349 (org-show-context 'org-goto))
9350 (if regionp
9351 (progn
9352 (org-kill-new (buffer-substring region-start region-end))
9353 (org-save-markers-in-region region-start region-end))
9354 (org-copy-subtree 1 nil t))
9355 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9356 (find-file-noselect file)))
9357 (setq reversed (org-notes-order-reversed-p))
9358 (save-excursion
9359 (save-restriction
9360 (widen)
9361 (if pos
9362 (progn
9363 (goto-char pos)
9364 (looking-at outline-regexp)
9365 (setq level (org-get-valid-level (funcall outline-level) 1))
9366 (goto-char
9367 (if reversed
9368 (or (outline-next-heading) (point-max))
9369 (or (save-excursion (org-get-next-sibling))
9370 (org-end-of-subtree t t)
9371 (point-max)))))
9372 (setq level 1)
9373 (if (not reversed)
9374 (goto-char (point-max))
9375 (goto-char (point-min))
9376 (or (outline-next-heading) (goto-char (point-max)))))
9377 (if (not (bolp)) (newline))
9378 (bookmark-set "org-refile-last-stored")
9379 (org-paste-subtree level)
9380 (if (fboundp 'deactivate-mark) (deactivate-mark))
9381 (run-hooks 'org-after-refile-insert-hook))))
9382 (if regionp
9383 (delete-region (point) (+ (point) region-length))
9384 (org-cut-subtree))
9385 (when (featurep 'org-inlinetask)
9386 (org-inlinetask-remove-END-maybe))
9387 (setq org-markers-to-move nil)
9388 (message "Refiled to \"%s\"" (car it))))))
9389 (org-reveal))
9391 (defun org-refile-goto-last-stored ()
9392 "Go to the location where the last refile was stored."
9393 (interactive)
9394 (bookmark-jump "org-refile-last-stored")
9395 (message "This is the location of the last refile"))
9397 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9398 "Prompt the user for a refile location, using PROMPT."
9399 (let ((org-refile-targets org-refile-targets)
9400 (org-refile-use-outline-path org-refile-use-outline-path))
9401 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9402 (unless org-refile-target-table
9403 (error "No refile targets"))
9404 (let* ((cbuf (current-buffer))
9405 (partial-completion-mode nil)
9406 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9407 (cfunc (if (and org-refile-use-outline-path
9408 org-outline-path-complete-in-steps)
9409 'org-olpath-completing-read
9410 'org-icompleting-read))
9411 (extra (if org-refile-use-outline-path "/" ""))
9412 (filename (and cfn (expand-file-name cfn)))
9413 (tbl (mapcar
9414 (lambda (x)
9415 (if (and (not (member org-refile-use-outline-path
9416 '(file full-file-path)))
9417 (not (equal filename (nth 1 x))))
9418 (cons (concat (car x) extra " ("
9419 (file-name-nondirectory (nth 1 x)) ")")
9420 (cdr x))
9421 (cons (concat (car x) extra) (cdr x))))
9422 org-refile-target-table))
9423 (completion-ignore-case t)
9424 pa answ parent-target child parent old-hist)
9425 (setq old-hist org-refile-history)
9426 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9427 nil 'org-refile-history))
9428 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9429 (if pa
9430 (progn
9431 (when (or (not org-refile-history)
9432 (not (eq old-hist org-refile-history))
9433 (not (equal (car pa) (car org-refile-history))))
9434 (setq org-refile-history
9435 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9436 org-refile-history
9437 (cdr org-refile-history))))
9438 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9439 (pop org-refile-history)))
9441 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9442 (setq parent (match-string 1 answ)
9443 child (match-string 2 answ))
9444 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9445 (when (and parent-target
9446 (or (eq new-nodes t)
9447 (and (eq new-nodes 'confirm)
9448 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9449 (org-refile-new-child parent-target child))))))
9451 (defun org-refile-new-child (parent-target child)
9452 "Use refile target PARENT-TARGET to add new CHILD below it."
9453 (unless parent-target
9454 (error "Cannot find parent for new node"))
9455 (let ((file (nth 1 parent-target))
9456 (pos (nth 3 parent-target))
9457 level)
9458 (with-current-buffer (or (find-buffer-visiting file)
9459 (find-file-noselect file))
9460 (save-excursion
9461 (save-restriction
9462 (widen)
9463 (if pos
9464 (goto-char pos)
9465 (goto-char (point-max))
9466 (if (not (bolp)) (newline)))
9467 (when (looking-at outline-regexp)
9468 (setq level (funcall outline-level))
9469 (org-end-of-subtree t t))
9470 (org-back-over-empty-lines)
9471 (insert "\n" (make-string
9472 (if pos (org-get-valid-level level 1) 1) ?*)
9473 " " child "\n")
9474 (beginning-of-line 0)
9475 (list (concat (car parent-target) "/" child) file "" (point)))))))
9477 (defun org-olpath-completing-read (prompt collection &rest args)
9478 "Read an outline path like a file name."
9479 (let ((thetable collection)
9480 (org-completion-use-ido nil) ; does not work with ido.
9481 (org-completion-use-iswitchb nil)) ; or iswitchb
9482 (apply
9483 'org-icompleting-read prompt
9484 (lambda (string predicate &optional flag)
9485 (let (rtn r f (l (length string)))
9486 (cond
9487 ((eq flag nil)
9488 ;; try completion
9489 (try-completion string thetable))
9490 ((eq flag t)
9491 ;; all-completions
9492 (setq rtn (all-completions string thetable predicate))
9493 (mapcar
9494 (lambda (x)
9495 (setq r (substring x l))
9496 (if (string-match " ([^)]*)$" x)
9497 (setq f (match-string 0 x))
9498 (setq f ""))
9499 (if (string-match "/" r)
9500 (concat string (substring r 0 (match-end 0)) f)
9502 rtn))
9503 ((eq flag 'lambda)
9504 ;; exact match?
9505 (assoc string thetable)))
9507 args)))
9509 ;;;; Dynamic blocks
9511 (defun org-find-dblock (name)
9512 "Find the first dynamic block with name NAME in the buffer.
9513 If not found, stay at current position and return nil."
9514 (let (pos)
9515 (save-excursion
9516 (goto-char (point-min))
9517 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9518 nil t)
9519 (match-beginning 0))))
9520 (if pos (goto-char pos))
9521 pos))
9523 (defconst org-dblock-start-re
9524 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9525 "Matches the start line of a dynamic block, with parameters.")
9527 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9528 "Matches the end of a dynamic block.")
9530 (defun org-create-dblock (plist)
9531 "Create a dynamic block section, with parameters taken from PLIST.
9532 PLIST must contain a :name entry which is used as name of the block."
9533 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9534 (end-of-line 1)
9535 (newline))
9536 (let ((col (current-column))
9537 (name (plist-get plist :name)))
9538 (insert "#+BEGIN: " name)
9539 (while plist
9540 (if (eq (car plist) :name)
9541 (setq plist (cddr plist))
9542 (insert " " (prin1-to-string (pop plist)))))
9543 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9544 (beginning-of-line -2)))
9546 (defun org-prepare-dblock ()
9547 "Prepare dynamic block for refresh.
9548 This empties the block, puts the cursor at the insert position and returns
9549 the property list including an extra property :name with the block name."
9550 (unless (looking-at org-dblock-start-re)
9551 (error "Not at a dynamic block"))
9552 (let* ((begdel (1+ (match-end 0)))
9553 (name (org-no-properties (match-string 1)))
9554 (params (append (list :name name)
9555 (read (concat "(" (match-string 3) ")")))))
9556 (save-excursion
9557 (beginning-of-line 1)
9558 (skip-chars-forward " \t")
9559 (setq params (plist-put params :indentation-column (current-column))))
9560 (unless (re-search-forward org-dblock-end-re nil t)
9561 (error "Dynamic block not terminated"))
9562 (setq params
9563 (append params
9564 (list :content (buffer-substring
9565 begdel (match-beginning 0)))))
9566 (delete-region begdel (match-beginning 0))
9567 (goto-char begdel)
9568 (open-line 1)
9569 params))
9571 (defun org-map-dblocks (&optional command)
9572 "Apply COMMAND to all dynamic blocks in the current buffer.
9573 If COMMAND is not given, use `org-update-dblock'."
9574 (let ((cmd (or command 'org-update-dblock))
9575 pos)
9576 (save-excursion
9577 (goto-char (point-min))
9578 (while (re-search-forward org-dblock-start-re nil t)
9579 (goto-char (setq pos (match-beginning 0)))
9580 (condition-case nil
9581 (funcall cmd)
9582 (error (message "Error during update of dynamic block")))
9583 (goto-char pos)
9584 (unless (re-search-forward org-dblock-end-re nil t)
9585 (error "Dynamic block not terminated"))))))
9587 (defun org-dblock-update (&optional arg)
9588 "User command for updating dynamic blocks.
9589 Update the dynamic block at point. With prefix ARG, update all dynamic
9590 blocks in the buffer."
9591 (interactive "P")
9592 (if arg
9593 (org-update-all-dblocks)
9594 (or (looking-at org-dblock-start-re)
9595 (org-beginning-of-dblock))
9596 (org-update-dblock)))
9598 (defun org-update-dblock ()
9599 "Update the dynamic block at point
9600 This means to empty the block, parse for parameters and then call
9601 the correct writing function."
9602 (save-window-excursion
9603 (let* ((pos (point))
9604 (line (org-current-line))
9605 (params (org-prepare-dblock))
9606 (name (plist-get params :name))
9607 (indent (plist-get params :indentation-column))
9608 (cmd (intern (concat "org-dblock-write:" name))))
9609 (message "Updating dynamic block `%s' at line %d..." name line)
9610 (funcall cmd params)
9611 (message "Updating dynamic block `%s' at line %d...done" name line)
9612 (goto-char pos)
9613 (when (and indent (> indent 0))
9614 (setq indent (make-string indent ?\ ))
9615 (save-excursion
9616 (org-beginning-of-dblock)
9617 (forward-line 1)
9618 (while (not (looking-at org-dblock-end-re))
9619 (insert indent)
9620 (beginning-of-line 2))
9621 (when (looking-at org-dblock-end-re)
9622 (and (looking-at "[ \t]+")
9623 (replace-match ""))
9624 (insert indent)))))))
9626 (defun org-beginning-of-dblock ()
9627 "Find the beginning of the dynamic block at point.
9628 Error if there is no such block at point."
9629 (let ((pos (point))
9630 beg)
9631 (end-of-line 1)
9632 (if (and (re-search-backward org-dblock-start-re nil t)
9633 (setq beg (match-beginning 0))
9634 (re-search-forward org-dblock-end-re nil t)
9635 (> (match-end 0) pos))
9636 (goto-char beg)
9637 (goto-char pos)
9638 (error "Not in a dynamic block"))))
9640 (defun org-update-all-dblocks ()
9641 "Update all dynamic blocks in the buffer.
9642 This function can be used in a hook."
9643 (when (org-mode-p)
9644 (org-map-dblocks 'org-update-dblock)))
9647 ;;;; Completion
9649 (defconst org-additional-option-like-keywords
9650 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9651 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9652 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9653 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9654 "BEGIN:" "END:"
9655 "ORGTBL" "TBLFM:" "TBLNAME:"
9656 "BEGIN_EXAMPLE" "END_EXAMPLE"
9657 "BEGIN_QUOTE" "END_QUOTE"
9658 "BEGIN_VERSE" "END_VERSE"
9659 "BEGIN_CENTER" "END_CENTER"
9660 "BEGIN_SRC" "END_SRC"
9661 "CATEGORY" "COLUMNS"
9662 "CAPTION" "LABEL"
9663 "SETUPFILE"
9664 "BIND"
9665 "MACRO"))
9667 (defcustom org-structure-template-alist
9669 ("s" "#+begin_src ?\n\n#+end_src"
9670 "<src lang=\"?\">\n\n</src>")
9671 ("e" "#+begin_example\n?\n#+end_example"
9672 "<example>\n?\n</example>")
9673 ("q" "#+begin_quote\n?\n#+end_quote"
9674 "<quote>\n?\n</quote>")
9675 ("v" "#+begin_verse\n?\n#+end_verse"
9676 "<verse>\n?\n/verse>")
9677 ("c" "#+begin_center\n?\n#+end_center"
9678 "<center>\n?\n/center>")
9679 ("l" "#+begin_latex\n?\n#+end_latex"
9680 "<literal style=\"latex\">\n?\n</literal>")
9681 ("L" "#+latex: "
9682 "<literal style=\"latex\">?</literal>")
9683 ("h" "#+begin_html\n?\n#+end_html"
9684 "<literal style=\"html\">\n?\n</literal>")
9685 ("H" "#+html: "
9686 "<literal style=\"html\">?</literal>")
9687 ("a" "#+begin_ascii\n?\n#+end_ascii")
9688 ("A" "#+ascii: ")
9689 ("i" "#+include %file ?"
9690 "<include file=%file markup=\"?\">")
9692 "Structure completion elements.
9693 This is a list of abbreviation keys and values. The value gets inserted
9694 it you type @samp{.} followed by the key and then the completion key,
9695 usually `M-TAB'. %file will be replaced by a file name after prompting
9696 for the file using completion.
9697 There are two templates for each key, the first uses the original Org syntax,
9698 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9699 the default when the /org-mtags.el/ module has been loaded. See also the
9700 variable `org-mtags-prefer-muse-templates'.
9701 This is an experimental feature, it is undecided if it is going to stay in."
9702 :group 'org-completion
9703 :type '(repeat
9704 (string :tag "Key")
9705 (string :tag "Template")
9706 (string :tag "Muse Template")))
9708 (defun org-try-structure-completion ()
9709 "Try to complete a structure template before point.
9710 This looks for strings like \"<e\" on an otherwise empty line and
9711 expands them."
9712 (let ((l (buffer-substring (point-at-bol) (point)))
9714 (when (and (looking-at "[ \t]*$")
9715 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9716 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9717 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9718 (match-beginning 1)) a)
9719 t)))
9721 (defun org-complete-expand-structure-template (start cell)
9722 "Expand a structure template."
9723 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9724 (rpl (nth (if musep 2 1) cell))
9725 (ind ""))
9726 (delete-region start (point))
9727 (when (string-match "\\`#\\+" rpl)
9728 (cond
9729 ((bolp))
9730 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9731 (setq ind (buffer-substring (point-at-bol) (point))))
9732 (t (newline))))
9733 (setq start (point))
9734 (if (string-match "%file" rpl)
9735 (setq rpl (replace-match
9736 (concat
9737 "\""
9738 (save-match-data
9739 (abbreviate-file-name (read-file-name "Include file: ")))
9740 "\"")
9741 t t rpl)))
9742 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9743 (concat "\n" ind)))
9744 (insert rpl)
9745 (if (re-search-backward "\\?" start t) (delete-char 1))))
9748 (defun org-complete (&optional arg)
9749 "Perform completion on word at point.
9750 At the beginning of a headline, this completes TODO keywords as given in
9751 `org-todo-keywords'.
9752 If the current word is preceded by a backslash, completes the TeX symbols
9753 that are supported for HTML support.
9754 If the current word is preceded by \"#+\", completes special words for
9755 setting file options.
9756 In the line after \"#+STARTUP:, complete valid keywords.\"
9757 At all other locations, this simply calls the value of
9758 `org-completion-fallback-command'."
9759 (interactive "P")
9760 (org-without-partial-completion
9761 (catch 'exit
9762 (let* ((a nil)
9763 (end (point))
9764 (beg1 (save-excursion
9765 (skip-chars-backward (org-re "[:alnum:]_@"))
9766 (point)))
9767 (beg (save-excursion
9768 (skip-chars-backward "a-zA-Z0-9_:$")
9769 (point)))
9770 (confirm (lambda (x) (stringp (car x))))
9771 (searchhead (equal (char-before beg) ?*))
9772 (struct
9773 (when (and (member (char-before beg1) '(?. ?<))
9774 (setq a (assoc (buffer-substring beg1 (point))
9775 org-structure-template-alist)))
9776 (org-complete-expand-structure-template (1- beg1) a)
9777 (throw 'exit t)))
9778 (tag (and (equal (char-before beg1) ?:)
9779 (equal (char-after (point-at-bol)) ?*)))
9780 (prop (and (equal (char-before beg1) ?:)
9781 (not (equal (char-after (point-at-bol)) ?*))))
9782 (texp (equal (char-before beg) ?\\))
9783 (link (equal (char-before beg) ?\[))
9784 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9785 beg)
9786 "#+"))
9787 (startup (string-match "^#\\+STARTUP:.*"
9788 (buffer-substring (point-at-bol) (point))))
9789 (completion-ignore-case opt)
9790 (type nil)
9791 (tbl nil)
9792 (table (cond
9793 (opt
9794 (setq type :opt)
9795 (require 'org-exp)
9796 (append
9797 (delq nil
9798 (mapcar
9799 (lambda (x)
9800 (if (string-match
9801 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9802 (cons (match-string 2 x)
9803 (match-string 1 x))))
9804 (org-split-string (org-get-current-options) "\n")))
9805 (mapcar 'list org-additional-option-like-keywords)))
9806 (startup
9807 (setq type :startup)
9808 org-startup-options)
9809 (link (append org-link-abbrev-alist-local
9810 org-link-abbrev-alist))
9811 (texp
9812 (setq type :tex)
9813 org-html-entities)
9814 ((string-match "\\`\\*+[ \t]+\\'"
9815 (buffer-substring (point-at-bol) beg))
9816 (setq type :todo)
9817 (mapcar 'list org-todo-keywords-1))
9818 (searchhead
9819 (setq type :searchhead)
9820 (save-excursion
9821 (goto-char (point-min))
9822 (while (re-search-forward org-todo-line-regexp nil t)
9823 (push (list
9824 (org-make-org-heading-search-string
9825 (match-string 3) t))
9826 tbl)))
9827 tbl)
9828 (tag (setq type :tag beg beg1)
9829 (or org-tag-alist (org-get-buffer-tags)))
9830 (prop (setq type :prop beg beg1)
9831 (mapcar 'list (org-buffer-property-keys nil t t)))
9832 (t (progn
9833 (call-interactively org-completion-fallback-command)
9834 (throw 'exit nil)))))
9835 (pattern (buffer-substring-no-properties beg end))
9836 (completion (try-completion pattern table confirm)))
9837 (cond ((eq completion t)
9838 (if (not (assoc (upcase pattern) table))
9839 (message "Already complete")
9840 (if (and (equal type :opt)
9841 (not (member (car (assoc (upcase pattern) table))
9842 org-additional-option-like-keywords)))
9843 (insert (substring (cdr (assoc (upcase pattern) table))
9844 (length pattern)))
9845 (if (memq type '(:tag :prop)) (insert ":")))))
9846 ((null completion)
9847 (message "Can't find completion for \"%s\"" pattern)
9848 (ding))
9849 ((not (string= pattern completion))
9850 (delete-region beg end)
9851 (if (string-match " +$" completion)
9852 (setq completion (replace-match "" t t completion)))
9853 (insert completion)
9854 (if (get-buffer-window "*Completions*")
9855 (delete-window (get-buffer-window "*Completions*")))
9856 (if (assoc completion table)
9857 (if (eq type :todo) (insert " ")
9858 (if (memq type '(:tag :prop)) (insert ":"))))
9859 (if (and (equal type :opt) (assoc completion table))
9860 (message "%s" (substitute-command-keys
9861 "Press \\[org-complete] again to insert example settings"))))
9863 (message "Making completion list...")
9864 (let ((list (sort (all-completions pattern table confirm)
9865 'string<)))
9866 (with-output-to-temp-buffer "*Completions*"
9867 (condition-case nil
9868 ;; Protection needed for XEmacs and emacs 21
9869 (display-completion-list list pattern)
9870 (error (display-completion-list list)))))
9871 (message "Making completion list...%s" "done")))))))
9873 ;;;; TODO, DEADLINE, Comments
9875 (defun org-toggle-comment ()
9876 "Change the COMMENT state of an entry."
9877 (interactive)
9878 (save-excursion
9879 (org-back-to-heading)
9880 (let (case-fold-search)
9881 (if (looking-at (concat outline-regexp
9882 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9883 (replace-match "" t t nil 1)
9884 (if (looking-at outline-regexp)
9885 (progn
9886 (goto-char (match-end 0))
9887 (insert org-comment-string " ")))))))
9889 (defvar org-last-todo-state-is-todo nil
9890 "This is non-nil when the last TODO state change led to a TODO state.
9891 If the last change removed the TODO tag or switched to DONE, then
9892 this is nil.")
9894 (defvar org-setting-tags nil) ; dynamically skipped
9896 (defun org-parse-local-options (string var)
9897 "Parse STRING for startup setting relevant for variable VAR."
9898 (let ((rtn (symbol-value var))
9899 e opts)
9900 (save-match-data
9901 (if (or (not string) (not (string-match "\\S-" string)))
9903 (setq opts (delq nil (mapcar (lambda (x)
9904 (setq e (assoc x org-startup-options))
9905 (if (eq (nth 1 e) var) e nil))
9906 (org-split-string string "[ \t]+"))))
9907 (if (not opts)
9909 (setq rtn nil)
9910 (while (setq e (pop opts))
9911 (if (not (nth 3 e))
9912 (setq rtn (nth 2 e))
9913 (if (not (listp rtn)) (setq rtn nil))
9914 (push (nth 2 e) rtn)))
9915 rtn)))))
9917 (defvar org-todo-setup-filter-hook nil
9918 "Hook for functions that pre-filter todo specs.
9920 Each function takes a todo spec and returns either `nil' or the spec
9921 transformed into canonical form." )
9923 (defvar org-todo-get-default-hook nil
9924 "Hook for functions that get a default item for todo.
9926 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9927 `nil' or a string to be used for the todo mark." )
9929 (defvar org-agenda-headline-snapshot-before-repeat)
9931 (defun org-todo (&optional arg)
9932 "Change the TODO state of an item.
9933 The state of an item is given by a keyword at the start of the heading,
9934 like
9935 *** TODO Write paper
9936 *** DONE Call mom
9938 The different keywords are specified in the variable `org-todo-keywords'.
9939 By default the available states are \"TODO\" and \"DONE\".
9940 So for this example: when the item starts with TODO, it is changed to DONE.
9941 When it starts with DONE, the DONE is removed. And when neither TODO nor
9942 DONE are present, add TODO at the beginning of the heading.
9944 With C-u prefix arg, use completion to determine the new state.
9945 With numeric prefix arg, switch to that state.
9946 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9947 With a triple C-u prefix, circumvent any state blocking.
9949 For calling through lisp, arg is also interpreted in the following way:
9950 'none -> empty state
9951 \"\"(empty string) -> switch to empty state
9952 'done -> switch to DONE
9953 'nextset -> switch to the next set of keywords
9954 'previousset -> switch to the previous set of keywords
9955 \"WAITING\" -> switch to the specified keyword, but only if it
9956 really is a member of `org-todo-keywords'."
9957 (interactive "P")
9958 (if (equal arg '(16)) (setq arg 'nextset))
9959 (let ((org-blocker-hook org-blocker-hook)
9960 (case-fold-search nil))
9961 (when (equal arg '(64))
9962 (setq arg nil org-blocker-hook nil))
9963 (when (and org-blocker-hook
9964 (or org-inhibit-blocking
9965 (org-entry-get nil "NOBLOCKING")))
9966 (setq org-blocker-hook nil))
9967 (save-excursion
9968 (catch 'exit
9969 (org-back-to-heading t)
9970 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9971 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9972 (looking-at " *"))
9973 (let* ((match-data (match-data))
9974 (startpos (point-at-bol))
9975 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9976 (org-log-done org-log-done)
9977 (org-log-repeat org-log-repeat)
9978 (org-todo-log-states org-todo-log-states)
9979 (this (match-string 1))
9980 (hl-pos (match-beginning 0))
9981 (head (org-get-todo-sequence-head this))
9982 (ass (assoc head org-todo-kwd-alist))
9983 (interpret (nth 1 ass))
9984 (done-word (nth 3 ass))
9985 (final-done-word (nth 4 ass))
9986 (last-state (or this ""))
9987 (completion-ignore-case t)
9988 (member (member this org-todo-keywords-1))
9989 (tail (cdr member))
9990 (state (cond
9991 ((and org-todo-key-trigger
9992 (or (and (equal arg '(4))
9993 (eq org-use-fast-todo-selection 'prefix))
9994 (and (not arg) org-use-fast-todo-selection
9995 (not (eq org-use-fast-todo-selection
9996 'prefix)))))
9997 ;; Use fast selection
9998 (org-fast-todo-selection))
9999 ((and (equal arg '(4))
10000 (or (not org-use-fast-todo-selection)
10001 (not org-todo-key-trigger)))
10002 ;; Read a state with completion
10003 (org-icompleting-read
10004 "State: " (mapcar (lambda(x) (list x))
10005 org-todo-keywords-1)
10006 nil t))
10007 ((eq arg 'right)
10008 (if this
10009 (if tail (car tail) nil)
10010 (car org-todo-keywords-1)))
10011 ((eq arg 'left)
10012 (if (equal member org-todo-keywords-1)
10014 (if this
10015 (nth (- (length org-todo-keywords-1)
10016 (length tail) 2)
10017 org-todo-keywords-1)
10018 (org-last org-todo-keywords-1))))
10019 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10020 (setq arg nil))) ; hack to fall back to cycling
10021 (arg
10022 ;; user or caller requests a specific state
10023 (cond
10024 ((equal arg "") nil)
10025 ((eq arg 'none) nil)
10026 ((eq arg 'done) (or done-word (car org-done-keywords)))
10027 ((eq arg 'nextset)
10028 (or (car (cdr (member head org-todo-heads)))
10029 (car org-todo-heads)))
10030 ((eq arg 'previousset)
10031 (let ((org-todo-heads (reverse org-todo-heads)))
10032 (or (car (cdr (member head org-todo-heads)))
10033 (car org-todo-heads))))
10034 ((car (member arg org-todo-keywords-1)))
10035 ((stringp arg)
10036 (error "State `%s' not valid in this file" arg))
10037 ((nth (1- (prefix-numeric-value arg))
10038 org-todo-keywords-1))))
10039 ((null member) (or head (car org-todo-keywords-1)))
10040 ((equal this final-done-word) nil) ;; -> make empty
10041 ((null tail) nil) ;; -> first entry
10042 ((memq interpret '(type priority))
10043 (if (eq this-command last-command)
10044 (car tail)
10045 (if (> (length tail) 0)
10046 (or done-word (car org-done-keywords))
10047 nil)))
10049 (car tail))))
10050 (state (or
10051 (run-hook-with-args-until-success
10052 'org-todo-get-default-hook state last-state)
10053 state))
10054 (next (if state (concat " " state " ") " "))
10055 (change-plist (list :type 'todo-state-change :from this :to state
10056 :position startpos))
10057 dolog now-done-p)
10058 (when org-blocker-hook
10059 (setq org-last-todo-state-is-todo
10060 (not (member this org-done-keywords)))
10061 (unless (save-excursion
10062 (save-match-data
10063 (run-hook-with-args-until-failure
10064 'org-blocker-hook change-plist)))
10065 (if (interactive-p)
10066 (error "TODO state change from %s to %s blocked" this state)
10067 ;; fail silently
10068 (message "TODO state change from %s to %s blocked" this state)
10069 (throw 'exit nil))))
10070 (store-match-data match-data)
10071 (replace-match next t t)
10072 (unless (pos-visible-in-window-p hl-pos)
10073 (message "TODO state changed to %s" (org-trim next)))
10074 (unless head
10075 (setq head (org-get-todo-sequence-head state)
10076 ass (assoc head org-todo-kwd-alist)
10077 interpret (nth 1 ass)
10078 done-word (nth 3 ass)
10079 final-done-word (nth 4 ass)))
10080 (when (memq arg '(nextset previousset))
10081 (message "Keyword-Set %d/%d: %s"
10082 (- (length org-todo-sets) -1
10083 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10084 (length org-todo-sets)
10085 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10086 (setq org-last-todo-state-is-todo
10087 (not (member state org-done-keywords)))
10088 (setq now-done-p (and (member state org-done-keywords)
10089 (not (member this org-done-keywords))))
10090 (and logging (org-local-logging logging))
10091 (when (and (or org-todo-log-states org-log-done)
10092 (not (eq org-inhibit-logging t))
10093 (not (memq arg '(nextset previousset))))
10094 ;; we need to look at recording a time and note
10095 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10096 (nth 2 (assoc this org-todo-log-states))))
10097 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10098 (setq dolog 'time))
10099 (when (and state
10100 (member state org-not-done-keywords)
10101 (not (member this org-not-done-keywords)))
10102 ;; This is now a todo state and was not one before
10103 ;; If there was a CLOSED time stamp, get rid of it.
10104 (org-add-planning-info nil nil 'closed))
10105 (when (and now-done-p org-log-done)
10106 ;; It is now done, and it was not done before
10107 (org-add-planning-info 'closed (org-current-time))
10108 (if (and (not dolog) (eq 'note org-log-done))
10109 (org-add-log-setup 'done state this 'findpos 'note)))
10110 (when (and state dolog)
10111 ;; This is a non-nil state, and we need to log it
10112 (org-add-log-setup 'state state this 'findpos dolog)))
10113 ;; Fixup tag positioning
10114 (org-todo-trigger-tag-changes state)
10115 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10116 (when org-provide-todo-statistics
10117 (org-update-parent-todo-statistics))
10118 (run-hooks 'org-after-todo-state-change-hook)
10119 (if (and arg (not (member state org-done-keywords)))
10120 (setq head (org-get-todo-sequence-head state)))
10121 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10122 ;; Do we need to trigger a repeat?
10123 (when now-done-p
10124 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10125 ;; This is for the agenda, take a snapshot of the headline.
10126 (save-match-data
10127 (setq org-agenda-headline-snapshot-before-repeat
10128 (org-get-heading))))
10129 (org-auto-repeat-maybe state))
10130 ;; Fixup cursor location if close to the keyword
10131 (if (and (outline-on-heading-p)
10132 (not (bolp))
10133 (save-excursion (beginning-of-line 1)
10134 (looking-at org-todo-line-regexp))
10135 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10136 (progn
10137 (goto-char (or (match-end 2) (match-end 1)))
10138 (and (looking-at " ") (just-one-space))))
10139 (when org-trigger-hook
10140 (save-excursion
10141 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10143 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10144 "Block turning an entry into a TODO, using the hierarchy.
10145 This checks whether the current task should be blocked from state
10146 changes. Such blocking occurs when:
10148 1. The task has children which are not all in a completed state.
10150 2. A task has a parent with the property :ORDERED:, and there
10151 are siblings prior to the current task with incomplete
10152 status.
10154 3. The parent of the task is blocked because it has siblings that should
10155 be done first, or is child of a block grandparent TODO entry."
10157 (catch 'dont-block
10158 ;; If this is not a todo state change, or if this entry is already DONE,
10159 ;; do not block
10160 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10161 (member (plist-get change-plist :from)
10162 (cons 'done org-done-keywords))
10163 (member (plist-get change-plist :to)
10164 (cons 'todo org-not-done-keywords))
10165 (not (plist-get change-plist :to)))
10166 (throw 'dont-block t))
10167 ;; If this task has children, and any are undone, it's blocked
10168 (save-excursion
10169 (org-back-to-heading t)
10170 (let ((this-level (funcall outline-level)))
10171 (outline-next-heading)
10172 (let ((child-level (funcall outline-level)))
10173 (while (and (not (eobp))
10174 (> child-level this-level))
10175 ;; this todo has children, check whether they are all
10176 ;; completed
10177 (if (and (not (org-entry-is-done-p))
10178 (org-entry-is-todo-p))
10179 (throw 'dont-block nil))
10180 (outline-next-heading)
10181 (setq child-level (funcall outline-level))))))
10182 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10183 ;; any previous siblings are undone, it's blocked
10184 (save-excursion
10185 (org-back-to-heading t)
10186 (let* ((pos (point))
10187 (parent-pos (and (org-up-heading-safe) (point))))
10188 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10189 (when (and (org-entry-get (point) "ORDERED")
10190 (forward-line 1)
10191 (re-search-forward org-not-done-heading-regexp pos t))
10192 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10193 ;; Search further up the hierarchy, to see if an anchestor is blocked
10194 (while t
10195 (goto-char parent-pos)
10196 (if (not (looking-at org-not-done-heading-regexp))
10197 (throw 'dont-block t)) ; do not block, parent is not a TODO
10198 (setq pos (point))
10199 (setq parent-pos (and (org-up-heading-safe) (point)))
10200 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10201 (when (and (org-entry-get (point) "ORDERED")
10202 (forward-line 1)
10203 (re-search-forward org-not-done-heading-regexp pos t))
10204 (throw 'dont-block nil))))))) ; block, older sibling not done.
10206 (defcustom org-track-ordered-property-with-tag nil
10207 "Should the ORDERED property also be shown as a tag?
10208 The ORDERED property decides if an entry should require subtasks to be
10209 completed in sequence. Since a property is not very visible, setting
10210 this option means that toggling the ORDERED property with the command
10211 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10212 not relevant for the behavior, but it makes things more visible.
10214 Note that toggling the tag with tags commands will not change the property
10215 and therefore not influence behavior!
10217 This can be t, meaning the tag ORDERED should be used, It can also be a
10218 string to select a different tag for this task."
10219 :group 'org-todo
10220 :type '(choice
10221 (const :tag "No tracking" nil)
10222 (const :tag "Track with ORDERED tag" t)
10223 (string :tag "Use other tag")))
10225 (defun org-toggle-ordered-property ()
10226 "Toggle the ORDERED property of the current entry.
10227 For better visibility, you can track the value of this property with a tag.
10228 See variable `org-track-ordered-property-with-tag'."
10229 (interactive)
10230 (let* ((t1 org-track-ordered-property-with-tag)
10231 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10232 (save-excursion
10233 (org-back-to-heading)
10234 (if (org-entry-get nil "ORDERED")
10235 (progn
10236 (org-delete-property "ORDERED")
10237 (and tag (org-toggle-tag tag 'off))
10238 (message "Subtasks can be completed in arbitrary order"))
10239 (org-entry-put nil "ORDERED" "t")
10240 (and tag (org-toggle-tag tag 'on))
10241 (message "Subtasks must be completed in sequence")))))
10243 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10244 (defun org-block-todo-from-checkboxes (change-plist)
10245 "Block turning an entry into a TODO, using checkboxes.
10246 This checks whether the current task should be blocked from state
10247 changes because there are unchecked boxes in this entry."
10248 (catch 'dont-block
10249 ;; If this is not a todo state change, or if this entry is already DONE,
10250 ;; do not block
10251 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10252 (member (plist-get change-plist :from)
10253 (cons 'done org-done-keywords))
10254 (member (plist-get change-plist :to)
10255 (cons 'todo org-not-done-keywords))
10256 (not (plist-get change-plist :to)))
10257 (throw 'dont-block t))
10258 ;; If this task has checkboxes that are not checked, it's blocked
10259 (save-excursion
10260 (org-back-to-heading t)
10261 (let ((beg (point)) end)
10262 (outline-next-heading)
10263 (setq end (point))
10264 (goto-char beg)
10265 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10266 end t)
10267 (progn
10268 (if (boundp 'org-blocked-by-checkboxes)
10269 (setq org-blocked-by-checkboxes t))
10270 (throw 'dont-block nil)))))
10271 t)) ; do not block
10273 (defun org-entry-blocked-p ()
10274 "Is the current entry blocked?"
10275 (if (org-entry-get nil "NOBLOCKING")
10276 nil ;; Never block this entry
10277 (not
10278 (run-hook-with-args-until-failure
10279 'org-blocker-hook
10280 (list :type 'todo-state-change
10281 :position (point)
10282 :from 'todo
10283 :to 'done)))))
10285 (defun org-update-statistics-cookies (all)
10286 "Update the statistics cookie, either from TODO or from checkboxes.
10287 This should be called with the cursor in a line with a statistics cookie."
10288 (interactive "P")
10289 (if all
10290 (progn
10291 (org-update-checkbox-count 'all)
10292 (org-map-entries 'org-update-parent-todo-statistics))
10293 (if (not (org-on-heading-p))
10294 (org-update-checkbox-count)
10295 (let ((pos (move-marker (make-marker) (point)))
10296 end l1 l2)
10297 (ignore-errors (org-back-to-heading t))
10298 (if (not (org-on-heading-p))
10299 (org-update-checkbox-count)
10300 (setq l1 (org-outline-level))
10301 (setq end (save-excursion
10302 (outline-next-heading)
10303 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10304 (point)))
10305 (if (and (save-excursion (re-search-forward
10306 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10307 (not (save-excursion (re-search-forward
10308 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10309 (org-update-checkbox-count)
10310 (if (and l2 (> l2 l1))
10311 (progn
10312 (goto-char end)
10313 (org-update-parent-todo-statistics))
10314 (goto-char pos)
10315 (beginning-of-line 1)
10316 (while (re-search-forward
10317 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10318 (point-at-eol) t)
10319 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10320 (goto-char pos)
10321 (move-marker pos nil)))))
10323 (defvar org-entry-property-inherited-from) ;; defined below
10324 (defun org-update-parent-todo-statistics ()
10325 "Update any statistics cookie in the parent of the current headline.
10326 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10327 the entire subtree and this will travel up the hierarchy and update
10328 statistics everywhere."
10329 (interactive)
10330 (let* ((lim 0) prop
10331 (recursive (or (not org-hierarchical-todo-statistics)
10332 (string-match
10333 "\\<recursive\\>"
10334 (or (setq prop (org-entry-get
10335 nil "COOKIE_DATA" 'inherit)) ""))))
10336 (lim (or (and prop (marker-position
10337 org-entry-property-inherited-from))
10338 lim))
10339 (first t)
10340 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10341 level ltoggle l1 new ndel
10342 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10343 (catch 'exit
10344 (save-excursion
10345 (beginning-of-line 1)
10346 (if (org-at-heading-p)
10347 (setq ltoggle (funcall outline-level))
10348 (error "This should not happen"))
10349 (while (and (setq level (org-up-heading-safe))
10350 (or recursive first)
10351 (>= (point) lim))
10352 (setq first nil cookie-present nil)
10353 (unless (and level
10354 (not (string-match
10355 "\\<checkbox\\>"
10356 (downcase
10357 (or (org-entry-get
10358 nil "COOKIE_DATA")
10359 "")))))
10360 (throw 'exit nil))
10361 (while (re-search-forward box-re (point-at-eol) t)
10362 (setq cnt-all 0 cnt-done 0 cookie-present t)
10363 (setq is-percent (match-end 2))
10364 (save-match-data
10365 (unless (outline-next-heading) (throw 'exit nil))
10366 (while (and (looking-at org-complex-heading-regexp)
10367 (> (setq l1 (length (match-string 1))) level))
10368 (setq kwd (and (or recursive (= l1 ltoggle))
10369 (match-string 2)))
10370 (if (or (eq org-provide-todo-statistics 'all-headlines)
10371 (and (listp org-provide-todo-statistics)
10372 (or (member kwd org-provide-todo-statistics)
10373 (member kwd org-done-keywords))))
10374 (setq cnt-all (1+ cnt-all))
10375 (if (eq org-provide-todo-statistics t)
10376 (and kwd (setq cnt-all (1+ cnt-all)))))
10377 (and (member kwd org-done-keywords)
10378 (setq cnt-done (1+ cnt-done)))
10379 (outline-next-heading)))
10380 (setq new
10381 (if is-percent
10382 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10383 (format "[%d/%d]" cnt-done cnt-all))
10384 ndel (- (match-end 0) (match-beginning 0)))
10385 (goto-char (match-beginning 0))
10386 (insert new)
10387 (delete-region (point) (+ (point) ndel)))
10388 (when cookie-present
10389 (run-hook-with-args 'org-after-todo-statistics-hook
10390 cnt-done (- cnt-all cnt-done))))))
10391 (run-hooks 'org-todo-statistics-hook)))
10393 (defvar org-after-todo-statistics-hook nil
10394 "Hook that is called after a TODO statistics cookie has been updated.
10395 Each function is called with two arguments: the number of not-done entries
10396 and the number of done entries.
10398 For example, the following function, when added to this hook, will switch
10399 an entry to DONE when all children are done, and back to TODO when new
10400 entries are set to a TODO status. Note that this hook is only called
10401 when there is a statistics cookie in the headline!
10403 (defun org-summary-todo (n-done n-not-done)
10404 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10405 (let (org-log-done org-log-states) ; turn off logging
10406 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10409 (defvar org-todo-statistics-hook nil
10410 "Hook that is run whenever Org thinks TODO statistics should be updated.
10411 This hook runs even if there is no statistics cookie present, in which case
10412 `org-after-todo-statistics-hook' would not run.")
10414 (defun org-todo-trigger-tag-changes (state)
10415 "Apply the changes defined in `org-todo-state-tags-triggers'."
10416 (let ((l org-todo-state-tags-triggers)
10417 changes)
10418 (when (or (not state) (equal state ""))
10419 (setq changes (append changes (cdr (assoc "" l)))))
10420 (when (and (stringp state) (> (length state) 0))
10421 (setq changes (append changes (cdr (assoc state l)))))
10422 (when (member state org-not-done-keywords)
10423 (setq changes (append changes (cdr (assoc 'todo l)))))
10424 (when (member state org-done-keywords)
10425 (setq changes (append changes (cdr (assoc 'done l)))))
10426 (dolist (c changes)
10427 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10429 (defun org-local-logging (value)
10430 "Get logging settings from a property VALUE."
10431 (let* (words w a)
10432 ;; directly set the variables, they are already local.
10433 (setq org-log-done nil
10434 org-log-repeat nil
10435 org-todo-log-states nil)
10436 (setq words (org-split-string value))
10437 (while (setq w (pop words))
10438 (cond
10439 ((setq a (assoc w org-startup-options))
10440 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10441 (set (nth 1 a) (nth 2 a))))
10442 ((setq a (org-extract-log-state-settings w))
10443 (and (member (car a) org-todo-keywords-1)
10444 (push a org-todo-log-states)))))))
10446 (defun org-get-todo-sequence-head (kwd)
10447 "Return the head of the TODO sequence to which KWD belongs.
10448 If KWD is not set, check if there is a text property remembering the
10449 right sequence."
10450 (let (p)
10451 (cond
10452 ((not kwd)
10453 (or (get-text-property (point-at-bol) 'org-todo-head)
10454 (progn
10455 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10456 nil (point-at-eol)))
10457 (get-text-property p 'org-todo-head))))
10458 ((not (member kwd org-todo-keywords-1))
10459 (car org-todo-keywords-1))
10460 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10462 (defun org-fast-todo-selection ()
10463 "Fast TODO keyword selection with single keys.
10464 Returns the new TODO keyword, or nil if no state change should occur."
10465 (let* ((fulltable org-todo-key-alist)
10466 (done-keywords org-done-keywords) ;; needed for the faces.
10467 (maxlen (apply 'max (mapcar
10468 (lambda (x)
10469 (if (stringp (car x)) (string-width (car x)) 0))
10470 fulltable)))
10471 (expert nil)
10472 (fwidth (+ maxlen 3 1 3))
10473 (ncol (/ (- (window-width) 4) fwidth))
10474 tg cnt e c tbl
10475 groups ingroup)
10476 (save-excursion
10477 (save-window-excursion
10478 (if expert
10479 (set-buffer (get-buffer-create " *Org todo*"))
10480 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10481 (erase-buffer)
10482 (org-set-local 'org-done-keywords done-keywords)
10483 (setq tbl fulltable cnt 0)
10484 (while (setq e (pop tbl))
10485 (cond
10486 ((equal e '(:startgroup))
10487 (push '() groups) (setq ingroup t)
10488 (when (not (= cnt 0))
10489 (setq cnt 0)
10490 (insert "\n"))
10491 (insert "{ "))
10492 ((equal e '(:endgroup))
10493 (setq ingroup nil cnt 0)
10494 (insert "}\n"))
10495 ((equal e '(:newline))
10496 (when (not (= cnt 0))
10497 (setq cnt 0)
10498 (insert "\n")
10499 (setq e (car tbl))
10500 (while (equal (car tbl) '(:newline))
10501 (insert "\n")
10502 (setq tbl (cdr tbl)))))
10504 (setq tg (car e) c (cdr e))
10505 (if ingroup (push tg (car groups)))
10506 (setq tg (org-add-props tg nil 'face
10507 (org-get-todo-face tg)))
10508 (if (and (= cnt 0) (not ingroup)) (insert " "))
10509 (insert "[" c "] " tg (make-string
10510 (- fwidth 4 (length tg)) ?\ ))
10511 (when (= (setq cnt (1+ cnt)) ncol)
10512 (insert "\n")
10513 (if ingroup (insert " "))
10514 (setq cnt 0)))))
10515 (insert "\n")
10516 (goto-char (point-min))
10517 (if (not expert) (org-fit-window-to-buffer))
10518 (message "[a-z..]:Set [SPC]:clear")
10519 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10520 (cond
10521 ((or (= c ?\C-g)
10522 (and (= c ?q) (not (rassoc c fulltable))))
10523 (setq quit-flag t))
10524 ((= c ?\ ) nil)
10525 ((setq e (rassoc c fulltable) tg (car e))
10527 (t (setq quit-flag t)))))))
10529 (defun org-entry-is-todo-p ()
10530 (member (org-get-todo-state) org-not-done-keywords))
10532 (defun org-entry-is-done-p ()
10533 (member (org-get-todo-state) org-done-keywords))
10535 (defun org-get-todo-state ()
10536 (save-excursion
10537 (org-back-to-heading t)
10538 (and (looking-at org-todo-line-regexp)
10539 (match-end 2)
10540 (match-string 2))))
10542 (defun org-at-date-range-p (&optional inactive-ok)
10543 "Is the cursor inside a date range?"
10544 (interactive)
10545 (save-excursion
10546 (catch 'exit
10547 (let ((pos (point)))
10548 (skip-chars-backward "^[<\r\n")
10549 (skip-chars-backward "<[")
10550 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10551 (>= (match-end 0) pos)
10552 (throw 'exit t))
10553 (skip-chars-backward "^<[\r\n")
10554 (skip-chars-backward "<[")
10555 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10556 (>= (match-end 0) pos)
10557 (throw 'exit t)))
10558 nil)))
10560 (defun org-get-repeat (&optional tagline)
10561 "Check if there is a deadline/schedule with repeater in this entry."
10562 (save-match-data
10563 (save-excursion
10564 (org-back-to-heading t)
10565 (and (re-search-forward (if tagline
10566 (concat tagline "\\s-*" org-repeat-re)
10567 org-repeat-re)
10568 (org-entry-end-position) t)
10569 (match-string-no-properties 1)))))
10571 (defvar org-last-changed-timestamp)
10572 (defvar org-last-inserted-timestamp)
10573 (defvar org-log-post-message)
10574 (defvar org-log-note-purpose)
10575 (defvar org-log-note-how)
10576 (defvar org-log-note-extra)
10577 (defun org-auto-repeat-maybe (done-word)
10578 "Check if the current headline contains a repeated deadline/schedule.
10579 If yes, set TODO state back to what it was and change the base date
10580 of repeating deadline/scheduled time stamps to new date.
10581 This function is run automatically after each state change to a DONE state."
10582 ;; last-state is dynamically scoped into this function
10583 (let* ((repeat (org-get-repeat))
10584 (aa (assoc last-state org-todo-kwd-alist))
10585 (interpret (nth 1 aa))
10586 (head (nth 2 aa))
10587 (whata '(("d" . day) ("m" . month) ("y" . year)))
10588 (msg "Entry repeats: ")
10589 (org-log-done nil)
10590 (org-todo-log-states nil)
10591 (nshiftmax 10) (nshift 0)
10592 re type n what ts time)
10593 (when repeat
10594 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10595 (org-todo (if (eq interpret 'type) last-state head))
10596 (org-entry-put nil "LAST_REPEAT" (format-time-string
10597 (org-time-stamp-format t t)))
10598 (when org-log-repeat
10599 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10600 (memq 'org-add-log-note post-command-hook))
10601 ;; OK, we are already setup for some record
10602 (if (eq org-log-repeat 'note)
10603 ;; make sure we take a note, not only a time stamp
10604 (setq org-log-note-how 'note))
10605 ;; Set up for taking a record
10606 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10607 last-state
10608 'findpos org-log-repeat)))
10609 (org-back-to-heading t)
10610 (org-add-planning-info nil nil 'closed)
10611 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10612 org-deadline-time-regexp "\\)\\|\\("
10613 org-ts-regexp "\\)"))
10614 (while (re-search-forward
10615 re (save-excursion (outline-next-heading) (point)) t)
10616 (setq type (if (match-end 1) org-scheduled-string
10617 (if (match-end 3) org-deadline-string "Plain:"))
10618 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10619 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10620 (setq n (string-to-number (match-string 2 ts))
10621 what (match-string 3 ts))
10622 (if (equal what "w") (setq n (* n 7) what "d"))
10623 ;; Preparation, see if we need to modify the start date for the change
10624 (when (match-end 1)
10625 (setq time (save-match-data (org-time-string-to-time ts)))
10626 (cond
10627 ((equal (match-string 1 ts) ".")
10628 ;; Shift starting date to today
10629 (org-timestamp-change
10630 (- (time-to-days (current-time)) (time-to-days time))
10631 'day))
10632 ((equal (match-string 1 ts) "+")
10633 (while (or (= nshift 0)
10634 (<= (time-to-days time) (time-to-days (current-time))))
10635 (when (= (incf nshift) nshiftmax)
10636 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10637 (error "Abort")))
10638 (org-timestamp-change n (cdr (assoc what whata)))
10639 (org-at-timestamp-p t)
10640 (setq ts (match-string 1))
10641 (setq time (save-match-data (org-time-string-to-time ts))))
10642 (org-timestamp-change (- n) (cdr (assoc what whata)))
10643 ;; rematch, so that we have everything in place for the real shift
10644 (org-at-timestamp-p t)
10645 (setq ts (match-string 1))
10646 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10647 (org-timestamp-change n (cdr (assoc what whata)))
10648 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10649 (setq org-log-post-message msg)
10650 (message "%s" msg))))
10652 (defun org-show-todo-tree (arg)
10653 "Make a compact tree which shows all headlines marked with TODO.
10654 The tree will show the lines where the regexp matches, and all higher
10655 headlines above the match.
10656 With a \\[universal-argument] prefix, prompt for a regexp to match.
10657 With a numeric prefix N, construct a sparse tree for the Nth element
10658 of `org-todo-keywords-1'."
10659 (interactive "P")
10660 (let ((case-fold-search nil)
10661 (kwd-re
10662 (cond ((null arg) org-not-done-regexp)
10663 ((equal arg '(4))
10664 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10665 (mapcar 'list org-todo-keywords-1))))
10666 (concat "\\("
10667 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10668 "\\)\\>")))
10669 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10670 (regexp-quote (nth (1- (prefix-numeric-value arg))
10671 org-todo-keywords-1)))
10672 (t (error "Invalid prefix argument: %s" arg)))))
10673 (message "%d TODO entries found"
10674 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10676 (defun org-deadline (&optional remove time)
10677 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10678 With argument REMOVE, remove any deadline from the item.
10679 When TIME is set, it should be an internal time specification, and the
10680 scheduling will use the corresponding date."
10681 (interactive "P")
10682 (let ((old-date (org-entry-get nil "DEADLINE")))
10683 (if remove
10684 (progn
10685 (when (and old-date org-log-redeadline)
10686 (org-add-log-setup 'deldeadline nil old-date 'findpos
10687 org-log-redeadline))
10688 (org-remove-timestamp-with-keyword org-deadline-string)
10689 (message "Item no longer has a deadline."))
10690 (if (org-get-repeat)
10691 (error "Cannot change deadline on task with repeater, please do that by hand")
10692 (org-add-planning-info 'deadline time 'closed)
10693 (when (and old-date org-log-redeadline
10694 (not (equal old-date
10695 (substring org-last-inserted-timestamp 1 -1))))
10696 (org-add-log-setup 'redeadline nil old-date 'findpos
10697 org-log-redeadline))
10698 (message "Deadline on %s" org-last-inserted-timestamp)))))
10700 (defun org-schedule (&optional remove time)
10701 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10702 With argument REMOVE, remove any scheduling date from the item.
10703 When TIME is set, it should be an internal time specification, and the
10704 scheduling will use the corresponding date."
10705 (interactive "P")
10706 (let ((old-date (org-entry-get nil "SCHEDULED")))
10707 (if remove
10708 (progn
10709 (when (and old-date org-log-reschedule)
10710 (org-add-log-setup 'delschedule nil old-date 'findpos
10711 org-log-reschedule))
10712 (org-remove-timestamp-with-keyword org-scheduled-string)
10713 (message "Item is no longer scheduled."))
10714 (if (org-get-repeat)
10715 (error "Cannot reschedule task with repeater, please do that by hand")
10716 (org-add-planning-info 'scheduled time 'closed)
10717 (when (and old-date org-log-reschedule
10718 (not (equal old-date
10719 (substring org-last-inserted-timestamp 1 -1))))
10720 (org-add-log-setup 'reschedule nil old-date 'findpos
10721 org-log-reschedule))
10722 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10724 (defun org-get-scheduled-time (pom &optional inherit)
10725 "Get the scheduled time as a time tuple, of a format suitable
10726 for calling org-schedule with, or if there is no scheduling,
10727 returns nil."
10728 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10729 (when time
10730 (apply 'encode-time (org-parse-time-string time)))))
10732 (defun org-get-deadline-time (pom &optional inherit)
10733 "Get the deadine as a time tuple, of a format suitable for
10734 calling org-deadline with, or if there is no scheduling, returns
10735 nil."
10736 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10737 (when time
10738 (apply 'encode-time (org-parse-time-string time)))))
10740 (defun org-remove-timestamp-with-keyword (keyword)
10741 "Remove all time stamps with KEYWORD in the current entry."
10742 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10743 beg)
10744 (save-excursion
10745 (org-back-to-heading t)
10746 (setq beg (point))
10747 (outline-next-heading)
10748 (while (re-search-backward re beg t)
10749 (replace-match "")
10750 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10751 (equal (char-before) ?\ ))
10752 (backward-delete-char 1)
10753 (if (string-match "^[ \t]*$" (buffer-substring
10754 (point-at-bol) (point-at-eol)))
10755 (delete-region (point-at-bol)
10756 (min (point-max) (1+ (point-at-eol))))))))))
10758 (defun org-add-planning-info (what &optional time &rest remove)
10759 "Insert new timestamp with keyword in the line directly after the headline.
10760 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10761 If non is given, the user is prompted for a date.
10762 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10763 be removed."
10764 (interactive)
10765 (let (org-time-was-given org-end-time-was-given ts
10766 end default-time default-input)
10768 (catch 'exit
10769 (when (and (not time) (memq what '(scheduled deadline)))
10770 ;; Try to get a default date/time from existing timestamp
10771 (save-excursion
10772 (org-back-to-heading t)
10773 (setq end (save-excursion (outline-next-heading) (point)))
10774 (when (re-search-forward (if (eq what 'scheduled)
10775 org-scheduled-time-regexp
10776 org-deadline-time-regexp)
10777 end t)
10778 (setq ts (match-string 1)
10779 default-time
10780 (apply 'encode-time (org-parse-time-string ts))
10781 default-input (and ts (org-get-compact-tod ts))))))
10782 (when what
10783 ;; If necessary, get the time from the user
10784 (setq time (or time (org-read-date nil 'to-time nil nil
10785 default-time default-input))))
10787 (when (and org-insert-labeled-timestamps-at-point
10788 (member what '(scheduled deadline)))
10789 (insert
10790 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10791 (org-insert-time-stamp time org-time-was-given
10792 nil nil nil (list org-end-time-was-given))
10793 (setq what nil))
10794 (save-excursion
10795 (save-restriction
10796 (let (col list elt ts buffer-invisibility-spec)
10797 (org-back-to-heading t)
10798 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10799 (goto-char (match-end 1))
10800 (setq col (current-column))
10801 (goto-char (match-end 0))
10802 (if (eobp) (insert "\n") (forward-char 1))
10803 (when (and (not what)
10804 (not (looking-at
10805 (concat "[ \t]*"
10806 org-keyword-time-not-clock-regexp))))
10807 ;; Nothing to add, nothing to remove...... :-)
10808 (throw 'exit nil))
10809 (if (and (not (looking-at outline-regexp))
10810 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10811 "[^\r\n]*"))
10812 (not (equal (match-string 1) org-clock-string)))
10813 (narrow-to-region (match-beginning 0) (match-end 0))
10814 (insert-before-markers "\n")
10815 (backward-char 1)
10816 (narrow-to-region (point) (point))
10817 (and org-adapt-indentation (org-indent-to-column col)))
10818 ;; Check if we have to remove something.
10819 (setq list (cons what remove))
10820 (while list
10821 (setq elt (pop list))
10822 (goto-char (point-min))
10823 (when (or (and (eq elt 'scheduled)
10824 (re-search-forward org-scheduled-time-regexp nil t))
10825 (and (eq elt 'deadline)
10826 (re-search-forward org-deadline-time-regexp nil t))
10827 (and (eq elt 'closed)
10828 (re-search-forward org-closed-time-regexp nil t)))
10829 (replace-match "")
10830 (if (looking-at "--+<[^>]+>") (replace-match ""))
10831 (skip-chars-backward " ")
10832 (if (looking-at " +") (replace-match ""))))
10833 (goto-char (point-max))
10834 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10835 (when what
10836 (insert
10837 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10838 (cond ((eq what 'scheduled) org-scheduled-string)
10839 ((eq what 'deadline) org-deadline-string)
10840 ((eq what 'closed) org-closed-string))
10841 " ")
10842 (setq ts (org-insert-time-stamp
10843 time
10844 (or org-time-was-given
10845 (and (eq what 'closed) org-log-done-with-time))
10846 (eq what 'closed)
10847 nil nil (list org-end-time-was-given)))
10848 (end-of-line 1))
10849 (goto-char (point-min))
10850 (widen)
10851 (if (and (looking-at "[ \t]+\n")
10852 (equal (char-before) ?\n))
10853 (delete-region (1- (point)) (point-at-eol)))
10854 ts))))))
10856 (defvar org-log-note-marker (make-marker))
10857 (defvar org-log-note-purpose nil)
10858 (defvar org-log-note-state nil)
10859 (defvar org-log-note-previous-state nil)
10860 (defvar org-log-note-how nil)
10861 (defvar org-log-note-extra nil)
10862 (defvar org-log-note-window-configuration nil)
10863 (defvar org-log-note-return-to (make-marker))
10864 (defvar org-log-post-message nil
10865 "Message to be displayed after a log note has been stored.
10866 The auto-repeater uses this.")
10868 (defun org-add-note ()
10869 "Add a note to the current entry.
10870 This is done in the same way as adding a state change note."
10871 (interactive)
10872 (org-add-log-setup 'note nil nil 'findpos nil))
10874 (defvar org-property-end-re)
10875 (defun org-add-log-setup (&optional purpose state prev-state
10876 findpos how &optional extra)
10877 "Set up the post command hook to take a note.
10878 If this is about to TODO state change, the new state is expected in STATE.
10879 When FINDPOS is non-nil, find the correct position for the note in
10880 the current entry. If not, assume that it can be inserted at point.
10881 HOW is an indicator what kind of note should be created.
10882 EXTRA is additional text that will be inserted into the notes buffer."
10883 (let* ((org-log-into-drawer (org-log-into-drawer))
10884 (drawer (cond ((stringp org-log-into-drawer)
10885 org-log-into-drawer)
10886 (org-log-into-drawer "LOGBOOK")
10887 (t nil))))
10888 (save-restriction
10889 (save-excursion
10890 (when findpos
10891 (org-back-to-heading t)
10892 (narrow-to-region (point) (save-excursion
10893 (outline-next-heading) (point)))
10894 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10895 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10896 "[^\r\n]*\\)?"))
10897 (goto-char (match-end 0))
10898 (cond
10899 (drawer
10900 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10901 nil t)
10902 (progn
10903 (goto-char (match-end 0))
10904 (or org-log-states-order-reversed
10905 (and (re-search-forward org-property-end-re nil t)
10906 (goto-char (1- (match-beginning 0))))))
10907 (insert "\n:" drawer ":\n:END:")
10908 (beginning-of-line 0)
10909 (org-indent-line-function)
10910 (beginning-of-line 2)
10911 (org-indent-line-function)
10912 (end-of-line 0)))
10913 ((and org-log-state-notes-insert-after-drawers
10914 (save-excursion
10915 (forward-line) (looking-at org-drawer-regexp)))
10916 (forward-line)
10917 (while (looking-at org-drawer-regexp)
10918 (goto-char (match-end 0))
10919 (re-search-forward org-property-end-re (point-max) t)
10920 (forward-line))
10921 (forward-line -1)))
10922 (unless org-log-states-order-reversed
10923 (and (= (char-after) ?\n) (forward-char 1))
10924 (org-skip-over-state-notes)
10925 (skip-chars-backward " \t\n\r")))
10926 (move-marker org-log-note-marker (point))
10927 (setq org-log-note-purpose purpose
10928 org-log-note-state state
10929 org-log-note-previous-state prev-state
10930 org-log-note-how how
10931 org-log-note-extra extra)
10932 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10934 (defun org-skip-over-state-notes ()
10935 "Skip past the list of State notes in an entry."
10936 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10937 (while (looking-at "[ \t]*- State")
10938 (condition-case nil
10939 (org-next-item)
10940 (error (org-end-of-item)))))
10942 (defun org-add-log-note (&optional purpose)
10943 "Pop up a window for taking a note, and add this note later at point."
10944 (remove-hook 'post-command-hook 'org-add-log-note)
10945 (setq org-log-note-window-configuration (current-window-configuration))
10946 (delete-other-windows)
10947 (move-marker org-log-note-return-to (point))
10948 (switch-to-buffer (marker-buffer org-log-note-marker))
10949 (goto-char org-log-note-marker)
10950 (org-switch-to-buffer-other-window "*Org Note*")
10951 (erase-buffer)
10952 (if (memq org-log-note-how '(time state))
10953 (let (current-prefix-arg) (org-store-log-note))
10954 (let ((org-inhibit-startup t)) (org-mode))
10955 (insert (format "# Insert note for %s.
10956 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10957 (cond
10958 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10959 ((eq org-log-note-purpose 'done) "closed todo item")
10960 ((eq org-log-note-purpose 'state)
10961 (format "state change from \"%s\" to \"%s\""
10962 (or org-log-note-previous-state "")
10963 (or org-log-note-state "")))
10964 ((eq org-log-note-purpose 'reschedule)
10965 "rescheduling")
10966 ((eq org-log-note-purpose 'delschedule)
10967 "no longer scheduled")
10968 ((eq org-log-note-purpose 'redeadline)
10969 "changing deadline")
10970 ((eq org-log-note-purpose 'deldeadline)
10971 "removing deadline")
10972 ((eq org-log-note-purpose 'note)
10973 "this entry")
10974 (t (error "This should not happen")))))
10975 (if org-log-note-extra (insert org-log-note-extra))
10976 (org-set-local 'org-finish-function 'org-store-log-note)))
10978 (defvar org-note-abort nil) ; dynamically scoped
10979 (defun org-store-log-note ()
10980 "Finish taking a log note, and insert it to where it belongs."
10981 (let ((txt (buffer-string))
10982 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10983 lines ind)
10984 (kill-buffer (current-buffer))
10985 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10986 (setq txt (replace-match "" t t txt)))
10987 (if (string-match "\\s-+\\'" txt)
10988 (setq txt (replace-match "" t t txt)))
10989 (setq lines (org-split-string txt "\n"))
10990 (when (and note (string-match "\\S-" note))
10991 (setq note
10992 (org-replace-escapes
10993 note
10994 (list (cons "%u" (user-login-name))
10995 (cons "%U" user-full-name)
10996 (cons "%t" (format-time-string
10997 (org-time-stamp-format 'long 'inactive)
10998 (current-time)))
10999 (cons "%s" (if org-log-note-state
11000 (concat "\"" org-log-note-state "\"")
11001 ""))
11002 (cons "%S" (if org-log-note-previous-state
11003 (concat "\"" org-log-note-previous-state "\"")
11004 "\"\"")))))
11005 (if lines (setq note (concat note " \\\\")))
11006 (push note lines))
11007 (when (or current-prefix-arg org-note-abort)
11008 (when org-log-into-drawer
11009 (org-remove-empty-drawer-at
11010 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11011 org-log-note-marker))
11012 (setq lines nil))
11013 (when lines
11014 (with-current-buffer (marker-buffer org-log-note-marker)
11015 (save-excursion
11016 (goto-char org-log-note-marker)
11017 (move-marker org-log-note-marker nil)
11018 (end-of-line 1)
11019 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11020 (insert "- " (pop lines))
11021 (org-indent-line-function)
11022 (beginning-of-line 1)
11023 (looking-at "[ \t]*")
11024 (setq ind (concat (match-string 0) " "))
11025 (end-of-line 1)
11026 (while lines (insert "\n" ind (pop lines)))
11027 (message "Note stored")
11028 (org-back-to-heading t)
11029 (org-cycle-hide-drawers 'children)))))
11030 (set-window-configuration org-log-note-window-configuration)
11031 (with-current-buffer (marker-buffer org-log-note-return-to)
11032 (goto-char org-log-note-return-to))
11033 (move-marker org-log-note-return-to nil)
11034 (and org-log-post-message (message "%s" org-log-post-message)))
11036 (defun org-remove-empty-drawer-at (drawer pos)
11037 "Remove an empty drawer DRAWER at position POS.
11038 POS may also be a marker."
11039 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11040 (save-excursion
11041 (save-restriction
11042 (widen)
11043 (goto-char pos)
11044 (if (org-in-regexp
11045 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11046 (replace-match ""))))))
11048 (defun org-sparse-tree (&optional arg)
11049 "Create a sparse tree, prompt for the details.
11050 This command can create sparse trees. You first need to select the type
11051 of match used to create the tree:
11053 t Show entries with a specific TODO keyword.
11054 m Show entries selected by a tags/property match.
11055 p Enter a property name and its value (both with completion on existing
11056 names/values) and show entries with that property.
11057 / Show entries matching a regular expression (`r' can be used as well)
11058 d Show deadlines due within `org-deadline-warning-days'.
11059 b Show deadlines and scheduled items before a date.
11060 a Show deadlines and scheduled items after a date."
11061 (interactive "P")
11062 (let (ans kwd value)
11063 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11064 (setq ans (read-char-exclusive))
11065 (cond
11066 ((equal ans ?d)
11067 (call-interactively 'org-check-deadlines))
11068 ((equal ans ?b)
11069 (call-interactively 'org-check-before-date))
11070 ((equal ans ?a)
11071 (call-interactively 'org-check-after-date))
11072 ((equal ans ?t)
11073 (org-show-todo-tree '(4)))
11074 ((member ans '(?T ?m))
11075 (call-interactively 'org-match-sparse-tree))
11076 ((member ans '(?p ?P))
11077 (setq kwd (org-icompleting-read "Property: "
11078 (mapcar 'list (org-buffer-property-keys))))
11079 (setq value (org-icompleting-read "Value: "
11080 (mapcar 'list (org-property-values kwd))))
11081 (unless (string-match "\\`{.*}\\'" value)
11082 (setq value (concat "\"" value "\"")))
11083 (org-match-sparse-tree arg (concat kwd "=" value)))
11084 ((member ans '(?r ?R ?/))
11085 (call-interactively 'org-occur))
11086 (t (error "No such sparse tree command \"%c\"" ans)))))
11088 (defvar org-occur-highlights nil
11089 "List of overlays used for occur matches.")
11090 (make-variable-buffer-local 'org-occur-highlights)
11091 (defvar org-occur-parameters nil
11092 "Parameters of the active org-occur calls.
11093 This is a list, each call to org-occur pushes as cons cell,
11094 containing the regular expression and the callback, onto the list.
11095 The list can contain several entries if `org-occur' has been called
11096 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11097 will only contain one set of parameters. When the highlights are
11098 removed (for example with `C-c C-c', or with the next edit (depending
11099 on `org-remove-highlights-with-change'), this variable is emptied
11100 as well.")
11101 (make-variable-buffer-local 'org-occur-parameters)
11103 (defun org-occur (regexp &optional keep-previous callback)
11104 "Make a compact tree which shows all matches of REGEXP.
11105 The tree will show the lines where the regexp matches, and all higher
11106 headlines above the match. It will also show the heading after the match,
11107 to make sure editing the matching entry is easy.
11108 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11109 call to `org-occur' will be kept, to allow stacking of calls to this
11110 command.
11111 If CALLBACK is non-nil, it is a function which is called to confirm
11112 that the match should indeed be shown."
11113 (interactive "sRegexp: \nP")
11114 (when (equal regexp "")
11115 (error "Regexp cannot be empty"))
11116 (unless keep-previous
11117 (org-remove-occur-highlights nil nil t))
11118 (push (cons regexp callback) org-occur-parameters)
11119 (let ((cnt 0))
11120 (save-excursion
11121 (goto-char (point-min))
11122 (if (or (not keep-previous) ; do not want to keep
11123 (not org-occur-highlights)) ; no previous matches
11124 ;; hide everything
11125 (org-overview))
11126 (while (re-search-forward regexp nil t)
11127 (when (or (not callback)
11128 (save-match-data (funcall callback)))
11129 (setq cnt (1+ cnt))
11130 (when org-highlight-sparse-tree-matches
11131 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11132 (org-show-context 'occur-tree))))
11133 (when org-remove-highlights-with-change
11134 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11135 nil 'local))
11136 (unless org-sparse-tree-open-archived-trees
11137 (org-hide-archived-subtrees (point-min) (point-max)))
11138 (run-hooks 'org-occur-hook)
11139 (if (interactive-p)
11140 (message "%d match(es) for regexp %s" cnt regexp))
11141 cnt))
11143 (defun org-show-context (&optional key)
11144 "Make sure point and context and visible.
11145 How much context is shown depends upon the variables
11146 `org-show-hierarchy-above', `org-show-following-heading'. and
11147 `org-show-siblings'."
11148 (let ((heading-p (org-on-heading-p t))
11149 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11150 (following-p (org-get-alist-option org-show-following-heading key))
11151 (entry-p (org-get-alist-option org-show-entry-below key))
11152 (siblings-p (org-get-alist-option org-show-siblings key)))
11153 (catch 'exit
11154 ;; Show heading or entry text
11155 (if (and heading-p (not entry-p))
11156 (org-flag-heading nil) ; only show the heading
11157 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11158 (org-show-hidden-entry))) ; show entire entry
11159 (when following-p
11160 ;; Show next sibling, or heading below text
11161 (save-excursion
11162 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11163 (org-flag-heading nil))))
11164 (when siblings-p (org-show-siblings))
11165 (when hierarchy-p
11166 ;; show all higher headings, possibly with siblings
11167 (save-excursion
11168 (while (and (condition-case nil
11169 (progn (org-up-heading-all 1) t)
11170 (error nil))
11171 (not (bobp)))
11172 (org-flag-heading nil)
11173 (when siblings-p (org-show-siblings))))))))
11175 (defun org-reveal (&optional siblings)
11176 "Show current entry, hierarchy above it, and the following headline.
11177 This can be used to show a consistent set of context around locations
11178 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11179 not t for the search context.
11181 With optional argument SIBLINGS, on each level of the hierarchy all
11182 siblings are shown. This repairs the tree structure to what it would
11183 look like when opened with hierarchical calls to `org-cycle'."
11184 (interactive "P")
11185 (let ((org-show-hierarchy-above t)
11186 (org-show-following-heading t)
11187 (org-show-siblings (if siblings t org-show-siblings)))
11188 (org-show-context nil)))
11190 (defun org-highlight-new-match (beg end)
11191 "Highlight from BEG to END and mark the highlight is an occur headline."
11192 (let ((ov (org-make-overlay beg end)))
11193 (org-overlay-put ov 'face 'secondary-selection)
11194 (push ov org-occur-highlights)))
11196 (defun org-remove-occur-highlights (&optional beg end noremove)
11197 "Remove the occur highlights from the buffer.
11198 BEG and END are ignored. If NOREMOVE is nil, remove this function
11199 from the `before-change-functions' in the current buffer."
11200 (interactive)
11201 (unless org-inhibit-highlight-removal
11202 (mapc 'org-delete-overlay org-occur-highlights)
11203 (setq org-occur-highlights nil)
11204 (setq org-occur-parameters nil)
11205 (unless noremove
11206 (remove-hook 'before-change-functions
11207 'org-remove-occur-highlights 'local))))
11209 ;;;; Priorities
11211 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11212 "Regular expression matching the priority indicator.")
11214 (defvar org-remove-priority-next-time nil)
11216 (defun org-priority-up ()
11217 "Increase the priority of the current item."
11218 (interactive)
11219 (org-priority 'up))
11221 (defun org-priority-down ()
11222 "Decrease the priority of the current item."
11223 (interactive)
11224 (org-priority 'down))
11226 (defun org-priority (&optional action)
11227 "Change the priority of an item by ARG.
11228 ACTION can be `set', `up', `down', or a character."
11229 (interactive)
11230 (unless org-enable-priority-commands
11231 (error "Priority commands are disabled"))
11232 (setq action (or action 'set))
11233 (let (current new news have remove)
11234 (save-excursion
11235 (org-back-to-heading t)
11236 (if (looking-at org-priority-regexp)
11237 (setq current (string-to-char (match-string 2))
11238 have t)
11239 (setq current org-default-priority))
11240 (cond
11241 ((eq action 'remove)
11242 (setq remove t new ?\ ))
11243 ((or (eq action 'set)
11244 (if (featurep 'xemacs) (characterp action) (integerp action)))
11245 (if (not (eq action 'set))
11246 (setq new action)
11247 (message "Priority %c-%c, SPC to remove: "
11248 org-highest-priority org-lowest-priority)
11249 (setq new (read-char-exclusive)))
11250 (if (and (= (upcase org-highest-priority) org-highest-priority)
11251 (= (upcase org-lowest-priority) org-lowest-priority))
11252 (setq new (upcase new)))
11253 (cond ((equal new ?\ ) (setq remove t))
11254 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11255 (error "Priority must be between `%c' and `%c'"
11256 org-highest-priority org-lowest-priority))))
11257 ((eq action 'up)
11258 (if (and (not have) (eq last-command this-command))
11259 (setq new org-lowest-priority)
11260 (setq new (if (and org-priority-start-cycle-with-default (not have))
11261 org-default-priority (1- current)))))
11262 ((eq action 'down)
11263 (if (and (not have) (eq last-command this-command))
11264 (setq new org-highest-priority)
11265 (setq new (if (and org-priority-start-cycle-with-default (not have))
11266 org-default-priority (1+ current)))))
11267 (t (error "Invalid action")))
11268 (if (or (< (upcase new) org-highest-priority)
11269 (> (upcase new) org-lowest-priority))
11270 (setq remove t))
11271 (setq news (format "%c" new))
11272 (if have
11273 (if remove
11274 (replace-match "" t t nil 1)
11275 (replace-match news t t nil 2))
11276 (if remove
11277 (error "No priority cookie found in line")
11278 (let ((case-fold-search nil))
11279 (looking-at org-todo-line-regexp))
11280 (if (match-end 2)
11281 (progn
11282 (goto-char (match-end 2))
11283 (insert " [#" news "]"))
11284 (goto-char (match-beginning 3))
11285 (insert "[#" news "] "))))
11286 (org-preserve-lc (org-set-tags nil 'align)))
11287 (if remove
11288 (message "Priority removed")
11289 (message "Priority of current item set to %s" news))))
11291 (defun org-get-priority (s)
11292 "Find priority cookie and return priority."
11293 (save-match-data
11294 (if (not (string-match org-priority-regexp s))
11295 (* 1000 (- org-lowest-priority org-default-priority))
11296 (* 1000 (- org-lowest-priority
11297 (string-to-char (match-string 2 s)))))))
11299 ;;;; Tags
11301 (defvar org-agenda-archives-mode)
11302 (defvar org-map-continue-from nil
11303 "Position from where mapping should continue.
11304 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11306 (defvar org-scanner-tags nil
11307 "The current tag list while the tags scanner is running.")
11308 (defvar org-trust-scanner-tags nil
11309 "Should `org-get-tags-at' use the tags fro the scanner.
11310 This is for internal dynamical scoping only.
11311 When this is non-nil, the function `org-get-tags-at' will return the value
11312 of `org-scanner-tags' instead of building the list by itself. This
11313 can lead to large speed-ups when the tags scanner is used in a file with
11314 many entries, and when the list of tags is retrieved, for example to
11315 obtain a list of properties. Building the tags list for each entry in such
11316 a file becomes an N^2 operation - but with this variable set, it scales
11317 as N.")
11319 (defun org-scan-tags (action matcher &optional todo-only)
11320 "Scan headline tags with inheritance and produce output ACTION.
11322 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11323 or `agenda' to produce an entry list for an agenda view. It can also be
11324 a Lisp form or a function that should be called at each matched headline, in
11325 this case the return value is a list of all return values from these calls.
11327 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11328 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11329 only lines with a TODO keyword are included in the output."
11330 (require 'org-agenda)
11331 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11332 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11333 (org-re
11334 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11335 (props (list 'face 'default
11336 'done-face 'org-agenda-done
11337 'undone-face 'default
11338 'mouse-face 'highlight
11339 'org-not-done-regexp org-not-done-regexp
11340 'org-todo-regexp org-todo-regexp
11341 'help-echo
11342 (format "mouse-2 or RET jump to org file %s"
11343 (abbreviate-file-name
11344 (or (buffer-file-name (buffer-base-buffer))
11345 (buffer-name (buffer-base-buffer)))))))
11346 (case-fold-search nil)
11347 (org-map-continue-from nil)
11348 lspos tags tags-list
11349 (tags-alist (list (cons 0 org-file-tags)))
11350 (llast 0) rtn rtn1 level category i txt
11351 todo marker entry priority)
11352 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11353 (setq action (list 'lambda nil action)))
11354 (save-excursion
11355 (goto-char (point-min))
11356 (when (eq action 'sparse-tree)
11357 (org-overview)
11358 (org-remove-occur-highlights))
11359 (while (re-search-forward re nil t)
11360 (catch :skip
11361 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11362 tags (if (match-end 4) (org-match-string-no-properties 4)))
11363 (goto-char (setq lspos (match-beginning 0)))
11364 (setq level (org-reduced-level (funcall outline-level))
11365 category (org-get-category))
11366 (setq i llast llast level)
11367 ;; remove tag lists from same and sublevels
11368 (while (>= i level)
11369 (when (setq entry (assoc i tags-alist))
11370 (setq tags-alist (delete entry tags-alist)))
11371 (setq i (1- i)))
11372 ;; add the next tags
11373 (when tags
11374 (setq tags (org-split-string tags ":")
11375 tags-alist
11376 (cons (cons level tags) tags-alist)))
11377 ;; compile tags for current headline
11378 (setq tags-list
11379 (if org-use-tag-inheritance
11380 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11381 tags)
11382 org-scanner-tags tags-list)
11383 (when org-use-tag-inheritance
11384 (setcdr (car tags-alist)
11385 (mapcar (lambda (x)
11386 (setq x (copy-sequence x))
11387 (org-add-prop-inherited x))
11388 (cdar tags-alist))))
11389 (when (and tags org-use-tag-inheritance
11390 (or (not (eq t org-use-tag-inheritance))
11391 org-tags-exclude-from-inheritance))
11392 ;; selective inheritance, remove uninherited ones
11393 (setcdr (car tags-alist)
11394 (org-remove-uniherited-tags (cdar tags-alist))))
11395 (when (and (or (not todo-only)
11396 (and (member todo org-not-done-keywords)
11397 (or (not org-agenda-tags-todo-honor-ignore-options)
11398 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11399 (let ((case-fold-search t)) (eval matcher))
11401 (not (member org-archive-tag tags-list))
11402 ;; we have an archive tag, should we use this anyway?
11403 (or (not org-agenda-skip-archived-trees)
11404 (and (eq action 'agenda) org-agenda-archives-mode))))
11405 (unless (eq action 'sparse-tree) (org-agenda-skip))
11407 ;; select this headline
11409 (cond
11410 ((eq action 'sparse-tree)
11411 (and org-highlight-sparse-tree-matches
11412 (org-get-heading) (match-end 0)
11413 (org-highlight-new-match
11414 (match-beginning 0) (match-beginning 1)))
11415 (org-show-context 'tags-tree))
11416 ((eq action 'agenda)
11417 (setq txt (org-format-agenda-item
11419 (concat
11420 (if (eq org-tags-match-list-sublevels 'indented)
11421 (make-string (1- level) ?.) "")
11422 (org-get-heading))
11423 category
11424 tags-list
11426 priority (org-get-priority txt))
11427 (goto-char lspos)
11428 (setq marker (org-agenda-new-marker))
11429 (org-add-props txt props
11430 'org-marker marker 'org-hd-marker marker 'org-category category
11431 'todo-state todo
11432 'priority priority 'type "tagsmatch")
11433 (push txt rtn))
11434 ((functionp action)
11435 (setq org-map-continue-from nil)
11436 (save-excursion
11437 (setq rtn1 (funcall action))
11438 (push rtn1 rtn)))
11439 (t (error "Invalid action")))
11441 ;; if we are to skip sublevels, jump to end of subtree
11442 (unless org-tags-match-list-sublevels
11443 (org-end-of-subtree t)
11444 (backward-char 1))))
11445 ;; Get the correct position from where to continue
11446 (if org-map-continue-from
11447 (goto-char org-map-continue-from)
11448 (and (= (point) lspos) (end-of-line 1)))))
11449 (when (and (eq action 'sparse-tree)
11450 (not org-sparse-tree-open-archived-trees))
11451 (org-hide-archived-subtrees (point-min) (point-max)))
11452 (nreverse rtn)))
11454 (defun org-remove-uniherited-tags (tags)
11455 "Remove all tags that are not inherited from the list TAGS."
11456 (cond
11457 ((eq org-use-tag-inheritance t)
11458 (if org-tags-exclude-from-inheritance
11459 (org-delete-all org-tags-exclude-from-inheritance tags)
11460 tags))
11461 ((not org-use-tag-inheritance) nil)
11462 ((stringp org-use-tag-inheritance)
11463 (delq nil (mapcar
11464 (lambda (x)
11465 (if (and (string-match org-use-tag-inheritance x)
11466 (not (member x org-tags-exclude-from-inheritance)))
11467 x nil))
11468 tags)))
11469 ((listp org-use-tag-inheritance)
11470 (delq nil (mapcar
11471 (lambda (x)
11472 (if (member x org-use-tag-inheritance) x nil))
11473 tags)))))
11475 (defvar todo-only) ;; dynamically scoped
11477 (defun org-match-sparse-tree (&optional todo-only match)
11478 "Create a sparse tree according to tags string MATCH.
11479 MATCH can contain positive and negative selection of tags, like
11480 \"+WORK+URGENT-WITHBOSS\".
11481 If optional argument TODO-ONLY is non-nil, only select lines that are
11482 also TODO lines."
11483 (interactive "P")
11484 (org-prepare-agenda-buffers (list (current-buffer)))
11485 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11487 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11489 (defvar org-cached-props nil)
11490 (defun org-cached-entry-get (pom property)
11491 (if (or (eq t org-use-property-inheritance)
11492 (and (stringp org-use-property-inheritance)
11493 (string-match org-use-property-inheritance property))
11494 (and (listp org-use-property-inheritance)
11495 (member property org-use-property-inheritance)))
11496 ;; Caching is not possible, check it directly
11497 (org-entry-get pom property 'inherit)
11498 ;; Get all properties, so that we can do complicated checks easily
11499 (cdr (assoc property (or org-cached-props
11500 (setq org-cached-props
11501 (org-entry-properties pom)))))))
11503 (defun org-global-tags-completion-table (&optional files)
11504 "Return the list of all tags in all agenda buffer/files."
11505 (save-excursion
11506 (org-uniquify
11507 (delq nil
11508 (apply 'append
11509 (mapcar
11510 (lambda (file)
11511 (set-buffer (find-file-noselect file))
11512 (append (org-get-buffer-tags)
11513 (mapcar (lambda (x) (if (stringp (car-safe x))
11514 (list (car-safe x)) nil))
11515 org-tag-alist)))
11516 (if (and files (car files))
11517 files
11518 (org-agenda-files))))))))
11520 (defun org-make-tags-matcher (match)
11521 "Create the TAGS//TODO matcher form for the selection string MATCH."
11522 ;; todo-only is scoped dynamically into this function, and the function
11523 ;; may change it if the matcher asks for it.
11524 (unless match
11525 ;; Get a new match request, with completion
11526 (let ((org-last-tags-completion-table
11527 (org-global-tags-completion-table)))
11528 (setq match (org-completing-read-no-i
11529 "Match: " 'org-tags-completion-function nil nil nil
11530 'org-tags-history))))
11532 ;; Parse the string and create a lisp form
11533 (let ((match0 match)
11534 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11535 minus tag mm
11536 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11537 orterms term orlist re-p str-p level-p level-op time-p
11538 prop-p pn pv po cat-p gv rest)
11539 (if (string-match "/+" match)
11540 ;; match contains also a todo-matching request
11541 (progn
11542 (setq tagsmatch (substring match 0 (match-beginning 0))
11543 todomatch (substring match (match-end 0)))
11544 (if (string-match "^!" todomatch)
11545 (setq todo-only t todomatch (substring todomatch 1)))
11546 (if (string-match "^\\s-*$" todomatch)
11547 (setq todomatch nil)))
11548 ;; only matching tags
11549 (setq tagsmatch match todomatch nil))
11551 ;; Make the tags matcher
11552 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11553 (setq tagsmatcher t)
11554 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11555 (while (setq term (pop orterms))
11556 (while (and (equal (substring term -1) "\\") orterms)
11557 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11558 (while (string-match re term)
11559 (setq rest (substring term (match-end 0))
11560 minus (and (match-end 1)
11561 (equal (match-string 1 term) "-"))
11562 tag (match-string 2 term)
11563 re-p (equal (string-to-char tag) ?{)
11564 level-p (match-end 4)
11565 prop-p (match-end 5)
11566 mm (cond
11567 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11568 (level-p
11569 (setq level-op (org-op-to-function (match-string 3 term)))
11570 `(,level-op level ,(string-to-number
11571 (match-string 4 term))))
11572 (prop-p
11573 (setq pn (match-string 5 term)
11574 po (match-string 6 term)
11575 pv (match-string 7 term)
11576 cat-p (equal pn "CATEGORY")
11577 re-p (equal (string-to-char pv) ?{)
11578 str-p (equal (string-to-char pv) ?\")
11579 time-p (save-match-data
11580 (string-match "^\"[[<].*[]>]\"$" pv))
11581 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11582 (if time-p (setq pv (org-matcher-time pv)))
11583 (setq po (org-op-to-function po (if time-p 'time str-p)))
11584 (cond
11585 ((equal pn "CATEGORY")
11586 (setq gv '(get-text-property (point) 'org-category)))
11587 ((equal pn "TODO")
11588 (setq gv 'todo))
11590 (setq gv `(org-cached-entry-get nil ,pn))))
11591 (if re-p
11592 (if (eq po 'org<>)
11593 `(not (string-match ,pv (or ,gv "")))
11594 `(string-match ,pv (or ,gv "")))
11595 (if str-p
11596 `(,po (or ,gv "") ,pv)
11597 `(,po (string-to-number (or ,gv ""))
11598 ,(string-to-number pv) ))))
11599 (t `(member ,tag tags-list)))
11600 mm (if minus (list 'not mm) mm)
11601 term rest)
11602 (push mm tagsmatcher))
11603 (push (if (> (length tagsmatcher) 1)
11604 (cons 'and tagsmatcher)
11605 (car tagsmatcher))
11606 orlist)
11607 (setq tagsmatcher nil))
11608 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11609 (setq tagsmatcher
11610 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11611 ;; Make the todo matcher
11612 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11613 (setq todomatcher t)
11614 (setq orterms (org-split-string todomatch "|") orlist nil)
11615 (while (setq term (pop orterms))
11616 (while (string-match re term)
11617 (setq minus (and (match-end 1)
11618 (equal (match-string 1 term) "-"))
11619 kwd (match-string 2 term)
11620 re-p (equal (string-to-char kwd) ?{)
11621 term (substring term (match-end 0))
11622 mm (if re-p
11623 `(string-match ,(substring kwd 1 -1) todo)
11624 (list 'equal 'todo kwd))
11625 mm (if minus (list 'not mm) mm))
11626 (push mm todomatcher))
11627 (push (if (> (length todomatcher) 1)
11628 (cons 'and todomatcher)
11629 (car todomatcher))
11630 orlist)
11631 (setq todomatcher nil))
11632 (setq todomatcher (if (> (length orlist) 1)
11633 (cons 'or orlist) (car orlist))))
11635 ;; Return the string and lisp forms of the matcher
11636 (setq matcher (if todomatcher
11637 (list 'and tagsmatcher todomatcher)
11638 tagsmatcher))
11639 (cons match0 matcher)))
11641 (defun org-op-to-function (op &optional stringp)
11642 "Turn an operator into the appropriate function."
11643 (setq op
11644 (cond
11645 ((equal op "<" ) '(< string< org-time<))
11646 ((equal op ">" ) '(> org-string> org-time>))
11647 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11648 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11649 ((member op '("=" "==")) '(= string= org-time=))
11650 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11651 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11653 (defun org<> (a b) (not (= a b)))
11654 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11655 (defun org-string>= (a b) (not (string< a b)))
11656 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11657 (defun org-string<> (a b) (not (string= a b)))
11658 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11659 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11660 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11661 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11662 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11663 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11664 (defun org-2ft (s)
11665 "Convert S to a floating point time.
11666 If S is already a number, just return it. If it is a string, parse
11667 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11668 (cond
11669 ((numberp s) s)
11670 ((stringp s)
11671 (condition-case nil
11672 (float-time (apply 'encode-time (org-parse-time-string s)))
11673 (error 0.)))
11674 (t 0.)))
11676 (defun org-time-today ()
11677 "Time in seconds today at 0:00.
11678 Returns the float number of seconds since the beginning of the
11679 epoch to the beginning of today (00:00)."
11680 (float-time (apply 'encode-time
11681 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11683 (defun org-matcher-time (s)
11684 "Interpret a time comparison value."
11685 (save-match-data
11686 (cond
11687 ((string= s "<now>") (float-time))
11688 ((string= s "<today>") (org-time-today))
11689 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11690 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11691 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11692 (+ (org-time-today)
11693 (* (string-to-number (match-string 1 s))
11694 (cdr (assoc (match-string 2 s)
11695 '(("d" . 86400.0) ("w" . 604800.0)
11696 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11697 (t (org-2ft s)))))
11699 (defun org-match-any-p (re list)
11700 "Does re match any element of list?"
11701 (setq list (mapcar (lambda (x) (string-match re x)) list))
11702 (delq nil list))
11704 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11705 (defvar org-tags-overlay (org-make-overlay 1 1))
11706 (org-detach-overlay org-tags-overlay)
11708 (defun org-get-local-tags-at (&optional pos)
11709 "Get a list of tags defined in the current headline."
11710 (org-get-tags-at pos 'local))
11712 (defun org-get-local-tags ()
11713 "Get a list of tags defined in the current headline."
11714 (org-get-tags-at nil 'local))
11716 (defun org-get-tags-at (&optional pos local)
11717 "Get a list of all headline tags applicable at POS.
11718 POS defaults to point. If tags are inherited, the list contains
11719 the targets in the same sequence as the headlines appear, i.e.
11720 the tags of the current headline come last.
11721 When LOCAL is non-nil, only return tags from the current headline,
11722 ignore inherited ones."
11723 (interactive)
11724 (if (and org-trust-scanner-tags
11725 (or (not pos) (equal pos (point)))
11726 (not local))
11727 org-scanner-tags
11728 (let (tags ltags lastpos parent)
11729 (save-excursion
11730 (save-restriction
11731 (widen)
11732 (goto-char (or pos (point)))
11733 (save-match-data
11734 (catch 'done
11735 (condition-case nil
11736 (progn
11737 (org-back-to-heading t)
11738 (while (not (equal lastpos (point)))
11739 (setq lastpos (point))
11740 (when (looking-at
11741 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11742 (setq ltags (org-split-string
11743 (org-match-string-no-properties 1) ":"))
11744 (when parent
11745 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11746 (setq tags (append
11747 (if parent
11748 (org-remove-uniherited-tags ltags)
11749 ltags)
11750 tags)))
11751 (or org-use-tag-inheritance (throw 'done t))
11752 (if local (throw 'done t))
11753 (or (org-up-heading-safe) (error nil))
11754 (setq parent t)))
11755 (error nil)))))
11756 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11758 (defun org-add-prop-inherited (s)
11759 (add-text-properties 0 (length s) '(inherited t) s)
11762 (defun org-toggle-tag (tag &optional onoff)
11763 "Toggle the tag TAG for the current line.
11764 If ONOFF is `on' or `off', don't toggle but set to this state."
11765 (let (res current)
11766 (save-excursion
11767 (org-back-to-heading t)
11768 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11769 (point-at-eol) t)
11770 (progn
11771 (setq current (match-string 1))
11772 (replace-match ""))
11773 (setq current ""))
11774 (setq current (nreverse (org-split-string current ":")))
11775 (cond
11776 ((eq onoff 'on)
11777 (setq res t)
11778 (or (member tag current) (push tag current)))
11779 ((eq onoff 'off)
11780 (or (not (member tag current)) (setq current (delete tag current))))
11781 (t (if (member tag current)
11782 (setq current (delete tag current))
11783 (setq res t)
11784 (push tag current))))
11785 (end-of-line 1)
11786 (if current
11787 (progn
11788 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11789 (org-set-tags nil t))
11790 (delete-horizontal-space))
11791 (run-hooks 'org-after-tags-change-hook))
11792 res))
11794 (defun org-align-tags-here (to-col)
11795 ;; Assumes that this is a headline
11796 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11797 (beginning-of-line 1)
11798 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11799 (< pos (match-beginning 2)))
11800 (progn
11801 (setq tags-l (- (match-end 2) (match-beginning 2)))
11802 (goto-char (match-beginning 1))
11803 (insert " ")
11804 (delete-region (point) (1+ (match-beginning 2)))
11805 (setq ncol (max (1+ (current-column))
11806 (1+ col)
11807 (if (> to-col 0)
11808 to-col
11809 (- (abs to-col) tags-l))))
11810 (setq p (point))
11811 (insert (make-string (- ncol (current-column)) ?\ ))
11812 (setq ncol (current-column))
11813 (when indent-tabs-mode (tabify p (point-at-eol)))
11814 (org-move-to-column (min ncol col) t))
11815 (goto-char pos))))
11817 (defun org-set-tags-command (&optional arg just-align)
11818 "Call the set-tags command for the current entry."
11819 (interactive "P")
11820 (if (org-on-heading-p)
11821 (org-set-tags arg just-align)
11822 (save-excursion
11823 (org-back-to-heading t)
11824 (org-set-tags arg just-align))))
11826 (defun org-set-tags-to (data)
11827 "Set the tags of the current entry to DATA, replacing the current tags.
11828 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11829 If DATA is nil or the empty string, any tags will be removed."
11830 (interactive "sTags: ")
11831 (setq data
11832 (cond
11833 ((eq data nil) "")
11834 ((equal data "") "")
11835 ((stringp data)
11836 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11837 ":"))
11838 ((listp data)
11839 (concat ":" (mapconcat 'identity data ":") ":"))
11840 (t nil)))
11841 (when data
11842 (save-excursion
11843 (org-back-to-heading t)
11844 (when (looking-at org-complex-heading-regexp)
11845 (if (match-end 5)
11846 (progn
11847 (goto-char (match-beginning 5))
11848 (insert data)
11849 (delete-region (point) (point-at-eol))
11850 (org-set-tags nil 'align))
11851 (goto-char (point-at-eol))
11852 (insert " " data)
11853 (org-set-tags nil 'align)))
11854 (beginning-of-line 1)
11855 (if (looking-at ".*?\\([ \t]+\\)$")
11856 (delete-region (match-beginning 1) (match-end 1))))))
11858 (defun org-set-tags (&optional arg just-align)
11859 "Set the tags for the current headline.
11860 With prefix ARG, realign all tags in headings in the current buffer."
11861 (interactive "P")
11862 (let* ((re (concat "^" outline-regexp))
11863 (current (org-get-tags-string))
11864 (col (current-column))
11865 (org-setting-tags t)
11866 table current-tags inherited-tags ; computed below when needed
11867 tags p0 c0 c1 rpl)
11868 (if arg
11869 (save-excursion
11870 (goto-char (point-min))
11871 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11872 (while (re-search-forward re nil t)
11873 (org-set-tags nil t)
11874 (end-of-line 1)))
11875 (message "All tags realigned to column %d" org-tags-column))
11876 (if just-align
11877 (setq tags current)
11878 ;; Get a new set of tags from the user
11879 (save-excursion
11880 (setq table (append org-tag-persistent-alist
11881 (or org-tag-alist (org-get-buffer-tags))
11882 (and org-complete-tags-always-offer-all-agenda-tags
11883 (org-global-tags-completion-table (org-agenda-files))))
11884 org-last-tags-completion-table table
11885 current-tags (org-split-string current ":")
11886 inherited-tags (nreverse
11887 (nthcdr (length current-tags)
11888 (nreverse (org-get-tags-at))))
11889 tags
11890 (if (or (eq t org-use-fast-tag-selection)
11891 (and org-use-fast-tag-selection
11892 (delq nil (mapcar 'cdr table))))
11893 (org-fast-tag-selection
11894 current-tags inherited-tags table
11895 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11896 (let ((org-add-colon-after-tag-completion t))
11897 (org-trim
11898 (org-without-partial-completion
11899 (org-icompleting-read "Tags: " 'org-tags-completion-function
11900 nil nil current 'org-tags-history)))))))
11901 (while (string-match "[-+&]+" tags)
11902 ;; No boolean logic, just a list
11903 (setq tags (replace-match ":" t t tags))))
11905 (if org-tags-sort-function
11906 (setq tags (mapconcat 'identity
11907 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11908 org-tags-sort-function) ":")))
11910 (if (string-match "\\`[\t ]*\\'" tags)
11911 (setq tags "")
11912 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11913 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11915 ;; Insert new tags at the correct column
11916 (beginning-of-line 1)
11917 (cond
11918 ((and (equal current "") (equal tags "")))
11919 ((re-search-forward
11920 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11921 (point-at-eol) t)
11922 (if (equal tags "")
11923 (setq rpl "")
11924 (goto-char (match-beginning 0))
11925 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
11926 (1+ (point)) (point))
11927 c1 (max (1+ c0) (if (> org-tags-column 0)
11928 org-tags-column
11929 (- (- org-tags-column) (length tags))))
11930 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11931 (replace-match rpl t t)
11932 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11933 tags)
11934 (t (error "Tags alignment failed")))
11935 (org-move-to-column col)
11936 (unless just-align
11937 (run-hooks 'org-after-tags-change-hook)))))
11939 (defun org-change-tag-in-region (beg end tag off)
11940 "Add or remove TAG for each entry in the region.
11941 This works in the agenda, and also in an org-mode buffer."
11942 (interactive
11943 (list (region-beginning) (region-end)
11944 (let ((org-last-tags-completion-table
11945 (if (org-mode-p)
11946 (org-get-buffer-tags)
11947 (org-global-tags-completion-table))))
11948 (org-icompleting-read
11949 "Tag: " 'org-tags-completion-function nil nil nil
11950 'org-tags-history))
11951 (progn
11952 (message "[s]et or [r]emove? ")
11953 (equal (read-char-exclusive) ?r))))
11954 (if (fboundp 'deactivate-mark) (deactivate-mark))
11955 (let ((agendap (equal major-mode 'org-agenda-mode))
11956 l1 l2 m buf pos newhead (cnt 0))
11957 (goto-char end)
11958 (setq l2 (1- (org-current-line)))
11959 (goto-char beg)
11960 (setq l1 (org-current-line))
11961 (loop for l from l1 to l2 do
11962 (org-goto-line l)
11963 (setq m (get-text-property (point) 'org-hd-marker))
11964 (when (or (and (org-mode-p) (org-on-heading-p))
11965 (and agendap m))
11966 (setq buf (if agendap (marker-buffer m) (current-buffer))
11967 pos (if agendap m (point)))
11968 (with-current-buffer buf
11969 (save-excursion
11970 (save-restriction
11971 (goto-char pos)
11972 (setq cnt (1+ cnt))
11973 (org-toggle-tag tag (if off 'off 'on))
11974 (setq newhead (org-get-heading)))))
11975 (and agendap (org-agenda-change-all-lines newhead m))))
11976 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11978 (defun org-tags-completion-function (string predicate &optional flag)
11979 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11980 (confirm (lambda (x) (stringp (car x)))))
11981 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11982 (setq s1 (match-string 1 string)
11983 s2 (match-string 2 string))
11984 (setq s1 "" s2 string))
11985 (cond
11986 ((eq flag nil)
11987 ;; try completion
11988 (setq rtn (try-completion s2 ctable confirm))
11989 (if (stringp rtn)
11990 (setq rtn
11991 (concat s1 s2 (substring rtn (length s2))
11992 (if (and org-add-colon-after-tag-completion
11993 (assoc rtn ctable))
11994 ":" ""))))
11995 rtn)
11996 ((eq flag t)
11997 ;; all-completions
11998 (all-completions s2 ctable confirm)
12000 ((eq flag 'lambda)
12001 ;; exact match?
12002 (assoc s2 ctable)))
12005 (defun org-fast-tag-insert (kwd tags face &optional end)
12006 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12007 (insert (format "%-12s" (concat kwd ":"))
12008 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12009 (or end "")))
12011 (defun org-fast-tag-show-exit (flag)
12012 (save-excursion
12013 (org-goto-line 3)
12014 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12015 (replace-match ""))
12016 (when flag
12017 (end-of-line 1)
12018 (org-move-to-column (- (window-width) 19) t)
12019 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12021 (defun org-set-current-tags-overlay (current prefix)
12022 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12023 (if (featurep 'xemacs)
12024 (org-overlay-display org-tags-overlay (concat prefix s)
12025 'secondary-selection)
12026 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12027 (org-overlay-display org-tags-overlay (concat prefix s)))))
12029 (defvar org-last-tag-selection-key nil)
12030 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12031 "Fast tag selection with single keys.
12032 CURRENT is the current list of tags in the headline, INHERITED is the
12033 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12034 possibly with grouping information. TODO-TABLE is a similar table with
12035 TODO keywords, should these have keys assigned to them.
12036 If the keys are nil, a-z are automatically assigned.
12037 Returns the new tags string, or nil to not change the current settings."
12038 (let* ((fulltable (append table todo-table))
12039 (maxlen (apply 'max (mapcar
12040 (lambda (x)
12041 (if (stringp (car x)) (string-width (car x)) 0))
12042 fulltable)))
12043 (buf (current-buffer))
12044 (expert (eq org-fast-tag-selection-single-key 'expert))
12045 (buffer-tags nil)
12046 (fwidth (+ maxlen 3 1 3))
12047 (ncol (/ (- (window-width) 4) fwidth))
12048 (i-face 'org-done)
12049 (c-face 'org-todo)
12050 tg cnt e c char c1 c2 ntable tbl rtn
12051 ov-start ov-end ov-prefix
12052 (exit-after-next org-fast-tag-selection-single-key)
12053 (done-keywords org-done-keywords)
12054 groups ingroup)
12055 (save-excursion
12056 (beginning-of-line 1)
12057 (if (looking-at
12058 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12059 (setq ov-start (match-beginning 1)
12060 ov-end (match-end 1)
12061 ov-prefix "")
12062 (setq ov-start (1- (point-at-eol))
12063 ov-end (1+ ov-start))
12064 (skip-chars-forward "^\n\r")
12065 (setq ov-prefix
12066 (concat
12067 (buffer-substring (1- (point)) (point))
12068 (if (> (current-column) org-tags-column)
12070 (make-string (- org-tags-column (current-column)) ?\ ))))))
12071 (org-move-overlay org-tags-overlay ov-start ov-end)
12072 (save-window-excursion
12073 (if expert
12074 (set-buffer (get-buffer-create " *Org tags*"))
12075 (delete-other-windows)
12076 (split-window-vertically)
12077 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12078 (erase-buffer)
12079 (org-set-local 'org-done-keywords done-keywords)
12080 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12081 (org-fast-tag-insert "Current" current c-face "\n\n")
12082 (org-fast-tag-show-exit exit-after-next)
12083 (org-set-current-tags-overlay current ov-prefix)
12084 (setq tbl fulltable char ?a cnt 0)
12085 (while (setq e (pop tbl))
12086 (cond
12087 ((equal (car e) :startgroup)
12088 (push '() groups) (setq ingroup t)
12089 (when (not (= cnt 0))
12090 (setq cnt 0)
12091 (insert "\n"))
12092 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12093 ((equal (car e) :endgroup)
12094 (setq ingroup nil cnt 0)
12095 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12096 ((equal e '(:newline))
12097 (when (not (= cnt 0))
12098 (setq cnt 0)
12099 (insert "\n")
12100 (setq e (car tbl))
12101 (while (equal (car tbl) '(:newline))
12102 (insert "\n")
12103 (setq tbl (cdr tbl)))))
12105 (setq tg (copy-sequence (car e)) c2 nil)
12106 (if (cdr e)
12107 (setq c (cdr e))
12108 ;; automatically assign a character.
12109 (setq c1 (string-to-char
12110 (downcase (substring
12111 tg (if (= (string-to-char tg) ?@) 1 0)))))
12112 (if (or (rassoc c1 ntable) (rassoc c1 table))
12113 (while (or (rassoc char ntable) (rassoc char table))
12114 (setq char (1+ char)))
12115 (setq c2 c1))
12116 (setq c (or c2 char)))
12117 (if ingroup (push tg (car groups)))
12118 (setq tg (org-add-props tg nil 'face
12119 (cond
12120 ((not (assoc tg table))
12121 (org-get-todo-face tg))
12122 ((member tg current) c-face)
12123 ((member tg inherited) i-face)
12124 (t nil))))
12125 (if (and (= cnt 0) (not ingroup)) (insert " "))
12126 (insert "[" c "] " tg (make-string
12127 (- fwidth 4 (length tg)) ?\ ))
12128 (push (cons tg c) ntable)
12129 (when (= (setq cnt (1+ cnt)) ncol)
12130 (insert "\n")
12131 (if ingroup (insert " "))
12132 (setq cnt 0)))))
12133 (setq ntable (nreverse ntable))
12134 (insert "\n")
12135 (goto-char (point-min))
12136 (if (not expert) (org-fit-window-to-buffer))
12137 (setq rtn
12138 (catch 'exit
12139 (while t
12140 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12141 (if (not groups) "no " "")
12142 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12143 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12144 (setq org-last-tag-selection-key c)
12145 (cond
12146 ((= c ?\r) (throw 'exit t))
12147 ((= c ?!)
12148 (setq groups (not groups))
12149 (goto-char (point-min))
12150 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12151 ((= c ?\C-c)
12152 (if (not expert)
12153 (org-fast-tag-show-exit
12154 (setq exit-after-next (not exit-after-next)))
12155 (setq expert nil)
12156 (delete-other-windows)
12157 (split-window-vertically)
12158 (org-switch-to-buffer-other-window " *Org tags*")
12159 (org-fit-window-to-buffer)))
12160 ((or (= c ?\C-g)
12161 (and (= c ?q) (not (rassoc c ntable))))
12162 (org-detach-overlay org-tags-overlay)
12163 (setq quit-flag t))
12164 ((= c ?\ )
12165 (setq current nil)
12166 (if exit-after-next (setq exit-after-next 'now)))
12167 ((= c ?\t)
12168 (condition-case nil
12169 (setq tg (org-icompleting-read
12170 "Tag: "
12171 (or buffer-tags
12172 (with-current-buffer buf
12173 (org-get-buffer-tags)))))
12174 (quit (setq tg "")))
12175 (when (string-match "\\S-" tg)
12176 (add-to-list 'buffer-tags (list tg))
12177 (if (member tg current)
12178 (setq current (delete tg current))
12179 (push tg current)))
12180 (if exit-after-next (setq exit-after-next 'now)))
12181 ((setq e (rassoc c todo-table) tg (car e))
12182 (with-current-buffer buf
12183 (save-excursion (org-todo tg)))
12184 (if exit-after-next (setq exit-after-next 'now)))
12185 ((setq e (rassoc c ntable) tg (car e))
12186 (if (member tg current)
12187 (setq current (delete tg current))
12188 (loop for g in groups do
12189 (if (member tg g)
12190 (mapc (lambda (x)
12191 (setq current (delete x current)))
12192 g)))
12193 (push tg current))
12194 (if exit-after-next (setq exit-after-next 'now))))
12196 ;; Create a sorted list
12197 (setq current
12198 (sort current
12199 (lambda (a b)
12200 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12201 (if (eq exit-after-next 'now) (throw 'exit t))
12202 (goto-char (point-min))
12203 (beginning-of-line 2)
12204 (delete-region (point) (point-at-eol))
12205 (org-fast-tag-insert "Current" current c-face)
12206 (org-set-current-tags-overlay current ov-prefix)
12207 (while (re-search-forward
12208 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12209 (setq tg (match-string 1))
12210 (add-text-properties
12211 (match-beginning 1) (match-end 1)
12212 (list 'face
12213 (cond
12214 ((member tg current) c-face)
12215 ((member tg inherited) i-face)
12216 (t (get-text-property (match-beginning 1) 'face))))))
12217 (goto-char (point-min)))))
12218 (org-detach-overlay org-tags-overlay)
12219 (if rtn
12220 (mapconcat 'identity current ":")
12221 nil))))
12223 (defun org-get-tags-string ()
12224 "Get the TAGS string in the current headline."
12225 (unless (org-on-heading-p t)
12226 (error "Not on a heading"))
12227 (save-excursion
12228 (beginning-of-line 1)
12229 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12230 (org-match-string-no-properties 1)
12231 "")))
12233 (defun org-get-tags ()
12234 "Get the list of tags specified in the current headline."
12235 (org-split-string (org-get-tags-string) ":"))
12237 (defun org-get-buffer-tags ()
12238 "Get a table of all tags used in the buffer, for completion."
12239 (let (tags)
12240 (save-excursion
12241 (goto-char (point-min))
12242 (while (re-search-forward
12243 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12244 (when (equal (char-after (point-at-bol 0)) ?*)
12245 (mapc (lambda (x) (add-to-list 'tags x))
12246 (org-split-string (org-match-string-no-properties 1) ":")))))
12247 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12248 (mapcar 'list tags)))
12250 ;;;; The mapping API
12252 ;;;###autoload
12253 (defun org-map-entries (func &optional match scope &rest skip)
12254 "Call FUNC at each headline selected by MATCH in SCOPE.
12256 FUNC is a function or a lisp form. The function will be called without
12257 arguments, with the cursor positioned at the beginning of the headline.
12258 The return values of all calls to the function will be collected and
12259 returned as a list.
12261 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12262 does not need to preserve point. After evaluation, the cursor will be
12263 moved to the end of the line (presumably of the headline of the
12264 processed entry) and search continues from there. Under some
12265 circumstances, this may not produce the wanted results. For example,
12266 if you have removed (e.g. archived) the current (sub)tree it could
12267 mean that the next entry will be skipped entirely. In such cases, you
12268 can specify the position from where search should continue by making
12269 FUNC set the variable `org-map-continue-from' to the desired buffer
12270 position.
12272 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12273 Only headlines that are matched by this query will be considered during
12274 the iteration. When MATCH is nil or t, all headlines will be
12275 visited by the iteration.
12277 SCOPE determines the scope of this command. It can be any of:
12279 nil The current buffer, respecting the restriction if any
12280 tree The subtree started with the entry at point
12281 file The current buffer, without restriction
12282 file-with-archives
12283 The current buffer, and any archives associated with it
12284 agenda All agenda files
12285 agenda-with-archives
12286 All agenda files with any archive files associated with them
12287 \(file1 file2 ...)
12288 If this is a list, all files in the list will be scanned
12290 The remaining args are treated as settings for the skipping facilities of
12291 the scanner. The following items can be given here:
12293 archive skip trees with the archive tag.
12294 comment skip trees with the COMMENT keyword
12295 function or Emacs Lisp form:
12296 will be used as value for `org-agenda-skip-function', so whenever
12297 the function returns t, FUNC will not be called for that
12298 entry and search will continue from the point where the
12299 function leaves it.
12301 If your function needs to retrieve the tags including inherited tags
12302 at the *current* entry, you can use the value of the variable
12303 `org-scanner-tags' which will be much faster than getting the value
12304 with `org-get-tags-at'. If your function gets properties with
12305 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12306 to t around the call to `org-entry-properties' to get the same speedup.
12307 Note that if your function moves around to retrieve tags and properties at
12308 a *different* entry, you cannot use these techniques."
12309 (let* ((org-agenda-archives-mode nil) ; just to make sure
12310 (org-agenda-skip-archived-trees (memq 'archive skip))
12311 (org-agenda-skip-comment-trees (memq 'comment skip))
12312 (org-agenda-skip-function
12313 (car (org-delete-all '(comment archive) skip)))
12314 (org-tags-match-list-sublevels t)
12315 matcher file res
12316 org-todo-keywords-for-agenda
12317 org-done-keywords-for-agenda
12318 org-todo-keyword-alist-for-agenda
12319 org-drawers-for-agenda
12320 org-tag-alist-for-agenda)
12322 (cond
12323 ((eq match t) (setq matcher t))
12324 ((eq match nil) (setq matcher t))
12325 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12327 (save-excursion
12328 (save-restriction
12329 (when (eq scope 'tree)
12330 (org-back-to-heading t)
12331 (org-narrow-to-subtree)
12332 (setq scope nil))
12334 (if (not scope)
12335 (progn
12336 (org-prepare-agenda-buffers
12337 (list (buffer-file-name (current-buffer))))
12338 (setq res (org-scan-tags func matcher)))
12339 ;; Get the right scope
12340 (cond
12341 ((and scope (listp scope) (symbolp (car scope)))
12342 (setq scope (eval scope)))
12343 ((eq scope 'agenda)
12344 (setq scope (org-agenda-files t)))
12345 ((eq scope 'agenda-with-archives)
12346 (setq scope (org-agenda-files t))
12347 (setq scope (org-add-archive-files scope)))
12348 ((eq scope 'file)
12349 (setq scope (list (buffer-file-name))))
12350 ((eq scope 'file-with-archives)
12351 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12352 (org-prepare-agenda-buffers scope)
12353 (while (setq file (pop scope))
12354 (with-current-buffer (org-find-base-buffer-visiting file)
12355 (save-excursion
12356 (save-restriction
12357 (widen)
12358 (goto-char (point-min))
12359 (setq res (append res (org-scan-tags func matcher))))))))))
12360 res))
12362 ;;;; Properties
12364 ;;; Setting and retrieving properties
12366 (defconst org-special-properties
12367 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12368 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12369 "The special properties valid in Org-mode.
12371 These are properties that are not defined in the property drawer,
12372 but in some other way.")
12374 (defconst org-default-properties
12375 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12376 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12377 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12378 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12379 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12380 "CLOCK_MODELINE_TOTAL" "STYLE")
12381 "Some properties that are used by Org-mode for various purposes.
12382 Being in this list makes sure that they are offered for completion.")
12384 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12385 "Regular expression matching the first line of a property drawer.")
12387 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12388 "Regular expression matching the first line of a property drawer.")
12390 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12391 "Regular expression matching the first line of a property drawer.")
12393 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12394 "Regular expression matching the first line of a property drawer.")
12396 (defconst org-property-drawer-re
12397 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12398 org-property-end-re "\\)\n?")
12399 "Matches an entire property drawer.")
12401 (defconst org-clock-drawer-re
12402 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12403 org-property-end-re "\\)\n?")
12404 "Matches an entire clock drawer.")
12406 (defun org-property-action ()
12407 "Do an action on properties."
12408 (interactive)
12409 (let (c)
12410 (org-at-property-p)
12411 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12412 (setq c (read-char-exclusive))
12413 (cond
12414 ((equal c ?s)
12415 (call-interactively 'org-set-property))
12416 ((equal c ?d)
12417 (call-interactively 'org-delete-property))
12418 ((equal c ?D)
12419 (call-interactively 'org-delete-property-globally))
12420 ((equal c ?c)
12421 (call-interactively 'org-compute-property-at-point))
12422 (t (error "No such property action %c" c)))))
12424 (defun org-set-effort (&optional value)
12425 "Set the effort property of the current entry.
12426 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12427 allowed value."
12428 (interactive "P")
12429 (if (equal value 0) (setq value 10))
12430 (let* ((completion-ignore-case t)
12431 (prop org-effort-property)
12432 (cur (org-entry-get nil prop))
12433 (allowed (org-property-get-allowed-values nil prop 'table))
12434 (existing (mapcar 'list (org-property-values prop)))
12436 (val (cond
12437 ((stringp value) value)
12438 ((and allowed (integerp value))
12439 (or (car (nth (1- value) allowed))
12440 (car (org-last allowed))))
12441 (allowed
12442 (message "Select 1-9,0, [RET%s]: %s"
12443 (if cur (concat "=" cur) "")
12444 (mapconcat 'car allowed " "))
12445 (setq rpl (read-char-exclusive))
12446 (if (equal rpl ?\r)
12448 (setq rpl (- rpl ?0))
12449 (if (equal rpl 0) (setq rpl 10))
12450 (if (and (> rpl 0) (<= rpl (length allowed)))
12451 (car (nth (1- rpl) allowed))
12452 (org-completing-read "Effort: " allowed nil))))
12454 (let (org-completion-use-ido org-completion-use-iswitchb)
12455 (org-completing-read
12456 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12457 (concat "[" cur "]") "")
12458 ": ")
12459 existing nil nil "" nil cur))))))
12460 (unless (equal (org-entry-get nil prop) val)
12461 (org-entry-put nil prop val))
12462 (message "%s is now %s" prop val)))
12464 (defun org-at-property-p ()
12465 "Is the cursor in a property line?"
12466 ;; FIXME: Does not check if we are actually in the drawer.
12467 ;; FIXME: also returns true on any drawers.....
12468 ;; This is used by C-c C-c for property action.
12469 (save-excursion
12470 (beginning-of-line 1)
12471 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12473 (defun org-get-property-block (&optional beg end force)
12474 "Return the (beg . end) range of the body of the property drawer.
12475 BEG and END can be beginning and end of subtree, if not given
12476 they will be found.
12477 If the drawer does not exist and FORCE is non-nil, create the drawer."
12478 (catch 'exit
12479 (save-excursion
12480 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12481 (end (or end (progn (outline-next-heading) (point)))))
12482 (goto-char beg)
12483 (if (re-search-forward org-property-start-re end t)
12484 (setq beg (1+ (match-end 0)))
12485 (if force
12486 (save-excursion
12487 (org-insert-property-drawer)
12488 (setq end (progn (outline-next-heading) (point))))
12489 (throw 'exit nil))
12490 (goto-char beg)
12491 (if (re-search-forward org-property-start-re end t)
12492 (setq beg (1+ (match-end 0)))))
12493 (if (re-search-forward org-property-end-re end t)
12494 (setq end (match-beginning 0))
12495 (or force (throw 'exit nil))
12496 (goto-char beg)
12497 (setq end beg)
12498 (org-indent-line-function)
12499 (insert ":END:\n"))
12500 (cons beg end)))))
12502 (defun org-entry-properties (&optional pom which specific)
12503 "Get all properties of the entry at point-or-marker POM.
12504 This includes the TODO keyword, the tags, time strings for deadline,
12505 scheduled, and clocking, and any additional properties defined in the
12506 entry. The return value is an alist, keys may occur multiple times
12507 if the property key was used several times.
12508 POM may also be nil, in which case the current entry is used.
12509 If WHICH is nil or `all', get all properties. If WHICH is
12510 `special' or `standard', only get that subclass. If WHICH
12511 is a string only get exactly this property. Specific can be a sting, the
12512 specific property we are interested in. Specifying it can speed
12513 things up because then unnecessary parsing is avoided."
12514 (setq which (or which 'all))
12515 (org-with-point-at pom
12516 (let ((clockstr (substring org-clock-string 0 -1))
12517 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12518 beg end range props sum-props key value string clocksum)
12519 (save-excursion
12520 (when (condition-case nil
12521 (and (org-mode-p) (org-back-to-heading t))
12522 (error nil))
12523 (setq beg (point))
12524 (setq sum-props (get-text-property (point) 'org-summaries))
12525 (setq clocksum (get-text-property (point) :org-clock-minutes))
12526 (outline-next-heading)
12527 (setq end (point))
12528 (when (memq which '(all special))
12529 ;; Get the special properties, like TODO and tags
12530 (goto-char beg)
12531 (when (and (or (not specific) (string= specific "TODO"))
12532 (looking-at org-todo-line-regexp) (match-end 2))
12533 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12534 (when (and (or (not specific) (string= specific "PRIORITY"))
12535 (looking-at org-priority-regexp))
12536 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12537 (when (and (or (not specific) (string= specific "TAGS"))
12538 (setq value (org-get-tags-string))
12539 (string-match "\\S-" value))
12540 (push (cons "TAGS" value) props))
12541 (when (and (or (not specific) (string= specific "TAGS"))
12542 (setq value (org-get-tags-at)))
12543 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12544 ":"))
12545 props))
12546 (when (or (not specific) (string= specific "TAGS"))
12547 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12548 (when (or (not specific)
12549 (member specific org-all-time-keywords)
12550 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12551 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12552 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12553 string (if (equal key clockstr)
12554 (org-no-properties
12555 (org-trim
12556 (buffer-substring
12557 (match-beginning 3) (goto-char (point-at-eol)))))
12558 (substring (org-match-string-no-properties 3) 1 -1)))
12559 (unless key
12560 (if (= (char-after (match-beginning 3)) ?\[)
12561 (setq key "TIMESTAMP_IA")
12562 (setq key "TIMESTAMP")))
12563 (when (or (equal key clockstr) (not (assoc key props)))
12564 (push (cons key string) props))))
12568 (when (memq which '(all standard))
12569 ;; Get the standard properties, like :PROP: ...
12570 (setq range (org-get-property-block beg end))
12571 (when range
12572 (goto-char (car range))
12573 (while (re-search-forward
12574 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12575 (cdr range) t)
12576 (setq key (org-match-string-no-properties 1)
12577 value (org-trim (or (org-match-string-no-properties 2) "")))
12578 (unless (member key excluded)
12579 (push (cons key (or value "")) props)))))
12580 (if clocksum
12581 (push (cons "CLOCKSUM"
12582 (org-columns-number-to-string (/ (float clocksum) 60.)
12583 'add_times))
12584 props))
12585 (unless (assoc "CATEGORY" props)
12586 (setq value (or (org-get-category)
12587 (progn (org-refresh-category-properties)
12588 (org-get-category))))
12589 (push (cons "CATEGORY" value) props))
12590 (append sum-props (nreverse props)))))))
12592 (defun org-entry-get (pom property &optional inherit)
12593 "Get value of PROPERTY for entry at point-or-marker POM.
12594 If INHERIT is non-nil and the entry does not have the property,
12595 then also check higher levels of the hierarchy.
12596 If INHERIT is the symbol `selective', use inheritance only if the setting
12597 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12598 If the property is present but empty, the return value is the empty string.
12599 If the property is not present at all, nil is returned."
12600 (org-with-point-at pom
12601 (if (and inherit (if (eq inherit 'selective)
12602 (org-property-inherit-p property)
12604 (org-entry-get-with-inheritance property)
12605 (if (member property org-special-properties)
12606 ;; We need a special property. Use `org-entry-properties' to
12607 ;; retrieve it, but specify the wanted property
12608 (cdr (assoc property (org-entry-properties nil 'special property)))
12609 (let ((range (org-get-property-block)))
12610 (if (and range
12611 (goto-char (car range))
12612 (re-search-forward
12613 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12614 (cdr range) t))
12615 ;; Found the property, return it.
12616 (if (match-end 1)
12617 (org-match-string-no-properties 1)
12618 "")))))))
12620 (defun org-property-or-variable-value (var &optional inherit)
12621 "Check if there is a property fixing the value of VAR.
12622 If yes, return this value. If not, return the current value of the variable."
12623 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12624 (if (and prop (stringp prop) (string-match "\\S-" prop))
12625 (read prop)
12626 (symbol-value var))))
12628 (defun org-entry-delete (pom property)
12629 "Delete the property PROPERTY from entry at point-or-marker POM."
12630 (org-with-point-at pom
12631 (if (member property org-special-properties)
12632 nil ; cannot delete these properties.
12633 (let ((range (org-get-property-block)))
12634 (if (and range
12635 (goto-char (car range))
12636 (re-search-forward
12637 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12638 (cdr range) t))
12639 (progn
12640 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12642 nil)))))
12644 ;; Multi-values properties are properties that contain multiple values
12645 ;; These values are assumed to be single words, separated by whitespace.
12646 (defun org-entry-add-to-multivalued-property (pom property value)
12647 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12648 (let* ((old (org-entry-get pom property))
12649 (values (and old (org-split-string old "[ \t]"))))
12650 (setq value (org-entry-protect-space value))
12651 (unless (member value values)
12652 (setq values (cons value values))
12653 (org-entry-put pom property
12654 (mapconcat 'identity values " ")))))
12656 (defun org-entry-remove-from-multivalued-property (pom property value)
12657 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12658 (let* ((old (org-entry-get pom property))
12659 (values (and old (org-split-string old "[ \t]"))))
12660 (setq value (org-entry-protect-space value))
12661 (when (member value values)
12662 (setq values (delete value values))
12663 (org-entry-put pom property
12664 (mapconcat 'identity values " ")))))
12666 (defun org-entry-member-in-multivalued-property (pom property value)
12667 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12668 (let* ((old (org-entry-get pom property))
12669 (values (and old (org-split-string old "[ \t]"))))
12670 (setq value (org-entry-protect-space value))
12671 (member value values)))
12673 (defun org-entry-get-multivalued-property (pom property)
12674 "Return a list of values in a multivalued property."
12675 (let* ((value (org-entry-get pom property))
12676 (values (and value (org-split-string value "[ \t]"))))
12677 (mapcar 'org-entry-restore-space values)))
12679 (defun org-entry-put-multivalued-property (pom property &rest values)
12680 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12681 VALUES should be a list of strings. Spaces will be protected."
12682 (org-entry-put pom property
12683 (mapconcat 'org-entry-protect-space values " "))
12684 (let* ((value (org-entry-get pom property))
12685 (values (and value (org-split-string value "[ \t]"))))
12686 (mapcar 'org-entry-restore-space values)))
12688 (defun org-entry-protect-space (s)
12689 "Protect spaces and newline in string S."
12690 (while (string-match " " s)
12691 (setq s (replace-match "%20" t t s)))
12692 (while (string-match "\n" s)
12693 (setq s (replace-match "%0A" t t s)))
12696 (defun org-entry-restore-space (s)
12697 "Restore spaces and newline in string S."
12698 (while (string-match "%20" s)
12699 (setq s (replace-match " " t t s)))
12700 (while (string-match "%0A" s)
12701 (setq s (replace-match "\n" t t s)))
12704 (defvar org-entry-property-inherited-from (make-marker)
12705 "Marker pointing to the entry from where a property was inherited.
12706 Each call to `org-entry-get-with-inheritance' will set this marker to the
12707 location of the entry where the inheritance search matched. If there was
12708 no match, the marker will point nowhere.
12709 Note that also `org-entry-get' calls this function, if the INHERIT flag
12710 is set.")
12712 (defun org-entry-get-with-inheritance (property)
12713 "Get entry property, and search higher levels if not present."
12714 (move-marker org-entry-property-inherited-from nil)
12715 (let (tmp)
12716 (save-excursion
12717 (save-restriction
12718 (widen)
12719 (catch 'ex
12720 (while t
12721 (when (setq tmp (org-entry-get nil property))
12722 (org-back-to-heading t)
12723 (move-marker org-entry-property-inherited-from (point))
12724 (throw 'ex tmp))
12725 (or (org-up-heading-safe) (throw 'ex nil)))))
12726 (or tmp
12727 (cdr (assoc property org-file-properties))
12728 (cdr (assoc property org-global-properties))
12729 (cdr (assoc property org-global-properties-fixed))))))
12731 (defvar org-property-changed-functions nil
12732 "Hook called when the value of a property has changed.
12733 Each hook function should accept two arguments, the name of the property
12734 and the new value.")
12736 (defun org-entry-put (pom property value)
12737 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12738 (org-with-point-at pom
12739 (org-back-to-heading t)
12740 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12741 range)
12742 (cond
12743 ((equal property "TODO")
12744 (when (and (stringp value) (string-match "\\S-" value)
12745 (not (member value org-todo-keywords-1)))
12746 (error "\"%s\" is not a valid TODO state" value))
12747 (if (or (not value)
12748 (not (string-match "\\S-" value)))
12749 (setq value 'none))
12750 (org-todo value)
12751 (org-set-tags nil 'align))
12752 ((equal property "PRIORITY")
12753 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12754 (string-to-char value) ?\ ))
12755 (org-set-tags nil 'align))
12756 ((equal property "SCHEDULED")
12757 (if (re-search-forward org-scheduled-time-regexp end t)
12758 (cond
12759 ((eq value 'earlier) (org-timestamp-change -1 'day))
12760 ((eq value 'later) (org-timestamp-change 1 'day))
12761 (t (call-interactively 'org-schedule)))
12762 (call-interactively 'org-schedule)))
12763 ((equal property "DEADLINE")
12764 (if (re-search-forward org-deadline-time-regexp end t)
12765 (cond
12766 ((eq value 'earlier) (org-timestamp-change -1 'day))
12767 ((eq value 'later) (org-timestamp-change 1 'day))
12768 (t (call-interactively 'org-deadline)))
12769 (call-interactively 'org-deadline)))
12770 ((member property org-special-properties)
12771 (error "The %s property can not yet be set with `org-entry-put'"
12772 property))
12773 (t ; a non-special property
12774 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12775 (setq range (org-get-property-block beg end 'force))
12776 (goto-char (car range))
12777 (if (re-search-forward
12778 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12779 (progn
12780 (delete-region (match-beginning 1) (match-end 1))
12781 (goto-char (match-beginning 1)))
12782 (goto-char (cdr range))
12783 (insert "\n")
12784 (backward-char 1)
12785 (org-indent-line-function)
12786 (insert ":" property ":"))
12787 (and value (insert " " value))
12788 (org-indent-line-function)))))
12789 (run-hook-with-args 'org-property-changed-functions property value)))
12791 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12792 "Get all property keys in the current buffer.
12793 With INCLUDE-SPECIALS, also list the special properties that reflect things
12794 like tags and TODO state.
12795 With INCLUDE-DEFAULTS, also include properties that has special meaning
12796 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12797 With INCLUDE-COLUMNS, also include property names given in COLUMN
12798 formats in the current buffer."
12799 (let (rtn range cfmt s p)
12800 (save-excursion
12801 (save-restriction
12802 (widen)
12803 (goto-char (point-min))
12804 (while (re-search-forward org-property-start-re nil t)
12805 (setq range (org-get-property-block))
12806 (goto-char (car range))
12807 (while (re-search-forward
12808 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12809 (cdr range) t)
12810 (add-to-list 'rtn (org-match-string-no-properties 1)))
12811 (outline-next-heading))))
12813 (when include-specials
12814 (setq rtn (append org-special-properties rtn)))
12816 (when include-defaults
12817 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12818 (add-to-list 'rtn org-effort-property))
12820 (when include-columns
12821 (save-excursion
12822 (save-restriction
12823 (widen)
12824 (goto-char (point-min))
12825 (while (re-search-forward
12826 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12827 nil t)
12828 (setq cfmt (match-string 2) s 0)
12829 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12830 cfmt s)
12831 (setq s (match-end 0)
12832 p (match-string 1 cfmt))
12833 (unless (or (equal p "ITEM")
12834 (member p org-special-properties))
12835 (add-to-list 'rtn (match-string 1 cfmt))))))))
12837 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12839 (defun org-property-values (key)
12840 "Return a list of all values of property KEY."
12841 (save-excursion
12842 (save-restriction
12843 (widen)
12844 (goto-char (point-min))
12845 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12846 values)
12847 (while (re-search-forward re nil t)
12848 (add-to-list 'values (org-trim (match-string 1))))
12849 (delete "" values)))))
12851 (defun org-insert-property-drawer ()
12852 "Insert a property drawer into the current entry."
12853 (interactive)
12854 (org-back-to-heading t)
12855 (looking-at outline-regexp)
12856 (let ((indent (if org-adapt-indentation
12857 (- (match-end 0)(match-beginning 0))
12859 (beg (point))
12860 (re (concat "^[ \t]*" org-keyword-time-regexp))
12861 end hiddenp)
12862 (outline-next-heading)
12863 (setq end (point))
12864 (goto-char beg)
12865 (while (re-search-forward re end t))
12866 (setq hiddenp (org-invisible-p))
12867 (end-of-line 1)
12868 (and (equal (char-after) ?\n) (forward-char 1))
12869 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12870 (if (member (match-string 1) '("CLOCK:" ":END:"))
12871 ;; just skip this line
12872 (beginning-of-line 2)
12873 ;; Drawer start, find the end
12874 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12875 (beginning-of-line 1)))
12876 (org-skip-over-state-notes)
12877 (skip-chars-backward " \t\n\r")
12878 (if (eq (char-before) ?*) (forward-char 1))
12879 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12880 (beginning-of-line 0)
12881 (org-indent-to-column indent)
12882 (beginning-of-line 2)
12883 (org-indent-to-column indent)
12884 (beginning-of-line 0)
12885 (if hiddenp
12886 (save-excursion
12887 (org-back-to-heading t)
12888 (hide-entry))
12889 (org-flag-drawer t))))
12891 (defun org-set-property (property value)
12892 "In the current entry, set PROPERTY to VALUE.
12893 When called interactively, this will prompt for a property name, offering
12894 completion on existing and default properties. And then it will prompt
12895 for a value, offering completion either on allowed values (via an inherited
12896 xxx_ALL property) or on existing values in other instances of this property
12897 in the current file."
12898 (interactive
12899 (let* ((completion-ignore-case t)
12900 (keys (org-buffer-property-keys nil t t))
12901 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12902 (prop (if (member prop0 keys)
12903 prop0
12904 (or (cdr (assoc (downcase prop0)
12905 (mapcar (lambda (x) (cons (downcase x) x))
12906 keys)))
12907 prop0)))
12908 (cur (org-entry-get nil prop))
12909 (allowed (org-property-get-allowed-values nil prop 'table))
12910 (existing (mapcar 'list (org-property-values prop)))
12911 (val (if allowed
12912 (org-completing-read "Value: " allowed nil
12913 (not (get-text-property 0 'org-unrestricted
12914 (caar allowed))))
12915 (let (org-completion-use-ido org-completion-use-iswitchb)
12916 (org-completing-read
12917 (concat "Value " (if (and cur (string-match "\\S-" cur))
12918 (concat "[" cur "]") "")
12919 ": ")
12920 existing nil nil "" nil cur)))))
12921 (list prop (if (equal val "") cur val))))
12922 (unless (equal (org-entry-get nil property) value)
12923 (org-entry-put nil property value)))
12925 (defun org-delete-property (property)
12926 "In the current entry, delete PROPERTY."
12927 (interactive
12928 (let* ((completion-ignore-case t)
12929 (prop (org-icompleting-read
12930 "Property: " (org-entry-properties nil 'standard))))
12931 (list prop)))
12932 (message "Property %s %s" property
12933 (if (org-entry-delete nil property)
12934 "deleted"
12935 "was not present in the entry")))
12937 (defun org-delete-property-globally (property)
12938 "Remove PROPERTY globally, from all entries."
12939 (interactive
12940 (let* ((completion-ignore-case t)
12941 (prop (org-icompleting-read
12942 "Globally remove property: "
12943 (mapcar 'list (org-buffer-property-keys)))))
12944 (list prop)))
12945 (save-excursion
12946 (save-restriction
12947 (widen)
12948 (goto-char (point-min))
12949 (let ((cnt 0))
12950 (while (re-search-forward
12951 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12952 nil t)
12953 (setq cnt (1+ cnt))
12954 (replace-match ""))
12955 (message "Property \"%s\" removed from %d entries" property cnt)))))
12957 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12959 (defun org-compute-property-at-point ()
12960 "Compute the property at point.
12961 This looks for an enclosing column format, extracts the operator and
12962 then applies it to the property in the column format's scope."
12963 (interactive)
12964 (unless (org-at-property-p)
12965 (error "Not at a property"))
12966 (let ((prop (org-match-string-no-properties 2)))
12967 (org-columns-get-format-and-top-level)
12968 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12969 (error "No operator defined for property %s" prop))
12970 (org-columns-compute prop)))
12972 (defvar org-property-allowed-value-functions nil
12973 "Hook for functions supplying allowed values for specific.
12974 The functions must take a single argument, the name of the property, and
12975 return a flat list of allowed values. If \":ETC\" is one of
12976 the values, this means that these values are intended as defaults for
12977 completion, but that other values should be allowed too.
12978 The functions must return nil if they are now responsible for this
12979 prioerty.")
12981 (defun org-property-get-allowed-values (pom property &optional table)
12982 "Get allowed values for the property PROPERTY.
12983 When TABLE is non-nil, return an alist that can directly be used for
12984 completion."
12985 (let (vals)
12986 (cond
12987 ((equal property "TODO")
12988 (setq vals (org-with-point-at pom
12989 (append org-todo-keywords-1 '("")))))
12990 ((equal property "PRIORITY")
12991 (let ((n org-lowest-priority))
12992 (while (>= n org-highest-priority)
12993 (push (char-to-string n) vals)
12994 (setq n (1- n)))))
12995 ((member property org-special-properties))
12996 ((setq vals (run-hook-with-args-until-success
12997 'org-property-allowed-value-functions property)))
12999 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13000 (when (and vals (string-match "\\S-" vals))
13001 (setq vals (car (read-from-string (concat "(" vals ")"))))
13002 (setq vals (mapcar (lambda (x)
13003 (cond ((stringp x) x)
13004 ((numberp x) (number-to-string x))
13005 ((symbolp x) (symbol-name x))
13006 (t "???")))
13007 vals)))))
13008 (when (member ":ETC" vals)
13009 (setq vals (remove ":ETC" vals))
13010 (org-add-props (car vals) '(org-unrestricted t)))
13011 (if table (mapcar 'list vals) vals)))
13013 (defun org-property-previous-allowed-value (&optional previous)
13014 "Switch to the next allowed value for this property."
13015 (interactive)
13016 (org-property-next-allowed-value t))
13018 (defun org-property-next-allowed-value (&optional previous)
13019 "Switch to the next allowed value for this property."
13020 (interactive)
13021 (unless (org-at-property-p)
13022 (error "Not at a property"))
13023 (let* ((key (match-string 2))
13024 (value (match-string 3))
13025 (allowed (or (org-property-get-allowed-values (point) key)
13026 (and (member value '("[ ]" "[-]" "[X]"))
13027 '("[ ]" "[X]"))))
13028 nval)
13029 (unless allowed
13030 (error "Allowed values for this property have not been defined"))
13031 (if previous (setq allowed (reverse allowed)))
13032 (if (member value allowed)
13033 (setq nval (car (cdr (member value allowed)))))
13034 (setq nval (or nval (car allowed)))
13035 (if (equal nval value)
13036 (error "Only one allowed value for this property"))
13037 (org-at-property-p)
13038 (replace-match (concat " :" key ": " nval) t t)
13039 (org-indent-line-function)
13040 (beginning-of-line 1)
13041 (skip-chars-forward " \t")
13042 (run-hook-with-args 'org-property-changed-functions key nval)))
13044 (defun org-find-entry-with-id (ident)
13045 "Locate the entry that contains the ID property with exact value IDENT.
13046 IDENT can be a string, a symbol or a number, this function will search for
13047 the string representation of it.
13048 Return the position where this entry starts, or nil if there is no such entry."
13049 (interactive "sID: ")
13050 (let ((id (cond
13051 ((stringp ident) ident)
13052 ((symbol-name ident) (symbol-name ident))
13053 ((numberp ident) (number-to-string ident))
13054 (t (error "IDENT %s must be a string, symbol or number" ident))))
13055 (case-fold-search nil))
13056 (save-excursion
13057 (save-restriction
13058 (widen)
13059 (goto-char (point-min))
13060 (when (re-search-forward
13061 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13062 nil t)
13063 (org-back-to-heading t)
13064 (point))))))
13066 ;;;; Timestamps
13068 (defvar org-last-changed-timestamp nil)
13069 (defvar org-last-inserted-timestamp nil
13070 "The last time stamp inserted with `org-insert-time-stamp'.")
13071 (defvar org-time-was-given) ; dynamically scoped parameter
13072 (defvar org-end-time-was-given) ; dynamically scoped parameter
13073 (defvar org-ts-what) ; dynamically scoped parameter
13075 (defun org-time-stamp (arg &optional inactive)
13076 "Prompt for a date/time and insert a time stamp.
13077 If the user specifies a time like HH:MM, or if this command is called
13078 with a prefix argument, the time stamp will contain date and time.
13079 Otherwise, only the date will be included. All parts of a date not
13080 specified by the user will be filled in from the current date/time.
13081 So if you press just return without typing anything, the time stamp
13082 will represent the current date/time. If there is already a timestamp
13083 at the cursor, it will be modified."
13084 (interactive "P")
13085 (let* ((ts nil)
13086 (default-time
13087 ;; Default time is either today, or, when entering a range,
13088 ;; the range start.
13089 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13090 (save-excursion
13091 (re-search-backward
13092 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13093 (- (point) 20) t)))
13094 (apply 'encode-time (org-parse-time-string (match-string 1)))
13095 (current-time)))
13096 (default-input (and ts (org-get-compact-tod ts)))
13097 org-time-was-given org-end-time-was-given time)
13098 (cond
13099 ((and (org-at-timestamp-p t)
13100 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13101 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13102 (insert "--")
13103 (setq time (let ((this-command this-command))
13104 (org-read-date arg 'totime nil nil
13105 default-time default-input)))
13106 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13107 ((org-at-timestamp-p t)
13108 (setq time (let ((this-command this-command))
13109 (org-read-date arg 'totime nil nil default-time default-input)))
13110 (when (org-at-timestamp-p t) ; just to get the match data
13111 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13112 (replace-match "")
13113 (setq org-last-changed-timestamp
13114 (org-insert-time-stamp
13115 time (or org-time-was-given arg)
13116 inactive nil nil (list org-end-time-was-given))))
13117 (message "Timestamp updated"))
13119 (setq time (let ((this-command this-command))
13120 (org-read-date arg 'totime nil nil default-time default-input)))
13121 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13122 nil nil (list org-end-time-was-given))))))
13124 ;; FIXME: can we use this for something else, like computing time differences?
13125 (defun org-get-compact-tod (s)
13126 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13127 (let* ((t1 (match-string 1 s))
13128 (h1 (string-to-number (match-string 2 s)))
13129 (m1 (string-to-number (match-string 3 s)))
13130 (t2 (and (match-end 4) (match-string 5 s)))
13131 (h2 (and t2 (string-to-number (match-string 6 s))))
13132 (m2 (and t2 (string-to-number (match-string 7 s))))
13133 dh dm)
13134 (if (not t2)
13136 (setq dh (- h2 h1) dm (- m2 m1))
13137 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13138 (concat t1 "+" (number-to-string dh)
13139 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13141 (defun org-time-stamp-inactive (&optional arg)
13142 "Insert an inactive time stamp.
13143 An inactive time stamp is enclosed in square brackets instead of angle
13144 brackets. It is inactive in the sense that it does not trigger agenda entries,
13145 does not link to the calendar and cannot be changed with the S-cursor keys.
13146 So these are more for recording a certain time/date."
13147 (interactive "P")
13148 (org-time-stamp arg 'inactive))
13150 (defvar org-date-ovl (org-make-overlay 1 1))
13151 (org-overlay-put org-date-ovl 'face 'org-warning)
13152 (org-detach-overlay org-date-ovl)
13154 (defvar org-ans1) ; dynamically scoped parameter
13155 (defvar org-ans2) ; dynamically scoped parameter
13157 (defvar org-plain-time-of-day-regexp) ; defined below
13159 (defvar org-overriding-default-time nil) ; dynamically scoped
13160 (defvar org-read-date-overlay nil)
13161 (defvar org-dcst nil) ; dynamically scoped
13162 (defvar org-read-date-history nil)
13163 (defvar org-read-date-final-answer nil)
13165 (defun org-read-date (&optional with-time to-time from-string prompt
13166 default-time default-input)
13167 "Read a date, possibly a time, and make things smooth for the user.
13168 The prompt will suggest to enter an ISO date, but you can also enter anything
13169 which will at least partially be understood by `parse-time-string'.
13170 Unrecognized parts of the date will default to the current day, month, year,
13171 hour and minute. If this command is called to replace a timestamp at point,
13172 of to enter the second timestamp of a range, the default time is taken from the
13173 existing stamp. For example,
13174 3-2-5 --> 2003-02-05
13175 feb 15 --> currentyear-02-15
13176 sep 12 9 --> 2009-09-12
13177 12:45 --> today 12:45
13178 22 sept 0:34 --> currentyear-09-22 0:34
13179 12 --> currentyear-currentmonth-12
13180 Fri --> nearest Friday (today or later)
13181 etc.
13183 Furthermore you can specify a relative date by giving, as the *first* thing
13184 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13185 change in days weeks, months, years.
13186 With a single plus or minus, the date is relative to today. With a double
13187 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13188 +4d --> four days from today
13189 +4 --> same as above
13190 +2w --> two weeks from today
13191 ++5 --> five days from default date
13193 The function understands only English month and weekday abbreviations,
13194 but this can be configured with the variables `parse-time-months' and
13195 `parse-time-weekdays'.
13197 While prompting, a calendar is popped up - you can also select the
13198 date with the mouse (button 1). The calendar shows a period of three
13199 months. To scroll it to other months, use the keys `>' and `<'.
13200 If you don't like the calendar, turn it off with
13201 \(setq org-read-date-popup-calendar nil)
13203 With optional argument TO-TIME, the date will immediately be converted
13204 to an internal time.
13205 With an optional argument WITH-TIME, the prompt will suggest to also
13206 insert a time. Note that when WITH-TIME is not set, you can still
13207 enter a time, and this function will inform the calling routine about
13208 this change. The calling routine may then choose to change the format
13209 used to insert the time stamp into the buffer to include the time.
13210 With optional argument FROM-STRING, read from this string instead from
13211 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13212 the time/date that is used for everything that is not specified by the
13213 user."
13214 (require 'parse-time)
13215 (let* ((org-time-stamp-rounding-minutes
13216 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13217 (org-dcst org-display-custom-times)
13218 (ct (org-current-time))
13219 (def (or org-overriding-default-time default-time ct))
13220 (defdecode (decode-time def))
13221 (dummy (progn
13222 (when (< (nth 2 defdecode) org-extend-today-until)
13223 (setcar (nthcdr 2 defdecode) -1)
13224 (setcar (nthcdr 1 defdecode) 59)
13225 (setq def (apply 'encode-time defdecode)
13226 defdecode (decode-time def)))))
13227 (calendar-frame-setup nil)
13228 (calendar-move-hook nil)
13229 (calendar-view-diary-initially-flag nil)
13230 (view-diary-entries-initially nil)
13231 (calendar-view-holidays-initially-flag nil)
13232 (view-calendar-holidays-initially nil)
13233 (timestr (format-time-string
13234 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13235 (prompt (concat (if prompt (concat prompt " ") "")
13236 (format "Date+time [%s]: " timestr)))
13237 ans (org-ans0 "") org-ans1 org-ans2 final)
13239 (cond
13240 (from-string (setq ans from-string))
13241 (org-read-date-popup-calendar
13242 (save-excursion
13243 (save-window-excursion
13244 (calendar)
13245 (calendar-forward-day (- (time-to-days def)
13246 (calendar-absolute-from-gregorian
13247 (calendar-current-date))))
13248 (org-eval-in-calendar nil t)
13249 (let* ((old-map (current-local-map))
13250 (map (copy-keymap calendar-mode-map))
13251 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13252 (org-defkey map (kbd "RET") 'org-calendar-select)
13253 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13254 'org-calendar-select-mouse)
13255 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13256 'org-calendar-select-mouse)
13257 (org-defkey minibuffer-local-map [(meta shift left)]
13258 (lambda () (interactive)
13259 (org-eval-in-calendar '(calendar-backward-month 1))))
13260 (org-defkey minibuffer-local-map [(meta shift right)]
13261 (lambda () (interactive)
13262 (org-eval-in-calendar '(calendar-forward-month 1))))
13263 (org-defkey minibuffer-local-map [(meta shift up)]
13264 (lambda () (interactive)
13265 (org-eval-in-calendar '(calendar-backward-year 1))))
13266 (org-defkey minibuffer-local-map [(meta shift down)]
13267 (lambda () (interactive)
13268 (org-eval-in-calendar '(calendar-forward-year 1))))
13269 (org-defkey minibuffer-local-map [?\e (shift left)]
13270 (lambda () (interactive)
13271 (org-eval-in-calendar '(calendar-backward-month 1))))
13272 (org-defkey minibuffer-local-map [?\e (shift right)]
13273 (lambda () (interactive)
13274 (org-eval-in-calendar '(calendar-forward-month 1))))
13275 (org-defkey minibuffer-local-map [?\e (shift up)]
13276 (lambda () (interactive)
13277 (org-eval-in-calendar '(calendar-backward-year 1))))
13278 (org-defkey minibuffer-local-map [?\e (shift down)]
13279 (lambda () (interactive)
13280 (org-eval-in-calendar '(calendar-forward-year 1))))
13281 (org-defkey minibuffer-local-map [(shift up)]
13282 (lambda () (interactive)
13283 (org-eval-in-calendar '(calendar-backward-week 1))))
13284 (org-defkey minibuffer-local-map [(shift down)]
13285 (lambda () (interactive)
13286 (org-eval-in-calendar '(calendar-forward-week 1))))
13287 (org-defkey minibuffer-local-map [(shift left)]
13288 (lambda () (interactive)
13289 (org-eval-in-calendar '(calendar-backward-day 1))))
13290 (org-defkey minibuffer-local-map [(shift right)]
13291 (lambda () (interactive)
13292 (org-eval-in-calendar '(calendar-forward-day 1))))
13293 (org-defkey minibuffer-local-map ">"
13294 (lambda () (interactive)
13295 (org-eval-in-calendar '(scroll-calendar-left 1))))
13296 (org-defkey minibuffer-local-map "<"
13297 (lambda () (interactive)
13298 (org-eval-in-calendar '(scroll-calendar-right 1))))
13299 (run-hooks 'org-read-date-minibuffer-setup-hook)
13300 (unwind-protect
13301 (progn
13302 (use-local-map map)
13303 (add-hook 'post-command-hook 'org-read-date-display)
13304 (setq org-ans0 (read-string prompt default-input
13305 'org-read-date-history nil))
13306 ;; org-ans0: from prompt
13307 ;; org-ans1: from mouse click
13308 ;; org-ans2: from calendar motion
13309 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13310 (remove-hook 'post-command-hook 'org-read-date-display)
13311 (use-local-map old-map)
13312 (when org-read-date-overlay
13313 (org-delete-overlay org-read-date-overlay)
13314 (setq org-read-date-overlay nil)))))))
13316 (t ; Naked prompt only
13317 (unwind-protect
13318 (setq ans (read-string prompt default-input
13319 'org-read-date-history timestr))
13320 (when org-read-date-overlay
13321 (org-delete-overlay org-read-date-overlay)
13322 (setq org-read-date-overlay nil)))))
13324 (setq final (org-read-date-analyze ans def defdecode))
13325 (setq org-read-date-final-answer ans)
13327 (if to-time
13328 (apply 'encode-time final)
13329 (if (and (boundp 'org-time-was-given) org-time-was-given)
13330 (format "%04d-%02d-%02d %02d:%02d"
13331 (nth 5 final) (nth 4 final) (nth 3 final)
13332 (nth 2 final) (nth 1 final))
13333 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13335 (defvar def)
13336 (defvar defdecode)
13337 (defvar with-time)
13338 (defvar org-read-date-analyze-futurep nil)
13339 (defun org-read-date-display ()
13340 "Display the current date prompt interpretation in the minibuffer."
13341 (when org-read-date-display-live
13342 (when org-read-date-overlay
13343 (org-delete-overlay org-read-date-overlay))
13344 (let ((p (point)))
13345 (end-of-line 1)
13346 (while (not (equal (buffer-substring
13347 (max (point-min) (- (point) 4)) (point))
13348 " "))
13349 (insert " "))
13350 (goto-char p))
13351 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13352 " " (or org-ans1 org-ans2)))
13353 (org-end-time-was-given nil)
13354 (f (org-read-date-analyze ans def defdecode))
13355 (fmts (if org-dcst
13356 org-time-stamp-custom-formats
13357 org-time-stamp-formats))
13358 (fmt (if (or with-time
13359 (and (boundp 'org-time-was-given) org-time-was-given))
13360 (cdr fmts)
13361 (car fmts)))
13362 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13363 (when (and org-end-time-was-given
13364 (string-match org-plain-time-of-day-regexp txt))
13365 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13366 org-end-time-was-given
13367 (substring txt (match-end 0)))))
13368 (when org-read-date-analyze-futurep
13369 (setq txt (concat txt " (=>F)")))
13370 (setq org-read-date-overlay
13371 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13372 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13374 (defun org-read-date-analyze (ans def defdecode)
13375 "Analyse the combined answer of the date prompt."
13376 ;; FIXME: cleanup and comment
13377 (let ((nowdecode (decode-time (current-time)))
13378 delta deltan deltaw deltadef year month day
13379 hour minute second wday pm h2 m2 tl wday1
13380 iso-year iso-weekday iso-week iso-year iso-date futurep)
13381 (setq org-read-date-analyze-futurep nil)
13382 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13383 (setq ans "+0"))
13385 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13386 (setq ans (replace-match "" t t ans)
13387 deltan (car delta)
13388 deltaw (nth 1 delta)
13389 deltadef (nth 2 delta)))
13391 ;; Check if there is an iso week date in there
13392 ;; If yes, store the info and postpone interpreting it until the rest
13393 ;; of the parsing is done
13394 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13395 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13396 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13397 iso-week (string-to-number (match-string 2 ans)))
13398 (setq ans (replace-match "" t t ans)))
13400 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13401 (when (string-match
13402 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13403 (setq year (if (match-end 2)
13404 (string-to-number (match-string 2 ans))
13405 (string-to-number (format-time-string "%Y")))
13406 month (string-to-number (match-string 3 ans))
13407 day (string-to-number (match-string 4 ans)))
13408 (if (< year 100) (setq year (+ 2000 year)))
13409 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13410 t nil ans)))
13411 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13412 ;; If there is a time with am/pm, and *no* time without it, we convert
13413 ;; so that matching will be successful.
13414 (loop for i from 1 to 2 do ; twice, for end time as well
13415 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13416 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13417 (setq hour (string-to-number (match-string 1 ans))
13418 minute (if (match-end 3)
13419 (string-to-number (match-string 3 ans))
13421 pm (equal ?p
13422 (string-to-char (downcase (match-string 4 ans)))))
13423 (if (and (= hour 12) (not pm))
13424 (setq hour 0)
13425 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13426 (setq ans (replace-match (format "%02d:%02d" hour minute)
13427 t t ans))))
13429 ;; Check if a time range is given as a duration
13430 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13431 (setq hour (string-to-number (match-string 1 ans))
13432 h2 (+ hour (string-to-number (match-string 3 ans)))
13433 minute (string-to-number (match-string 2 ans))
13434 m2 (+ minute (if (match-end 5) (string-to-number
13435 (match-string 5 ans))0)))
13436 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13437 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13438 t t ans)))
13440 ;; Check if there is a time range
13441 (when (boundp 'org-end-time-was-given)
13442 (setq org-time-was-given nil)
13443 (when (and (string-match org-plain-time-of-day-regexp ans)
13444 (match-end 8))
13445 (setq org-end-time-was-given (match-string 8 ans))
13446 (setq ans (concat (substring ans 0 (match-beginning 7))
13447 (substring ans (match-end 7))))))
13449 (setq tl (parse-time-string ans)
13450 day (or (nth 3 tl) (nth 3 defdecode))
13451 month (or (nth 4 tl)
13452 (if (and org-read-date-prefer-future
13453 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13454 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13455 (nth 4 defdecode)))
13456 year (or (nth 5 tl)
13457 (if (and org-read-date-prefer-future
13458 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13459 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13460 (nth 5 defdecode)))
13461 hour (or (nth 2 tl) (nth 2 defdecode))
13462 minute (or (nth 1 tl) (nth 1 defdecode))
13463 second (or (nth 0 tl) 0)
13464 wday (nth 6 tl))
13466 (when (and (eq org-read-date-prefer-future 'time)
13467 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13468 (equal day (nth 3 nowdecode))
13469 (equal month (nth 4 nowdecode))
13470 (equal year (nth 5 nowdecode))
13471 (nth 2 tl)
13472 (or (< (nth 2 tl) (nth 2 nowdecode))
13473 (and (= (nth 2 tl) (nth 2 nowdecode))
13474 (nth 1 tl)
13475 (< (nth 1 tl) (nth 1 nowdecode)))))
13476 (setq day (1+ day)
13477 futurep t))
13479 ;; Special date definitions below
13480 (cond
13481 (iso-week
13482 ;; There was an iso week
13483 (setq futurep nil)
13484 (setq year (or iso-year year)
13485 day (or iso-weekday wday 1)
13486 wday nil ; to make sure that the trigger below does not match
13487 iso-date (calendar-gregorian-from-absolute
13488 (calendar-absolute-from-iso
13489 (list iso-week day year))))
13490 ; FIXME: Should we also push ISO weeks into the future?
13491 ; (when (and org-read-date-prefer-future
13492 ; (not iso-year)
13493 ; (< (calendar-absolute-from-gregorian iso-date)
13494 ; (time-to-days (current-time))))
13495 ; (setq year (1+ year)
13496 ; iso-date (calendar-gregorian-from-absolute
13497 ; (calendar-absolute-from-iso
13498 ; (list iso-week day year)))))
13499 (setq month (car iso-date)
13500 year (nth 2 iso-date)
13501 day (nth 1 iso-date)))
13502 (deltan
13503 (setq futurep nil)
13504 (unless deltadef
13505 (let ((now (decode-time (current-time))))
13506 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13507 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13508 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13509 ((equal deltaw "m") (setq month (+ month deltan)))
13510 ((equal deltaw "y") (setq year (+ year deltan)))))
13511 ((and wday (not (nth 3 tl)))
13512 (setq futurep nil)
13513 ;; Weekday was given, but no day, so pick that day in the week
13514 ;; on or after the derived date.
13515 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13516 (unless (equal wday wday1)
13517 (setq day (+ day (% (- wday wday1 -7) 7))))))
13518 (if (and (boundp 'org-time-was-given)
13519 (nth 2 tl))
13520 (setq org-time-was-given t))
13521 (if (< year 100) (setq year (+ 2000 year)))
13522 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13523 (setq org-read-date-analyze-futurep futurep)
13524 (list second minute hour day month year)))
13526 (defvar parse-time-weekdays)
13528 (defun org-read-date-get-relative (s today default)
13529 "Check string S for special relative date string.
13530 TODAY and DEFAULT are internal times, for today and for a default.
13531 Return shift list (N what def-flag)
13532 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13533 N is the number of WHATs to shift.
13534 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13535 the DEFAULT date rather than TODAY."
13536 (when (and
13537 (string-match
13538 (concat
13539 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13540 "\\([0-9]+\\)?"
13541 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13542 "\\([ \t]\\|$\\)") s)
13543 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13544 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13545 (string-to-char (substring (match-string 1 s) -1))
13546 ?+))
13547 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13548 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13549 (what (if (match-end 3) (match-string 3 s) "d"))
13550 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13551 (date (if rel default today))
13552 (wday (nth 6 (decode-time date)))
13553 delta)
13554 (if wday1
13555 (progn
13556 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13557 (if (= dir ?-) (setq delta (- delta 7)))
13558 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13559 (list delta "d" rel))
13560 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13562 (defun org-eval-in-calendar (form &optional keepdate)
13563 "Eval FORM in the calendar window and return to current window.
13564 Also, store the cursor date in variable org-ans2."
13565 (let ((sf (selected-frame))
13566 (sw (selected-window)))
13567 (select-window (get-buffer-window "*Calendar*" t))
13568 (eval form)
13569 (when (and (not keepdate) (calendar-cursor-to-date))
13570 (let* ((date (calendar-cursor-to-date))
13571 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13572 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13573 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13574 (select-window sw)
13575 (org-select-frame-set-input-focus sf)))
13577 (defun org-calendar-select ()
13578 "Return to `org-read-date' with the date currently selected.
13579 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13580 (interactive)
13581 (when (calendar-cursor-to-date)
13582 (let* ((date (calendar-cursor-to-date))
13583 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13584 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13585 (if (active-minibuffer-window) (exit-minibuffer))))
13587 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13588 "Insert a date stamp for the date given by the internal TIME.
13589 WITH-HM means, use the stamp format that includes the time of the day.
13590 INACTIVE means use square brackets instead of angular ones, so that the
13591 stamp will not contribute to the agenda.
13592 PRE and POST are optional strings to be inserted before and after the
13593 stamp.
13594 The command returns the inserted time stamp."
13595 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13596 stamp)
13597 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13598 (insert-before-markers (or pre ""))
13599 (insert-before-markers (setq stamp (format-time-string fmt time)))
13600 (when (listp extra)
13601 (setq extra (car extra))
13602 (if (and (stringp extra)
13603 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13604 (setq extra (format "-%02d:%02d"
13605 (string-to-number (match-string 1 extra))
13606 (string-to-number (match-string 2 extra))))
13607 (setq extra nil)))
13608 (when extra
13609 (backward-char 1)
13610 (insert-before-markers extra)
13611 (forward-char 1))
13612 (insert-before-markers (or post ""))
13613 (setq org-last-inserted-timestamp stamp)))
13615 (defun org-toggle-time-stamp-overlays ()
13616 "Toggle the use of custom time stamp formats."
13617 (interactive)
13618 (setq org-display-custom-times (not org-display-custom-times))
13619 (unless org-display-custom-times
13620 (let ((p (point-min)) (bmp (buffer-modified-p)))
13621 (while (setq p (next-single-property-change p 'display))
13622 (if (and (get-text-property p 'display)
13623 (eq (get-text-property p 'face) 'org-date))
13624 (remove-text-properties
13625 p (setq p (next-single-property-change p 'display))
13626 '(display t))))
13627 (set-buffer-modified-p bmp)))
13628 (if (featurep 'xemacs)
13629 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13630 (org-restart-font-lock)
13631 (setq org-table-may-need-update t)
13632 (if org-display-custom-times
13633 (message "Time stamps are overlayed with custom format")
13634 (message "Time stamp overlays removed")))
13636 (defun org-display-custom-time (beg end)
13637 "Overlay modified time stamp format over timestamp between BEG and END."
13638 (let* ((ts (buffer-substring beg end))
13639 t1 w1 with-hm tf time str w2 (off 0))
13640 (save-match-data
13641 (setq t1 (org-parse-time-string ts t))
13642 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13643 (setq off (- (match-end 0) (match-beginning 0)))))
13644 (setq end (- end off))
13645 (setq w1 (- end beg)
13646 with-hm (and (nth 1 t1) (nth 2 t1))
13647 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13648 time (org-fix-decoded-time t1)
13649 str (org-add-props
13650 (format-time-string
13651 (substring tf 1 -1) (apply 'encode-time time))
13652 nil 'mouse-face 'highlight)
13653 w2 (length str))
13654 (if (not (= w2 w1))
13655 (add-text-properties (1+ beg) (+ 2 beg)
13656 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13657 (if (featurep 'xemacs)
13658 (progn
13659 (put-text-property beg end 'invisible t)
13660 (put-text-property beg end 'end-glyph (make-glyph str)))
13661 (put-text-property beg end 'display str))))
13663 (defun org-translate-time (string)
13664 "Translate all timestamps in STRING to custom format.
13665 But do this only if the variable `org-display-custom-times' is set."
13666 (when org-display-custom-times
13667 (save-match-data
13668 (let* ((start 0)
13669 (re org-ts-regexp-both)
13670 t1 with-hm inactive tf time str beg end)
13671 (while (setq start (string-match re string start))
13672 (setq beg (match-beginning 0)
13673 end (match-end 0)
13674 t1 (save-match-data
13675 (org-parse-time-string (substring string beg end) t))
13676 with-hm (and (nth 1 t1) (nth 2 t1))
13677 inactive (equal (substring string beg (1+ beg)) "[")
13678 tf (funcall (if with-hm 'cdr 'car)
13679 org-time-stamp-custom-formats)
13680 time (org-fix-decoded-time t1)
13681 str (format-time-string
13682 (concat
13683 (if inactive "[" "<") (substring tf 1 -1)
13684 (if inactive "]" ">"))
13685 (apply 'encode-time time))
13686 string (replace-match str t t string)
13687 start (+ start (length str)))))))
13688 string)
13690 (defun org-fix-decoded-time (time)
13691 "Set 0 instead of nil for the first 6 elements of time.
13692 Don't touch the rest."
13693 (let ((n 0))
13694 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13696 (defun org-days-to-time (timestamp-string)
13697 "Difference between TIMESTAMP-STRING and now in days."
13698 (- (time-to-days (org-time-string-to-time timestamp-string))
13699 (time-to-days (current-time))))
13701 (defun org-deadline-close (timestamp-string &optional ndays)
13702 "Is the time in TIMESTAMP-STRING close to the current date?"
13703 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13704 (and (< (org-days-to-time timestamp-string) ndays)
13705 (not (org-entry-is-done-p))))
13707 (defun org-get-wdays (ts)
13708 "Get the deadline lead time appropriate for timestring TS."
13709 (cond
13710 ((<= org-deadline-warning-days 0)
13711 ;; 0 or negative, enforce this value no matter what
13712 (- org-deadline-warning-days))
13713 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13714 ;; lead time is specified.
13715 (floor (* (string-to-number (match-string 1 ts))
13716 (cdr (assoc (match-string 2 ts)
13717 '(("d" . 1) ("w" . 7)
13718 ("m" . 30.4) ("y" . 365.25)))))))
13719 ;; go for the default.
13720 (t org-deadline-warning-days)))
13722 (defun org-calendar-select-mouse (ev)
13723 "Return to `org-read-date' with the date currently selected.
13724 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13725 (interactive "e")
13726 (mouse-set-point ev)
13727 (when (calendar-cursor-to-date)
13728 (let* ((date (calendar-cursor-to-date))
13729 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13730 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13731 (if (active-minibuffer-window) (exit-minibuffer))))
13733 (defun org-check-deadlines (ndays)
13734 "Check if there are any deadlines due or past due.
13735 A deadline is considered due if it happens within `org-deadline-warning-days'
13736 days from today's date. If the deadline appears in an entry marked DONE,
13737 it is not shown. The prefix arg NDAYS can be used to test that many
13738 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13739 (interactive "P")
13740 (let* ((org-warn-days
13741 (cond
13742 ((equal ndays '(4)) 100000)
13743 (ndays (prefix-numeric-value ndays))
13744 (t (abs org-deadline-warning-days))))
13745 (case-fold-search nil)
13746 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13747 (callback
13748 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13750 (message "%d deadlines past-due or due within %d days"
13751 (org-occur regexp nil callback)
13752 org-warn-days)))
13754 (defun org-check-before-date (date)
13755 "Check if there are deadlines or scheduled entries before DATE."
13756 (interactive (list (org-read-date)))
13757 (let ((case-fold-search nil)
13758 (regexp (concat "\\<\\(" org-deadline-string
13759 "\\|" org-scheduled-string
13760 "\\) *<\\([^>]+\\)>"))
13761 (callback
13762 (lambda () (time-less-p
13763 (org-time-string-to-time (match-string 2))
13764 (org-time-string-to-time date)))))
13765 (message "%d entries before %s"
13766 (org-occur regexp nil callback) date)))
13768 (defun org-check-after-date (date)
13769 "Check if there are deadlines or scheduled entries after DATE."
13770 (interactive (list (org-read-date)))
13771 (let ((case-fold-search nil)
13772 (regexp (concat "\\<\\(" org-deadline-string
13773 "\\|" org-scheduled-string
13774 "\\) *<\\([^>]+\\)>"))
13775 (callback
13776 (lambda () (not
13777 (time-less-p
13778 (org-time-string-to-time (match-string 2))
13779 (org-time-string-to-time date))))))
13780 (message "%d entries after %s"
13781 (org-occur regexp nil callback) date)))
13783 (defun org-evaluate-time-range (&optional to-buffer)
13784 "Evaluate a time range by computing the difference between start and end.
13785 Normally the result is just printed in the echo area, but with prefix arg
13786 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13787 If the time range is actually in a table, the result is inserted into the
13788 next column.
13789 For time difference computation, a year is assumed to be exactly 365
13790 days in order to avoid rounding problems."
13791 (interactive "P")
13793 (org-clock-update-time-maybe)
13794 (save-excursion
13795 (unless (org-at-date-range-p t)
13796 (goto-char (point-at-bol))
13797 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13798 (if (not (org-at-date-range-p t))
13799 (error "Not at a time-stamp range, and none found in current line")))
13800 (let* ((ts1 (match-string 1))
13801 (ts2 (match-string 2))
13802 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13803 (match-end (match-end 0))
13804 (time1 (org-time-string-to-time ts1))
13805 (time2 (org-time-string-to-time ts2))
13806 (t1 (org-float-time time1))
13807 (t2 (org-float-time time2))
13808 (diff (abs (- t2 t1)))
13809 (negative (< (- t2 t1) 0))
13810 ;; (ys (floor (* 365 24 60 60)))
13811 (ds (* 24 60 60))
13812 (hs (* 60 60))
13813 (fy "%dy %dd %02d:%02d")
13814 (fy1 "%dy %dd")
13815 (fd "%dd %02d:%02d")
13816 (fd1 "%dd")
13817 (fh "%02d:%02d")
13818 y d h m align)
13819 (if havetime
13820 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13822 d (floor (/ diff ds)) diff (mod diff ds)
13823 h (floor (/ diff hs)) diff (mod diff hs)
13824 m (floor (/ diff 60)))
13825 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13827 d (floor (+ (/ diff ds) 0.5))
13828 h 0 m 0))
13829 (if (not to-buffer)
13830 (message "%s" (org-make-tdiff-string y d h m))
13831 (if (org-at-table-p)
13832 (progn
13833 (goto-char match-end)
13834 (setq align t)
13835 (and (looking-at " *|") (goto-char (match-end 0))))
13836 (goto-char match-end))
13837 (if (looking-at
13838 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13839 (replace-match ""))
13840 (if negative (insert " -"))
13841 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13842 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13843 (insert " " (format fh h m))))
13844 (if align (org-table-align))
13845 (message "Time difference inserted")))))
13847 (defun org-make-tdiff-string (y d h m)
13848 (let ((fmt "")
13849 (l nil))
13850 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13851 l (push y l)))
13852 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13853 l (push d l)))
13854 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13855 l (push h l)))
13856 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13857 l (push m l)))
13858 (apply 'format fmt (nreverse l))))
13860 (defun org-time-string-to-time (s)
13861 (apply 'encode-time (org-parse-time-string s)))
13862 (defun org-time-string-to-seconds (s)
13863 (org-float-time (org-time-string-to-time s)))
13865 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13866 "Convert a time stamp to an absolute day number.
13867 If there is a specifyer for a cyclic time stamp, get the closest date to
13868 DAYNR.
13869 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13870 the variable date is bound by the calendar when this is called."
13871 (cond
13872 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13873 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13874 daynr
13875 (+ daynr 1000)))
13876 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13877 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13878 (time-to-days (current-time))) (match-string 0 s)
13879 prefer show-all))
13880 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13882 (defun org-days-to-iso-week (days)
13883 "Return the iso week number."
13884 (require 'cal-iso)
13885 (car (calendar-iso-from-absolute days)))
13887 (defun org-small-year-to-year (year)
13888 "Convert 2-digit years into 4-digit years.
13889 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13890 The year 2000 cannot be abbreviated. Any year larger than 99
13891 is returned unchanged."
13892 (if (< year 38)
13893 (setq year (+ 2000 year))
13894 (if (< year 100)
13895 (setq year (+ 1900 year))))
13896 year)
13898 (defun org-time-from-absolute (d)
13899 "Return the time corresponding to date D.
13900 D may be an absolute day number, or a calendar-type list (month day year)."
13901 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13902 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13904 (defun org-calendar-holiday ()
13905 "List of holidays, for Diary display in Org-mode."
13906 (require 'holidays)
13907 (let ((hl (funcall
13908 (if (fboundp 'calendar-check-holidays)
13909 'calendar-check-holidays 'check-calendar-holidays) date)))
13910 (if hl (mapconcat 'identity hl "; "))))
13912 (defun org-diary-sexp-entry (sexp entry date)
13913 "Process a SEXP diary ENTRY for DATE."
13914 (require 'diary-lib)
13915 (let ((result (if calendar-debug-sexp
13916 (let ((stack-trace-on-error t))
13917 (eval (car (read-from-string sexp))))
13918 (condition-case nil
13919 (eval (car (read-from-string sexp)))
13920 (error
13921 (beep)
13922 (message "Bad sexp at line %d in %s: %s"
13923 (org-current-line)
13924 (buffer-file-name) sexp)
13925 (sleep-for 2))))))
13926 (cond ((stringp result) result)
13927 ((and (consp result)
13928 (stringp (cdr result))) (cdr result))
13929 (result entry)
13930 (t nil))))
13932 (defun org-diary-to-ical-string (frombuf)
13933 "Get iCalendar entries from diary entries in buffer FROMBUF.
13934 This uses the icalendar.el library."
13935 (let* ((tmpdir (if (featurep 'xemacs)
13936 (temp-directory)
13937 temporary-file-directory))
13938 (tmpfile (make-temp-name
13939 (expand-file-name "orgics" tmpdir)))
13940 buf rtn b e)
13941 (with-current-buffer frombuf
13942 (icalendar-export-region (point-min) (point-max) tmpfile)
13943 (setq buf (find-buffer-visiting tmpfile))
13944 (set-buffer buf)
13945 (goto-char (point-min))
13946 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13947 (setq b (match-beginning 0)))
13948 (goto-char (point-max))
13949 (if (re-search-backward "^END:VEVENT" nil t)
13950 (setq e (match-end 0)))
13951 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13952 (kill-buffer buf)
13953 (delete-file tmpfile)
13954 rtn))
13956 (defun org-closest-date (start current change prefer show-all)
13957 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13958 When PREFER is `past' return a date that is either CURRENT or past.
13959 When PREFER is `future', return a date that is either CURRENT or future.
13960 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13961 ;; Make the proper lists from the dates
13962 (catch 'exit
13963 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13964 dn dw sday cday n1 n2 n0
13965 d m y y1 y2 date1 date2 nmonths nm ny m2)
13967 (setq start (org-date-to-gregorian start)
13968 current (org-date-to-gregorian
13969 (if show-all
13970 current
13971 (time-to-days (current-time))))
13972 sday (calendar-absolute-from-gregorian start)
13973 cday (calendar-absolute-from-gregorian current))
13975 (if (<= cday sday) (throw 'exit sday))
13977 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13978 (setq dn (string-to-number (match-string 1 change))
13979 dw (cdr (assoc (match-string 2 change) a1)))
13980 (error "Invalid change specifyer: %s" change))
13981 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13982 (cond
13983 ((eq dw 'day)
13984 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13985 n2 (+ n1 dn)))
13986 ((eq dw 'year)
13987 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13988 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13989 (setq date1 (list m d y1)
13990 n1 (calendar-absolute-from-gregorian date1)
13991 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13992 n2 (calendar-absolute-from-gregorian date2)))
13993 ((eq dw 'month)
13994 ;; approx number of month between the two dates
13995 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13996 ;; How often does dn fit in there?
13997 (setq d (nth 1 start) m (car start) y (nth 2 start)
13998 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13999 m (+ m nm)
14000 ny (floor (/ m 12))
14001 y (+ y ny)
14002 m (- m (* ny 12)))
14003 (while (> m 12) (setq m (- m 12) y (1+ y)))
14004 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14005 (setq m2 (+ m dn) y2 y)
14006 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14007 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14008 (while (<= n2 cday)
14009 (setq n1 n2 m m2 y y2)
14010 (setq m2 (+ m dn) y2 y)
14011 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14012 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14013 ;; Make sure n1 is the earlier date
14014 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14015 (if show-all
14016 (cond
14017 ((eq prefer 'past) (if (= cday n2) n2 n1))
14018 ((eq prefer 'future) (if (= cday n1) n1 n2))
14019 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14020 (cond
14021 ((eq prefer 'past) (if (= cday n2) n2 n1))
14022 ((eq prefer 'future) (if (= cday n1) n1 n2))
14023 (t (if (= cday n1) n1 n2)))))))
14025 (defun org-date-to-gregorian (date)
14026 "Turn any specification of DATE into a gregorian date for the calendar."
14027 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14028 ((and (listp date) (= (length date) 3)) date)
14029 ((stringp date)
14030 (setq date (org-parse-time-string date))
14031 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14032 ((listp date)
14033 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14035 (defun org-parse-time-string (s &optional nodefault)
14036 "Parse the standard Org-mode time string.
14037 This should be a lot faster than the normal `parse-time-string'.
14038 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14039 hour and minute fields will be nil if not given."
14040 (if (string-match org-ts-regexp0 s)
14041 (list 0
14042 (if (or (match-beginning 8) (not nodefault))
14043 (string-to-number (or (match-string 8 s) "0")))
14044 (if (or (match-beginning 7) (not nodefault))
14045 (string-to-number (or (match-string 7 s) "0")))
14046 (string-to-number (match-string 4 s))
14047 (string-to-number (match-string 3 s))
14048 (string-to-number (match-string 2 s))
14049 nil nil nil)
14050 (error "Not a standard Org-mode time string: %s" s)))
14052 (defun org-timestamp-up (&optional arg)
14053 "Increase the date item at the cursor by one.
14054 If the cursor is on the year, change the year. If it is on the month or
14055 the day, change that.
14056 With prefix ARG, change by that many units."
14057 (interactive "p")
14058 (org-timestamp-change (prefix-numeric-value arg)))
14060 (defun org-timestamp-down (&optional arg)
14061 "Decrease the date item at the cursor by one.
14062 If the cursor is on the year, change the year. If it is on the month or
14063 the day, change that.
14064 With prefix ARG, change by that many units."
14065 (interactive "p")
14066 (org-timestamp-change (- (prefix-numeric-value arg))))
14068 (defun org-timestamp-up-day (&optional arg)
14069 "Increase the date in the time stamp by one day.
14070 With prefix ARG, change that many days."
14071 (interactive "p")
14072 (if (and (not (org-at-timestamp-p t))
14073 (org-on-heading-p))
14074 (org-todo 'up)
14075 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14077 (defun org-timestamp-down-day (&optional arg)
14078 "Decrease the date in the time stamp by one day.
14079 With prefix ARG, change that many days."
14080 (interactive "p")
14081 (if (and (not (org-at-timestamp-p t))
14082 (org-on-heading-p))
14083 (org-todo 'down)
14084 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14086 (defun org-at-timestamp-p (&optional inactive-ok)
14087 "Determine if the cursor is in or at a timestamp."
14088 (interactive)
14089 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14090 (pos (point))
14091 (ans (or (looking-at tsr)
14092 (save-excursion
14093 (skip-chars-backward "^[<\n\r\t")
14094 (if (> (point) (point-min)) (backward-char 1))
14095 (and (looking-at tsr)
14096 (> (- (match-end 0) pos) -1))))))
14097 (and ans
14098 (boundp 'org-ts-what)
14099 (setq org-ts-what
14100 (cond
14101 ((= pos (match-beginning 0)) 'bracket)
14102 ((= pos (1- (match-end 0))) 'bracket)
14103 ((org-pos-in-match-range pos 2) 'year)
14104 ((org-pos-in-match-range pos 3) 'month)
14105 ((org-pos-in-match-range pos 7) 'hour)
14106 ((org-pos-in-match-range pos 8) 'minute)
14107 ((or (org-pos-in-match-range pos 4)
14108 (org-pos-in-match-range pos 5)) 'day)
14109 ((and (> pos (or (match-end 8) (match-end 5)))
14110 (< pos (match-end 0)))
14111 (- pos (or (match-end 8) (match-end 5))))
14112 (t 'day))))
14113 ans))
14115 (defun org-toggle-timestamp-type ()
14116 "Toggle the type (<active> or [inactive]) of a time stamp."
14117 (interactive)
14118 (when (org-at-timestamp-p t)
14119 (let ((beg (match-beginning 0)) (end (match-end 0))
14120 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14121 (save-excursion
14122 (goto-char beg)
14123 (while (re-search-forward "[][<>]" end t)
14124 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14125 t t)))
14126 (message "Timestamp is now %sactive"
14127 (if (equal (char-after beg) ?<) "" "in")))))
14129 (defun org-timestamp-change (n &optional what)
14130 "Change the date in the time stamp at point.
14131 The date will be changed by N times WHAT. WHAT can be `day', `month',
14132 `year', `minute', `second'. If WHAT is not given, the cursor position
14133 in the timestamp determines what will be changed."
14134 (let ((pos (point))
14135 with-hm inactive
14136 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14137 org-ts-what
14138 extra rem
14139 ts time time0)
14140 (if (not (org-at-timestamp-p t))
14141 (error "Not at a timestamp"))
14142 (if (and (not what) (eq org-ts-what 'bracket))
14143 (org-toggle-timestamp-type)
14144 (if (and (not what) (not (eq org-ts-what 'day))
14145 org-display-custom-times
14146 (get-text-property (point) 'display)
14147 (not (get-text-property (1- (point)) 'display)))
14148 (setq org-ts-what 'day))
14149 (setq org-ts-what (or what org-ts-what)
14150 inactive (= (char-after (match-beginning 0)) ?\[)
14151 ts (match-string 0))
14152 (replace-match "")
14153 (if (string-match
14154 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14156 (setq extra (match-string 1 ts)))
14157 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14158 (setq with-hm t))
14159 (setq time0 (org-parse-time-string ts))
14160 (when (and (eq org-ts-what 'minute)
14161 (eq current-prefix-arg nil))
14162 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14163 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14164 (setcar (cdr time0) (+ (nth 1 time0)
14165 (if (> n 0) (- rem) (- dm rem))))))
14166 (setq time
14167 (encode-time (or (car time0) 0)
14168 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14169 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14170 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14171 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14172 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14173 (nthcdr 6 time0)))
14174 (when (and (member org-ts-what '(hour minute))
14175 extra
14176 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14177 (setq extra (org-modify-ts-extra
14178 extra
14179 (if (eq org-ts-what 'hour) 2 5)
14180 n dm)))
14181 (when (integerp org-ts-what)
14182 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14183 (if (eq what 'calendar)
14184 (let ((cal-date (org-get-date-from-calendar)))
14185 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14186 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14187 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14188 (setcar time0 (or (car time0) 0))
14189 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14190 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14191 (setq time (apply 'encode-time time0))))
14192 (setq org-last-changed-timestamp
14193 (org-insert-time-stamp time with-hm inactive nil nil extra))
14194 (org-clock-update-time-maybe)
14195 (goto-char pos)
14196 ;; Try to recenter the calendar window, if any
14197 (if (and org-calendar-follow-timestamp-change
14198 (get-buffer-window "*Calendar*" t)
14199 (memq org-ts-what '(day month year)))
14200 (org-recenter-calendar (time-to-days time))))))
14202 (defun org-modify-ts-extra (s pos n dm)
14203 "Change the different parts of the lead-time and repeat fields in timestamp."
14204 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14205 ng h m new rem)
14206 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14207 (cond
14208 ((or (org-pos-in-match-range pos 2)
14209 (org-pos-in-match-range pos 3))
14210 (setq m (string-to-number (match-string 3 s))
14211 h (string-to-number (match-string 2 s)))
14212 (if (org-pos-in-match-range pos 2)
14213 (setq h (+ h n))
14214 (setq n (* dm (org-no-warnings (signum n))))
14215 (when (not (= 0 (setq rem (% m dm))))
14216 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14217 (setq m (+ m n)))
14218 (if (< m 0) (setq m (+ m 60) h (1- h)))
14219 (if (> m 59) (setq m (- m 60) h (1+ h)))
14220 (setq h (min 24 (max 0 h)))
14221 (setq ng 1 new (format "-%02d:%02d" h m)))
14222 ((org-pos-in-match-range pos 6)
14223 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14224 ((org-pos-in-match-range pos 5)
14225 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14227 ((org-pos-in-match-range pos 9)
14228 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14229 ((org-pos-in-match-range pos 8)
14230 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14232 (when ng
14233 (setq s (concat
14234 (substring s 0 (match-beginning ng))
14236 (substring s (match-end ng))))))
14239 (defun org-recenter-calendar (date)
14240 "If the calendar is visible, recenter it to DATE."
14241 (let* ((win (selected-window))
14242 (cwin (get-buffer-window "*Calendar*" t))
14243 (calendar-move-hook nil))
14244 (when cwin
14245 (select-window cwin)
14246 (calendar-goto-date (if (listp date) date
14247 (calendar-gregorian-from-absolute date)))
14248 (select-window win))))
14250 (defun org-goto-calendar (&optional arg)
14251 "Go to the Emacs calendar at the current date.
14252 If there is a time stamp in the current line, go to that date.
14253 A prefix ARG can be used to force the current date."
14254 (interactive "P")
14255 (let ((tsr org-ts-regexp) diff
14256 (calendar-move-hook nil)
14257 (calendar-view-holidays-initially-flag nil)
14258 (view-calendar-holidays-initially nil)
14259 (calendar-view-diary-initially-flag nil)
14260 (view-diary-entries-initially nil))
14261 (if (or (org-at-timestamp-p)
14262 (save-excursion
14263 (beginning-of-line 1)
14264 (looking-at (concat ".*" tsr))))
14265 (let ((d1 (time-to-days (current-time)))
14266 (d2 (time-to-days
14267 (org-time-string-to-time (match-string 1)))))
14268 (setq diff (- d2 d1))))
14269 (calendar)
14270 (calendar-goto-today)
14271 (if (and diff (not arg)) (calendar-forward-day diff))))
14273 (defun org-get-date-from-calendar ()
14274 "Return a list (month day year) of date at point in calendar."
14275 (with-current-buffer "*Calendar*"
14276 (save-match-data
14277 (calendar-cursor-to-date))))
14279 (defun org-date-from-calendar ()
14280 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14281 If there is already a time stamp at the cursor position, update it."
14282 (interactive)
14283 (if (org-at-timestamp-p t)
14284 (org-timestamp-change 0 'calendar)
14285 (let ((cal-date (org-get-date-from-calendar)))
14286 (org-insert-time-stamp
14287 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14289 (defun org-minutes-to-hh:mm-string (m)
14290 "Compute H:MM from a number of minutes."
14291 (let ((h (/ m 60)))
14292 (setq m (- m (* 60 h)))
14293 (format org-time-clocksum-format h m)))
14295 (defun org-hh:mm-string-to-minutes (s)
14296 "Convert a string H:MM to a number of minutes.
14297 If the string is just a number, interpret it as minutes.
14298 In fact, the first hh:mm or number in the string will be taken,
14299 there can be extra stuff in the string.
14300 If no number is found, the return value is 0."
14301 (cond
14302 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14303 (+ (* (string-to-number (match-string 1 s)) 60)
14304 (string-to-number (match-string 2 s))))
14305 ((string-match "\\([0-9]+\\)" s)
14306 (string-to-number (match-string 1 s)))
14307 (t 0)))
14309 ;;;; Files
14311 (defun org-save-all-org-buffers ()
14312 "Save all Org-mode buffers without user confirmation."
14313 (interactive)
14314 (message "Saving all Org-mode buffers...")
14315 (save-some-buffers t 'org-mode-p)
14316 (when (featurep 'org-id) (org-id-locations-save))
14317 (message "Saving all Org-mode buffers... done"))
14319 (defun org-revert-all-org-buffers ()
14320 "Revert all Org-mode buffers.
14321 Prompt for confirmation when there are unsaved changes.
14322 Be sure you know what you are doing before letting this function
14323 overwrite your changes.
14325 This function is useful in a setup where one tracks org files
14326 with a version control system, to revert on one machine after pulling
14327 changes from another. I believe the procedure must be like this:
14329 1. M-x org-save-all-org-buffers
14330 2. Pull changes from the other machine, resolve conflicts
14331 3. M-x org-revert-all-org-buffers"
14332 (interactive)
14333 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14334 (error "Abort"))
14335 (save-excursion
14336 (save-window-excursion
14337 (mapc
14338 (lambda (b)
14339 (when (and (with-current-buffer b (org-mode-p))
14340 (with-current-buffer b buffer-file-name))
14341 (switch-to-buffer b)
14342 (revert-buffer t 'no-confirm)))
14343 (buffer-list))
14344 (when (and (featurep 'org-id) org-id-track-globally)
14345 (org-id-locations-load)))))
14347 ;;;; Agenda files
14349 ;;;###autoload
14350 (defun org-iswitchb (&optional arg)
14351 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14352 With a prefix argument, restrict available to files.
14353 With two prefix arguments, restrict available buffers to agenda files."
14354 (interactive "P")
14355 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14356 ((equal arg '(16)) (org-buffer-list 'agenda))
14357 (t (org-buffer-list)))))
14358 (switch-to-buffer
14359 (org-icompleting-read "Org buffer: "
14360 (mapcar 'list (mapcar 'buffer-name blist))
14361 nil t))))
14363 ;;;###autoload
14364 (defalias 'org-ido-switchb 'org-iswitchb)
14366 (defun org-buffer-list (&optional predicate exclude-tmp)
14367 "Return a list of Org buffers.
14368 PREDICATE can be `export', `files' or `agenda'.
14370 export restrict the list to Export buffers.
14371 files restrict the list to buffers visiting Org files.
14372 agenda restrict the list to buffers visiting agenda files.
14374 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14375 (let* ((bfn nil)
14376 (agenda-files (and (eq predicate 'agenda)
14377 (mapcar 'file-truename (org-agenda-files t))))
14378 (filter
14379 (cond
14380 ((eq predicate 'files)
14381 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14382 ((eq predicate 'export)
14383 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14384 ((eq predicate 'agenda)
14385 (lambda (b)
14386 (with-current-buffer b
14387 (and (eq major-mode 'org-mode)
14388 (setq bfn (buffer-file-name b))
14389 (member (file-truename bfn) agenda-files)))))
14390 (t (lambda (b) (with-current-buffer b
14391 (or (eq major-mode 'org-mode)
14392 (string-match "\*Org .*Export"
14393 (buffer-name b)))))))))
14394 (delq nil
14395 (mapcar
14396 (lambda(b)
14397 (if (and (funcall filter b)
14398 (or (not exclude-tmp)
14399 (not (string-match "tmp" (buffer-name b)))))
14401 nil))
14402 (buffer-list)))))
14404 (defun org-agenda-files (&optional unrestricted archives)
14405 "Get the list of agenda files.
14406 Optional UNRESTRICTED means return the full list even if a restriction
14407 is currently in place.
14408 When ARCHIVES is t, include all archive files hat are really being
14409 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14410 `org-agenda-archives-mode' is t."
14411 (let ((files
14412 (cond
14413 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14414 ((stringp org-agenda-files) (org-read-agenda-file-list))
14415 ((listp org-agenda-files) org-agenda-files)
14416 (t (error "Invalid value of `org-agenda-files'")))))
14417 (setq files (apply 'append
14418 (mapcar (lambda (f)
14419 (if (file-directory-p f)
14420 (directory-files
14421 f t org-agenda-file-regexp)
14422 (list f)))
14423 files)))
14424 (when org-agenda-skip-unavailable-files
14425 (setq files (delq nil
14426 (mapcar (function
14427 (lambda (file)
14428 (and (file-readable-p file) file)))
14429 files))))
14430 (when (or (eq archives t)
14431 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14432 (setq files (org-add-archive-files files)))
14433 files))
14435 (defun org-edit-agenda-file-list ()
14436 "Edit the list of agenda files.
14437 Depending on setup, this either uses customize to edit the variable
14438 `org-agenda-files', or it visits the file that is holding the list. In the
14439 latter case, the buffer is set up in a way that saving it automatically kills
14440 the buffer and restores the previous window configuration."
14441 (interactive)
14442 (if (stringp org-agenda-files)
14443 (let ((cw (current-window-configuration)))
14444 (find-file org-agenda-files)
14445 (org-set-local 'org-window-configuration cw)
14446 (org-add-hook 'after-save-hook
14447 (lambda ()
14448 (set-window-configuration
14449 (prog1 org-window-configuration
14450 (kill-buffer (current-buffer))))
14451 (org-install-agenda-files-menu)
14452 (message "New agenda file list installed"))
14453 nil 'local)
14454 (message "%s" (substitute-command-keys
14455 "Edit list and finish with \\[save-buffer]")))
14456 (customize-variable 'org-agenda-files)))
14458 (defun org-store-new-agenda-file-list (list)
14459 "Set new value for the agenda file list and save it correctly."
14460 (if (stringp org-agenda-files)
14461 (let ((f org-agenda-files) b)
14462 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14463 (with-temp-file f
14464 (insert (mapconcat 'identity list "\n") "\n")))
14465 (let ((org-mode-hook nil) (org-inhibit-startup t)
14466 (org-insert-mode-line-in-empty-file nil))
14467 (setq org-agenda-files list)
14468 (customize-save-variable 'org-agenda-files org-agenda-files))))
14470 (defun org-read-agenda-file-list ()
14471 "Read the list of agenda files from a file."
14472 (when (file-directory-p org-agenda-files)
14473 (error "`org-agenda-files' cannot be a single directory"))
14474 (when (stringp org-agenda-files)
14475 (with-temp-buffer
14476 (insert-file-contents org-agenda-files)
14477 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14480 ;;;###autoload
14481 (defun org-cycle-agenda-files ()
14482 "Cycle through the files in `org-agenda-files'.
14483 If the current buffer visits an agenda file, find the next one in the list.
14484 If the current buffer does not, find the first agenda file."
14485 (interactive)
14486 (let* ((fs (org-agenda-files t))
14487 (files (append fs (list (car fs))))
14488 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14489 file)
14490 (unless files (error "No agenda files"))
14491 (catch 'exit
14492 (while (setq file (pop files))
14493 (if (equal (file-truename file) tcf)
14494 (when (car files)
14495 (find-file (car files))
14496 (throw 'exit t))))
14497 (find-file (car fs)))
14498 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14500 (defun org-agenda-file-to-front (&optional to-end)
14501 "Move/add the current file to the top of the agenda file list.
14502 If the file is not present in the list, it is added to the front. If it is
14503 present, it is moved there. With optional argument TO-END, add/move to the
14504 end of the list."
14505 (interactive "P")
14506 (let ((org-agenda-skip-unavailable-files nil)
14507 (file-alist (mapcar (lambda (x)
14508 (cons (file-truename x) x))
14509 (org-agenda-files t)))
14510 (ctf (file-truename buffer-file-name))
14511 x had)
14512 (setq x (assoc ctf file-alist) had x)
14514 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14515 (if to-end
14516 (setq file-alist (append (delq x file-alist) (list x)))
14517 (setq file-alist (cons x (delq x file-alist))))
14518 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14519 (org-install-agenda-files-menu)
14520 (message "File %s to %s of agenda file list"
14521 (if had "moved" "added") (if to-end "end" "front"))))
14523 (defun org-remove-file (&optional file)
14524 "Remove current file from the list of files in variable `org-agenda-files'.
14525 These are the files which are being checked for agenda entries.
14526 Optional argument FILE means, use this file instead of the current."
14527 (interactive)
14528 (let* ((org-agenda-skip-unavailable-files nil)
14529 (file (or file buffer-file-name))
14530 (true-file (file-truename file))
14531 (afile (abbreviate-file-name file))
14532 (files (delq nil (mapcar
14533 (lambda (x)
14534 (if (equal true-file
14535 (file-truename x))
14536 nil x))
14537 (org-agenda-files t)))))
14538 (if (not (= (length files) (length (org-agenda-files t))))
14539 (progn
14540 (org-store-new-agenda-file-list files)
14541 (org-install-agenda-files-menu)
14542 (message "Removed file: %s" afile))
14543 (message "File was not in list: %s (not removed)" afile))))
14545 (defun org-file-menu-entry (file)
14546 (vector file (list 'find-file file) t))
14548 (defun org-check-agenda-file (file)
14549 "Make sure FILE exists. If not, ask user what to do."
14550 (when (not (file-exists-p file))
14551 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14552 (abbreviate-file-name file))
14553 (let ((r (downcase (read-char-exclusive))))
14554 (cond
14555 ((equal r ?r)
14556 (org-remove-file file)
14557 (throw 'nextfile t))
14558 (t (error "Abort"))))))
14560 (defun org-get-agenda-file-buffer (file)
14561 "Get a buffer visiting FILE. If the buffer needs to be created, add
14562 it to the list of buffers which might be released later."
14563 (let ((buf (org-find-base-buffer-visiting file)))
14564 (if buf
14565 buf ; just return it
14566 ;; Make a new buffer and remember it
14567 (setq buf (find-file-noselect file))
14568 (if buf (push buf org-agenda-new-buffers))
14569 buf)))
14571 (defun org-release-buffers (blist)
14572 "Release all buffers in list, asking the user for confirmation when needed.
14573 When a buffer is unmodified, it is just killed. When modified, it is saved
14574 \(if the user agrees) and then killed."
14575 (let (buf file)
14576 (while (setq buf (pop blist))
14577 (setq file (buffer-file-name buf))
14578 (when (and (buffer-modified-p buf)
14579 file
14580 (y-or-n-p (format "Save file %s? " file)))
14581 (with-current-buffer buf (save-buffer)))
14582 (kill-buffer buf))))
14584 (defun org-prepare-agenda-buffers (files)
14585 "Create buffers for all agenda files, protect archived trees and comments."
14586 (interactive)
14587 (let ((pa '(:org-archived t))
14588 (pc '(:org-comment t))
14589 (pall '(:org-archived t :org-comment t))
14590 (inhibit-read-only t)
14591 (rea (concat ":" org-archive-tag ":"))
14592 bmp file re)
14593 (save-excursion
14594 (save-restriction
14595 (while (setq file (pop files))
14596 (catch 'nextfile
14597 (if (bufferp file)
14598 (set-buffer file)
14599 (org-check-agenda-file file)
14600 (set-buffer (org-get-agenda-file-buffer file)))
14601 (widen)
14602 (setq bmp (buffer-modified-p))
14603 (org-refresh-category-properties)
14604 (setq org-todo-keywords-for-agenda
14605 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14606 (setq org-done-keywords-for-agenda
14607 (append org-done-keywords-for-agenda org-done-keywords))
14608 (setq org-todo-keyword-alist-for-agenda
14609 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14610 (setq org-drawers-for-agenda
14611 (append org-drawers-for-agenda org-drawers))
14612 (setq org-tag-alist-for-agenda
14613 (append org-tag-alist-for-agenda org-tag-alist))
14615 (save-excursion
14616 (remove-text-properties (point-min) (point-max) pall)
14617 (when org-agenda-skip-archived-trees
14618 (goto-char (point-min))
14619 (while (re-search-forward rea nil t)
14620 (if (org-on-heading-p t)
14621 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14622 (goto-char (point-min))
14623 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14624 (while (re-search-forward re nil t)
14625 (add-text-properties
14626 (match-beginning 0) (org-end-of-subtree t) pc)))
14627 (set-buffer-modified-p bmp)))))
14628 (setq org-todo-keyword-alist-for-agenda
14629 (org-uniquify org-todo-keyword-alist-for-agenda)
14630 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14632 ;;;; Embedded LaTeX
14634 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14635 "Keymap for the minor `org-cdlatex-mode'.")
14637 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14638 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14639 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14640 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14641 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14643 (defvar org-cdlatex-texmathp-advice-is-done nil
14644 "Flag remembering if we have applied the advice to texmathp already.")
14646 (define-minor-mode org-cdlatex-mode
14647 "Toggle the minor `org-cdlatex-mode'.
14648 This mode supports entering LaTeX environment and math in LaTeX fragments
14649 in Org-mode.
14650 \\{org-cdlatex-mode-map}"
14651 nil " OCDL" nil
14652 (when org-cdlatex-mode (require 'cdlatex))
14653 (unless org-cdlatex-texmathp-advice-is-done
14654 (setq org-cdlatex-texmathp-advice-is-done t)
14655 (defadvice texmathp (around org-math-always-on activate)
14656 "Always return t in org-mode buffers.
14657 This is because we want to insert math symbols without dollars even outside
14658 the LaTeX math segments. If Orgmode thinks that point is actually inside
14659 an embedded LaTeX fragment, let texmathp do its job.
14660 \\[org-cdlatex-mode-map]"
14661 (interactive)
14662 (let (p)
14663 (cond
14664 ((not (org-mode-p)) ad-do-it)
14665 ((eq this-command 'cdlatex-math-symbol)
14666 (setq ad-return-value t
14667 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14669 (let ((p (org-inside-LaTeX-fragment-p)))
14670 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14671 (setq ad-return-value t
14672 texmathp-why '("Org-mode embedded math" . 0))
14673 (if p ad-do-it)))))))))
14675 (defun turn-on-org-cdlatex ()
14676 "Unconditionally turn on `org-cdlatex-mode'."
14677 (org-cdlatex-mode 1))
14679 (defun org-inside-LaTeX-fragment-p ()
14680 "Test if point is inside a LaTeX fragment.
14681 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14682 sequence appearing also before point.
14683 Even though the matchers for math are configurable, this function assumes
14684 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14685 delimiters are skipped when they have been removed by customization.
14686 The return value is nil, or a cons cell with the delimiter and
14687 and the position of this delimiter.
14689 This function does a reasonably good job, but can locally be fooled by
14690 for example currency specifications. For example it will assume being in
14691 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14692 fragments that are properly closed, but during editing, we have to live
14693 with the uncertainty caused by missing closing delimiters. This function
14694 looks only before point, not after."
14695 (catch 'exit
14696 (let ((pos (point))
14697 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14698 (lim (progn
14699 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14700 (point)))
14701 dd-on str (start 0) m re)
14702 (goto-char pos)
14703 (when dodollar
14704 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14705 re (nth 1 (assoc "$" org-latex-regexps)))
14706 (while (string-match re str start)
14707 (cond
14708 ((= (match-end 0) (length str))
14709 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14710 ((= (match-end 0) (- (length str) 5))
14711 (throw 'exit nil))
14712 (t (setq start (match-end 0))))))
14713 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14714 (goto-char pos)
14715 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14716 (and (match-beginning 2) (throw 'exit nil))
14717 ;; count $$
14718 (while (re-search-backward "\\$\\$" lim t)
14719 (setq dd-on (not dd-on)))
14720 (goto-char pos)
14721 (if dd-on (cons "$$" m))))))
14723 (defun org-inside-latex-macro-p ()
14724 "Is point inside a LaTeX macro or its arguments?"
14725 (save-match-data
14726 (org-in-regexp
14727 "\\\\[a-zA-Z]+\\*?\\(\\[[^][\n{}]*\\]\\)?\\({[^{}\n]*}\\)?")))
14729 (defun org-try-cdlatex-tab ()
14730 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14731 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14732 - inside a LaTeX fragment, or
14733 - after the first word in a line, where an abbreviation expansion could
14734 insert a LaTeX environment."
14735 (when org-cdlatex-mode
14736 (cond
14737 ((save-excursion
14738 (skip-chars-backward "a-zA-Z0-9*")
14739 (skip-chars-backward " \t")
14740 (bolp))
14741 (cdlatex-tab) t)
14742 ((org-inside-LaTeX-fragment-p)
14743 (cdlatex-tab) t)
14744 (t nil))))
14746 (defun org-cdlatex-underscore-caret (&optional arg)
14747 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14748 Revert to the normal definition outside of these fragments."
14749 (interactive "P")
14750 (if (org-inside-LaTeX-fragment-p)
14751 (call-interactively 'cdlatex-sub-superscript)
14752 (let (org-cdlatex-mode)
14753 (call-interactively (key-binding (vector last-input-event))))))
14755 (defun org-cdlatex-math-modify (&optional arg)
14756 "Execute `cdlatex-math-modify' in LaTeX fragments.
14757 Revert to the normal definition outside of these fragments."
14758 (interactive "P")
14759 (if (org-inside-LaTeX-fragment-p)
14760 (call-interactively 'cdlatex-math-modify)
14761 (let (org-cdlatex-mode)
14762 (call-interactively (key-binding (vector last-input-event))))))
14764 (defvar org-latex-fragment-image-overlays nil
14765 "List of overlays carrying the images of latex fragments.")
14766 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14768 (defun org-remove-latex-fragment-image-overlays ()
14769 "Remove all overlays with LaTeX fragment images in current buffer."
14770 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14771 (setq org-latex-fragment-image-overlays nil))
14773 (defun org-preview-latex-fragment (&optional subtree)
14774 "Preview the LaTeX fragment at point, or all locally or globally.
14775 If the cursor is in a LaTeX fragment, create the image and overlay
14776 it over the source code. If there is no fragment at point, display
14777 all fragments in the current text, from one headline to the next. With
14778 prefix SUBTREE, display all fragments in the current subtree. With a
14779 double prefix `C-u C-u', or when the cursor is before the first headline,
14780 display all fragments in the buffer.
14781 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14782 (interactive "P")
14783 (org-remove-latex-fragment-image-overlays)
14784 (save-excursion
14785 (save-restriction
14786 (let (beg end at msg)
14787 (cond
14788 ((or (equal subtree '(16))
14789 (not (save-excursion
14790 (re-search-backward (concat "^" outline-regexp) nil t))))
14791 (setq beg (point-min) end (point-max)
14792 msg "Creating images for buffer...%s"))
14793 ((equal subtree '(4))
14794 (org-back-to-heading)
14795 (setq beg (point) end (org-end-of-subtree t)
14796 msg "Creating images for subtree...%s"))
14798 (if (setq at (org-inside-LaTeX-fragment-p))
14799 (goto-char (max (point-min) (- (cdr at) 2)))
14800 (org-back-to-heading))
14801 (setq beg (point) end (progn (outline-next-heading) (point))
14802 msg (if at "Creating image...%s"
14803 "Creating images for entry...%s"))))
14804 (message msg "")
14805 (narrow-to-region beg end)
14806 (goto-char beg)
14807 (org-format-latex
14808 (concat "ltxpng/" (file-name-sans-extension
14809 (file-name-nondirectory
14810 buffer-file-name)))
14811 default-directory 'overlays msg at 'forbuffer)
14812 (message msg "done. Use `C-c C-c' to remove images.")))))
14814 (defvar org-latex-regexps
14815 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14816 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14817 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14818 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14819 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14820 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14821 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14822 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14823 "Regular expressions for matching embedded LaTeX.")
14825 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14826 "Replace LaTeX fragments with links to an image, and produce images.
14827 Some of the options can be changed using the variable
14828 `org-format-latex-options'."
14829 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14830 (let* ((prefixnodir (file-name-nondirectory prefix))
14831 (absprefix (expand-file-name prefix dir))
14832 (todir (file-name-directory absprefix))
14833 (opt org-format-latex-options)
14834 (matchers (plist-get opt :matchers))
14835 (re-list org-latex-regexps)
14836 (org-format-latex-header-extra
14837 (plist-get (org-infile-export-plist) :latex-header-extra))
14838 (cnt 0) txt hash link beg end re e checkdir
14839 executables-checked
14840 m n block linkfile movefile ov)
14841 ;; Check the different regular expressions
14842 (while (setq e (pop re-list))
14843 (setq m (car e) re (nth 1 e) n (nth 2 e)
14844 block (if (nth 3 e) "\n\n" ""))
14845 (when (member m matchers)
14846 (goto-char (point-min))
14847 (while (re-search-forward re nil t)
14848 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14849 (not (get-text-property (match-beginning n)
14850 'org-protected))
14851 (or (not overlays)
14852 (not (eq (get-char-property (match-beginning n)
14853 'org-overlay-type)
14854 'org-latex-overlay))))
14855 (setq txt (match-string n)
14856 beg (match-beginning n) end (match-end n)
14857 cnt (1+ cnt))
14858 (let (print-length print-level) ; make sure full list is printed
14859 (setq hash (sha1 (prin1-to-string
14860 (list org-format-latex-header
14861 org-format-latex-header-extra
14862 org-export-latex-packages-alist
14863 org-format-latex-options
14864 forbuffer txt)))
14865 linkfile (format "%s_%s.png" prefix hash)
14866 movefile (format "%s_%s.png" absprefix hash)))
14867 (setq link (concat block "[[file:" linkfile "]]" block))
14868 (if msg (message msg cnt))
14869 (goto-char beg)
14870 (unless checkdir ; make sure the directory exists
14871 (setq checkdir t)
14872 (or (file-directory-p todir) (make-directory todir)))
14874 (unless executables-checked
14875 (org-check-external-command
14876 "latex" "needed to convert LaTeX fragments to images")
14877 (org-check-external-command
14878 "dvipng" "needed to convert LaTeX fragments to images")
14879 (setq executables-checked t))
14881 (unless (file-exists-p movefile)
14882 (org-create-formula-image
14883 txt movefile opt forbuffer))
14884 (if overlays
14885 (progn
14886 (mapc (lambda (o)
14887 (if (eq (org-overlay-get o 'org-overlay-type)
14888 'org-latex-overlay)
14889 (org-delete-overlay o)))
14890 (org-overlays-in beg end))
14891 (setq ov (org-make-overlay beg end))
14892 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14893 (if (featurep 'xemacs)
14894 (progn
14895 (org-overlay-put ov 'invisible t)
14896 (org-overlay-put
14897 ov 'end-glyph
14898 (make-glyph (vector 'png :file movefile))))
14899 (org-overlay-put
14900 ov 'display
14901 (list 'image :type 'png :file movefile :ascent 'center)))
14902 (push ov org-latex-fragment-image-overlays)
14903 (goto-char end))
14904 (delete-region beg end)
14905 (insert link))))))))
14907 ;; This function borrows from Ganesh Swami's latex2png.el
14908 (defun org-create-formula-image (string tofile options buffer)
14909 "This calls dvipng."
14910 (require 'org-latex)
14911 (let* ((tmpdir (if (featurep 'xemacs)
14912 (temp-directory)
14913 temporary-file-directory))
14914 (texfilebase (make-temp-name
14915 (expand-file-name "orgtex" tmpdir)))
14916 (texfile (concat texfilebase ".tex"))
14917 (dvifile (concat texfilebase ".dvi"))
14918 (pngfile (concat texfilebase ".png"))
14919 (fnh (if (featurep 'xemacs)
14920 (font-height (get-face-font 'default))
14921 (face-attribute 'default :height nil)))
14922 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14923 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14924 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14925 "Black"))
14926 (bg (or (plist-get options (if buffer :background :html-background))
14927 "Transparent")))
14928 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14929 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14930 (with-temp-file texfile
14931 (insert org-format-latex-header
14932 (if org-export-latex-packages-alist
14933 (concat "\n"
14934 (mapconcat (lambda(p)
14935 (if (equal "" (car p))
14936 (format "\\usepackage{%s}" (cadr p))
14937 (format "\\usepackage[%s]{%s}"
14938 (car p) (cadr p))))
14939 org-export-latex-packages-alist "\n"))
14941 (if org-format-latex-header-extra
14942 (concat "\n" org-format-latex-header-extra)
14944 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14945 (let ((dir default-directory))
14946 (condition-case nil
14947 (progn
14948 (cd tmpdir)
14949 (call-process "latex" nil nil nil texfile))
14950 (error nil))
14951 (cd dir))
14952 (if (not (file-exists-p dvifile))
14953 (progn (message "Failed to create dvi file from %s" texfile) nil)
14954 (condition-case nil
14955 (call-process "dvipng" nil nil nil
14956 "-fg" fg "-bg" bg
14957 "-D" dpi
14958 ;;"-x" scale "-y" scale
14959 "-T" "tight"
14960 "-o" pngfile
14961 dvifile)
14962 (error nil))
14963 (if (not (file-exists-p pngfile))
14964 (progn (message "Failed to create png file from %s" texfile) nil)
14965 ;; Use the requested file name and clean up
14966 (copy-file pngfile tofile 'replace)
14967 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14968 (delete-file (concat texfilebase e)))
14969 pngfile))))
14971 (defun org-dvipng-color (attr)
14972 "Return an rgb color specification for dvipng."
14973 (apply 'format "rgb %s %s %s"
14974 (mapcar 'org-normalize-color
14975 (color-values (face-attribute 'default attr nil)))))
14977 (defun org-normalize-color (value)
14978 "Return string to be used as color value for an RGB component."
14979 (format "%g" (/ value 65535.0)))
14981 ;;;; Key bindings
14983 ;; Make `C-c C-x' a prefix key
14984 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14986 ;; TAB key with modifiers
14987 (org-defkey org-mode-map "\C-i" 'org-cycle)
14988 (org-defkey org-mode-map [(tab)] 'org-cycle)
14989 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14990 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14991 (org-defkey org-mode-map "\M-\t" 'org-complete)
14992 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14993 ;; The following line is necessary under Suse GNU/Linux
14994 (unless (featurep 'xemacs)
14995 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14996 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14997 (define-key org-mode-map [backtab] 'org-shifttab)
14999 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15000 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15001 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15003 ;; Cursor keys with modifiers
15004 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15005 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15006 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15007 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15009 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15010 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15011 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15012 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15014 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15015 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15016 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15017 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15019 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15020 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15022 ;;; Extra keys for tty access.
15023 ;; We only set them when really needed because otherwise the
15024 ;; menus don't show the simple keys
15026 (when (or org-use-extra-keys
15027 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15028 (not window-system))
15029 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15030 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15031 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15032 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15033 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15034 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15035 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15036 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15037 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15038 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15039 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15040 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15041 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15042 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15043 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15044 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15045 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15046 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15047 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15048 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15049 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15050 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15051 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15052 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15053 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15054 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15055 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15056 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15058 ;; All the other keys
15060 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15061 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15062 (if (boundp 'narrow-map)
15063 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15064 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15065 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15066 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15067 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15068 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15069 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15070 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15071 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15072 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15073 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15074 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15075 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15076 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15077 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15078 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15079 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15080 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15081 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15082 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15083 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15084 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15085 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15086 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15087 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15088 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15089 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15090 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15091 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15092 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15093 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15094 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15095 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15096 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15097 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15098 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15099 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15100 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15101 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15102 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15103 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15104 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15105 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15106 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15107 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15108 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15109 (org-defkey org-mode-map "\C-c^" 'org-sort)
15110 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15111 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15112 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15113 (org-defkey org-mode-map "\C-m" 'org-return)
15114 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15115 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15116 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15117 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15118 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15119 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15120 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15121 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15122 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15123 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15124 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15125 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15126 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15127 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15128 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15129 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15130 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15131 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15132 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15133 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15134 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15136 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15137 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15138 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15139 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15141 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15142 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15143 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15144 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15145 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15146 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15147 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15148 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15149 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15150 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15151 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15152 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15153 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15154 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15155 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15157 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15158 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15159 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15160 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15162 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15164 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15166 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15167 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15169 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15172 (when (featurep 'xemacs)
15173 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15176 (defconst org-speed-commands-default
15178 ("Outline Navigation")
15179 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15180 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15181 ("f" . (org-speed-move-safe 'org-forward-same-level))
15182 ("b" . (org-speed-move-safe 'org-backward-same-level))
15183 ("u" . (org-speed-move-safe 'outline-up-heading))
15184 ("j" . org-goto)
15185 ("g" . (org-refile t))
15186 ("Outline Visibility")
15187 ("c" . org-cycle)
15188 ("C" . org-shifttab)
15189 (" " . org-display-outline-path)
15190 ("Outline Structure Editing")
15191 ("U" . org-shiftmetaup)
15192 ("D" . org-shiftmetadown)
15193 ("r" . org-metaright)
15194 ("l" . org-metaleft)
15195 ("R" . org-shiftmetaright)
15196 ("L" . org-shiftmetaleft)
15197 ("i" . (progn (forward-char 1) (call-interactively
15198 'org-insert-heading-respect-content)))
15199 ("^" . org-sort)
15200 ("w" . org-refile)
15201 ("a" . org-archive-subtree-default-with-confirmation)
15202 ("." . outline-mark-subtree)
15203 ("Clock Commands")
15204 ("I" . org-clock-in)
15205 ("O" . org-clock-out)
15206 ("Meta Data Editing")
15207 ("t" . org-todo)
15208 ("0" . (org-priority ?\ ))
15209 ("1" . (org-priority ?A))
15210 ("2" . (org-priority ?B))
15211 ("3" . (org-priority ?C))
15212 (";" . org-set-tags-command)
15213 ("e" . org-set-effort)
15214 ("Agenda Views etc")
15215 ("v" . org-agenda)
15216 ("/" . org-sparse-tree)
15217 ("Misc")
15218 ("o" . org-open-at-point)
15219 ("?" . org-speed-command-help)
15221 "The default speed commands.")
15223 (defun org-print-speed-command (e)
15224 (if (> (length (car e)) 1)
15225 (progn
15226 (princ "\n")
15227 (princ (car e))
15228 (princ "\n")
15229 (princ (make-string (length (car e)) ?-))
15230 (princ "\n"))
15231 (princ (car e))
15232 (princ " ")
15233 (if (symbolp (cdr e))
15234 (princ (symbol-name (cdr e)))
15235 (prin1 (cdr e)))
15236 (princ "\n")))
15238 (defun org-speed-command-help ()
15239 "Show the available speed commands."
15240 (interactive)
15241 (if (not org-use-speed-commands)
15242 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15243 (with-output-to-temp-buffer "*Help*"
15244 (princ "User-defined Speed commands\n===========================\n")
15245 (mapc 'org-print-speed-command org-speed-commands-user)
15246 (princ "\n")
15247 (princ "Built-in Speed commands\n=======================\n")
15248 (mapc 'org-print-speed-command org-speed-commands-default))
15249 (with-current-buffer "*Help*"
15250 (setq truncate-lines t))))
15252 (defun org-speed-move-safe (cmd)
15253 "Execute CMD, but make sure that the cursor always ends up in a headline.
15254 If not, return to the original position and throw an error."
15255 (interactive)
15256 (let ((pos (point)))
15257 (call-interactively cmd)
15258 (unless (and (bolp) (org-on-heading-p))
15259 (goto-char pos)
15260 (error "Boundary reached while executing %s" cmd))))
15262 (defvar org-self-insert-command-undo-counter 0)
15264 (defvar org-table-auto-blank-field) ; defined in org-table.el
15265 (defvar org-speed-command nil)
15266 (defun org-self-insert-command (N)
15267 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15268 If the cursor is in a table looking at whitespace, the whitespace is
15269 overwritten, and the table is not marked as requiring realignment."
15270 (interactive "p")
15271 (cond
15272 ((and org-use-speed-commands
15273 (or (and (bolp) (looking-at outline-regexp))
15274 (and (functionp org-use-speed-commands)
15275 (funcall org-use-speed-commands)))
15276 (setq
15277 org-speed-command
15278 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15279 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15280 (cond
15281 ((commandp org-speed-command)
15282 (setq this-command org-speed-command)
15283 (call-interactively org-speed-command))
15284 ((functionp org-speed-command)
15285 (funcall org-speed-command))
15286 ((and org-speed-command (listp org-speed-command))
15287 (eval org-speed-command))
15288 (t (let (org-use-speed-commands)
15289 (call-interactively 'org-self-insert-command)))))
15290 ((and
15291 (org-table-p)
15292 (progn
15293 ;; check if we blank the field, and if that triggers align
15294 (and (featurep 'org-table) org-table-auto-blank-field
15295 (member last-command
15296 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15297 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15298 ;; got extra space, this field does not determine column width
15299 (let (org-table-may-need-update) (org-table-blank-field))
15300 ;; no extra space, this field may determine column width
15301 (org-table-blank-field)))
15303 (eq N 1)
15304 (looking-at "[^|\n]* |"))
15305 (let (org-table-may-need-update)
15306 (goto-char (1- (match-end 0)))
15307 (delete-backward-char 1)
15308 (goto-char (match-beginning 0))
15309 (self-insert-command N)))
15311 (setq org-table-may-need-update t)
15312 (self-insert-command N)
15313 (org-fix-tags-on-the-fly)
15314 (if org-self-insert-cluster-for-undo
15315 (if (not (eq last-command 'org-self-insert-command))
15316 (setq org-self-insert-command-undo-counter 1)
15317 (if (>= org-self-insert-command-undo-counter 20)
15318 (setq org-self-insert-command-undo-counter 1)
15319 (and (> org-self-insert-command-undo-counter 0)
15320 buffer-undo-list
15321 (not (cadr buffer-undo-list)) ; remove nil entry
15322 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15323 (setq org-self-insert-command-undo-counter
15324 (1+ org-self-insert-command-undo-counter))))))))
15326 (defun org-fix-tags-on-the-fly ()
15327 (when (and (equal (char-after (point-at-bol)) ?*)
15328 (org-on-heading-p))
15329 (org-align-tags-here org-tags-column)))
15331 (defun org-delete-backward-char (N)
15332 "Like `delete-backward-char', insert whitespace at field end in tables.
15333 When deleting backwards, in tables this function will insert whitespace in
15334 front of the next \"|\" separator, to keep the table aligned. The table will
15335 still be marked for re-alignment if the field did fill the entire column,
15336 because, in this case the deletion might narrow the column."
15337 (interactive "p")
15338 (if (and (org-table-p)
15339 (eq N 1)
15340 (string-match "|" (buffer-substring (point-at-bol) (point)))
15341 (looking-at ".*?|"))
15342 (let ((pos (point))
15343 (noalign (looking-at "[^|\n\r]* |"))
15344 (c org-table-may-need-update))
15345 (backward-delete-char N)
15346 (skip-chars-forward "^|")
15347 (insert " ")
15348 (goto-char (1- pos))
15349 ;; noalign: if there were two spaces at the end, this field
15350 ;; does not determine the width of the column.
15351 (if noalign (setq org-table-may-need-update c)))
15352 (backward-delete-char N)
15353 (org-fix-tags-on-the-fly)))
15355 (defun org-delete-char (N)
15356 "Like `delete-char', but insert whitespace at field end in tables.
15357 When deleting characters, in tables this function will insert whitespace in
15358 front of the next \"|\" separator, to keep the table aligned. The table will
15359 still be marked for re-alignment if the field did fill the entire column,
15360 because, in this case the deletion might narrow the column."
15361 (interactive "p")
15362 (if (and (org-table-p)
15363 (not (bolp))
15364 (not (= (char-after) ?|))
15365 (eq N 1))
15366 (if (looking-at ".*?|")
15367 (let ((pos (point))
15368 (noalign (looking-at "[^|\n\r]* |"))
15369 (c org-table-may-need-update))
15370 (replace-match (concat
15371 (substring (match-string 0) 1 -1)
15372 " |"))
15373 (goto-char pos)
15374 ;; noalign: if there were two spaces at the end, this field
15375 ;; does not determine the width of the column.
15376 (if noalign (setq org-table-may-need-update c)))
15377 (delete-char N))
15378 (delete-char N)
15379 (org-fix-tags-on-the-fly)))
15381 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15382 (put 'org-self-insert-command 'delete-selection t)
15383 (put 'orgtbl-self-insert-command 'delete-selection t)
15384 (put 'org-delete-char 'delete-selection 'supersede)
15385 (put 'org-delete-backward-char 'delete-selection 'supersede)
15386 (put 'org-yank 'delete-selection 'yank)
15388 ;; Make `flyspell-mode' delay after some commands
15389 (put 'org-self-insert-command 'flyspell-delayed t)
15390 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15391 (put 'org-delete-char 'flyspell-delayed t)
15392 (put 'org-delete-backward-char 'flyspell-delayed t)
15394 ;; Make pabbrev-mode expand after org-mode commands
15395 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15396 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15398 ;; How to do this: Measure non-white length of current string
15399 ;; If equal to column width, we should realign.
15401 (defun org-remap (map &rest commands)
15402 "In MAP, remap the functions given in COMMANDS.
15403 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15404 (let (new old)
15405 (while commands
15406 (setq old (pop commands) new (pop commands))
15407 (if (fboundp 'command-remapping)
15408 (org-defkey map (vector 'remap old) new)
15409 (substitute-key-definition old new map global-map)))))
15411 (when (eq org-enable-table-editor 'optimized)
15412 ;; If the user wants maximum table support, we need to hijack
15413 ;; some standard editing functions
15414 (org-remap org-mode-map
15415 'self-insert-command 'org-self-insert-command
15416 'delete-char 'org-delete-char
15417 'delete-backward-char 'org-delete-backward-char)
15418 (org-defkey org-mode-map "|" 'org-force-self-insert))
15420 (defvar org-ctrl-c-ctrl-c-hook nil
15421 "Hook for functions attaching themselves to `C-c C-c'.
15422 This can be used to add additional functionality to the C-c C-c key which
15423 executes context-dependent commands.
15424 Each function will be called with no arguments. The function must check
15425 if the context is appropriate for it to act. If yes, it should do its
15426 thing and then return a non-nil value. If the context is wrong,
15427 just do nothing and return nil.")
15429 (defvar org-tab-first-hook nil
15430 "Hook for functions to attach themselves to TAB.
15431 See `org-ctrl-c-ctrl-c-hook' for more information.
15432 This hook runs as the first action when TAB is pressed, even before
15433 `org-cycle' messes around with the `outline-regexp' to cater for
15434 inline tasks and plain list item folding.
15435 If any function in this hook returns t, not other actions like table
15436 field motion visibility cycling will be done.")
15438 (defvar org-tab-after-check-for-table-hook nil
15439 "Hook for functions to attach themselves to TAB.
15440 See `org-ctrl-c-ctrl-c-hook' for more information.
15441 This hook runs after it has been established that the cursor is not in a
15442 table, but before checking if the cursor is in a headline or if global cycling
15443 should be done.
15444 If any function in this hook returns t, not other actions like visibility
15445 cycling will be done.")
15447 (defvar org-tab-after-check-for-cycling-hook nil
15448 "Hook for functions to attach themselves to TAB.
15449 See `org-ctrl-c-ctrl-c-hook' for more information.
15450 This hook runs after it has been established that not table field motion and
15451 not visibility should be done because of current context. This is probably
15452 the place where a package like yasnippets can hook in.")
15454 (defvar org-tab-before-tab-emulation-hook nil
15455 "Hook for functions to attach themselves to TAB.
15456 See `org-ctrl-c-ctrl-c-hook' for more information.
15457 This hook runs after every other options for TAB have been exhausted, but
15458 before indentation and \t insertion takes place.")
15460 (defvar org-metaleft-hook nil
15461 "Hook for functions attaching themselves to `M-left'.
15462 See `org-ctrl-c-ctrl-c-hook' for more information.")
15463 (defvar org-metaright-hook nil
15464 "Hook for functions attaching themselves to `M-right'.
15465 See `org-ctrl-c-ctrl-c-hook' for more information.")
15466 (defvar org-metaup-hook nil
15467 "Hook for functions attaching themselves to `M-up'.
15468 See `org-ctrl-c-ctrl-c-hook' for more information.")
15469 (defvar org-metadown-hook nil
15470 "Hook for functions attaching themselves to `M-down'.
15471 See `org-ctrl-c-ctrl-c-hook' for more information.")
15472 (defvar org-shiftmetaleft-hook nil
15473 "Hook for functions attaching themselves to `M-S-left'.
15474 See `org-ctrl-c-ctrl-c-hook' for more information.")
15475 (defvar org-shiftmetaright-hook nil
15476 "Hook for functions attaching themselves to `M-S-right'.
15477 See `org-ctrl-c-ctrl-c-hook' for more information.")
15478 (defvar org-shiftmetaup-hook nil
15479 "Hook for functions attaching themselves to `M-S-up'.
15480 See `org-ctrl-c-ctrl-c-hook' for more information.")
15481 (defvar org-shiftmetadown-hook nil
15482 "Hook for functions attaching themselves to `M-S-down'.
15483 See `org-ctrl-c-ctrl-c-hook' for more information.")
15484 (defvar org-metareturn-hook nil
15485 "Hook for functions attaching themselves to `M-RET'.
15486 See `org-ctrl-c-ctrl-c-hook' for more information.")
15488 (defun org-modifier-cursor-error ()
15489 "Throw an error, a modified cursor command was applied in wrong context."
15490 (error "This command is active in special context like tables, headlines or items"))
15492 (defun org-shiftselect-error ()
15493 "Throw an error because Shift-Cursor command was applied in wrong context."
15494 (if (and (boundp 'shift-select-mode) shift-select-mode)
15495 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15496 (error "This command works only in special context like headlines or timestamps")))
15498 (defun org-call-for-shift-select (cmd)
15499 (let ((this-command-keys-shift-translated t))
15500 (call-interactively cmd)))
15502 (defun org-shifttab (&optional arg)
15503 "Global visibility cycling or move to previous table field.
15504 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15505 on context.
15506 See the individual commands for more information."
15507 (interactive "P")
15508 (cond
15509 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15510 ((integerp arg)
15511 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15512 (message "Content view to level: %d" arg)
15513 (org-content (prefix-numeric-value arg2))
15514 (setq org-cycle-global-status 'overview)))
15515 (t (call-interactively 'org-global-cycle))))
15517 (defun org-shiftmetaleft ()
15518 "Promote subtree or delete table column.
15519 Calls `org-promote-subtree', `org-outdent-item',
15520 or `org-table-delete-column', depending on context.
15521 See the individual commands for more information."
15522 (interactive)
15523 (cond
15524 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15525 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15526 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15527 ((org-at-item-p) (call-interactively 'org-outdent-item))
15528 (t (org-modifier-cursor-error))))
15530 (defun org-shiftmetaright ()
15531 "Demote subtree or insert table column.
15532 Calls `org-demote-subtree', `org-indent-item',
15533 or `org-table-insert-column', depending on context.
15534 See the individual commands for more information."
15535 (interactive)
15536 (cond
15537 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15538 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15539 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15540 ((org-at-item-p) (call-interactively 'org-indent-item))
15541 (t (org-modifier-cursor-error))))
15543 (defun org-shiftmetaup (&optional arg)
15544 "Move subtree up or kill table row.
15545 Calls `org-move-subtree-up' or `org-table-kill-row' or
15546 `org-move-item-up' depending on context. See the individual commands
15547 for more information."
15548 (interactive "P")
15549 (cond
15550 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15551 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15552 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15553 ((org-at-item-p) (call-interactively 'org-move-item-up))
15554 (t (org-modifier-cursor-error))))
15556 (defun org-shiftmetadown (&optional arg)
15557 "Move subtree down or insert table row.
15558 Calls `org-move-subtree-down' or `org-table-insert-row' or
15559 `org-move-item-down', depending on context. See the individual
15560 commands for more information."
15561 (interactive "P")
15562 (cond
15563 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15564 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15565 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15566 ((org-at-item-p) (call-interactively 'org-move-item-down))
15567 (t (org-modifier-cursor-error))))
15569 (defun org-metaleft (&optional arg)
15570 "Promote heading or move table column to left.
15571 Calls `org-do-promote' or `org-table-move-column', depending on context.
15572 With no specific context, calls the Emacs default `backward-word'.
15573 See the individual commands for more information."
15574 (interactive "P")
15575 (cond
15576 ((run-hook-with-args-until-success 'org-metaleft-hook))
15577 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15578 ((or (org-on-heading-p)
15579 (and (org-region-active-p)
15580 (save-excursion
15581 (goto-char (region-beginning))
15582 (org-on-heading-p))))
15583 (call-interactively 'org-do-promote))
15584 ((or (org-at-item-p)
15585 (and (org-region-active-p)
15586 (save-excursion
15587 (goto-char (region-beginning))
15588 (org-at-item-p))))
15589 (call-interactively 'org-outdent-item))
15590 (t (call-interactively 'backward-word))))
15592 (defun org-metaright (&optional arg)
15593 "Demote subtree or move table column to right.
15594 Calls `org-do-demote' or `org-table-move-column', depending on context.
15595 With no specific context, calls the Emacs default `forward-word'.
15596 See the individual commands for more information."
15597 (interactive "P")
15598 (cond
15599 ((run-hook-with-args-until-success 'org-metaright-hook))
15600 ((org-at-table-p) (call-interactively 'org-table-move-column))
15601 ((or (org-on-heading-p)
15602 (and (org-region-active-p)
15603 (save-excursion
15604 (goto-char (region-beginning))
15605 (org-on-heading-p))))
15606 (call-interactively 'org-do-demote))
15607 ((or (org-at-item-p)
15608 (and (org-region-active-p)
15609 (save-excursion
15610 (goto-char (region-beginning))
15611 (org-at-item-p))))
15612 (call-interactively 'org-indent-item))
15613 (t (call-interactively 'forward-word))))
15615 (defun org-metaup (&optional arg)
15616 "Move subtree up or move table row up.
15617 Calls `org-move-subtree-up' or `org-table-move-row' or
15618 `org-move-item-up', depending on context. See the individual commands
15619 for more information."
15620 (interactive "P")
15621 (cond
15622 ((run-hook-with-args-until-success 'org-metaup-hook))
15623 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15624 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15625 ((org-at-item-p) (call-interactively 'org-move-item-up))
15626 (t (transpose-lines 1) (beginning-of-line -1))))
15628 (defun org-metadown (&optional arg)
15629 "Move subtree down or move table row down.
15630 Calls `org-move-subtree-down' or `org-table-move-row' or
15631 `org-move-item-down', depending on context. See the individual
15632 commands for more information."
15633 (interactive "P")
15634 (cond
15635 ((run-hook-with-args-until-success 'org-metadown-hook))
15636 ((org-at-table-p) (call-interactively 'org-table-move-row))
15637 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15638 ((org-at-item-p) (call-interactively 'org-move-item-down))
15639 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15641 (defun org-shiftup (&optional arg)
15642 "Increase item in timestamp or increase priority of current headline.
15643 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15644 depending on context. See the individual commands for more information."
15645 (interactive "P")
15646 (cond
15647 ((and org-support-shift-select (org-region-active-p))
15648 (org-call-for-shift-select 'previous-line))
15649 ((org-at-timestamp-p t)
15650 (call-interactively (if org-edit-timestamp-down-means-later
15651 'org-timestamp-down 'org-timestamp-up)))
15652 ((and (not (eq org-support-shift-select 'always))
15653 org-enable-priority-commands
15654 (org-on-heading-p))
15655 (call-interactively 'org-priority-up))
15656 ((and (not org-support-shift-select) (org-at-item-p))
15657 (call-interactively 'org-previous-item))
15658 ((org-clocktable-try-shift 'up arg))
15659 (org-support-shift-select
15660 (org-call-for-shift-select 'previous-line))
15661 (t (org-shiftselect-error))))
15663 (defun org-shiftdown (&optional arg)
15664 "Decrease item in timestamp or decrease priority of current headline.
15665 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15666 depending on context. See the individual commands for more information."
15667 (interactive "P")
15668 (cond
15669 ((and org-support-shift-select (org-region-active-p))
15670 (org-call-for-shift-select 'next-line))
15671 ((org-at-timestamp-p t)
15672 (call-interactively (if org-edit-timestamp-down-means-later
15673 'org-timestamp-up 'org-timestamp-down)))
15674 ((and (not (eq org-support-shift-select 'always))
15675 org-enable-priority-commands
15676 (org-on-heading-p))
15677 (call-interactively 'org-priority-down))
15678 ((and (not org-support-shift-select) (org-at-item-p))
15679 (call-interactively 'org-next-item))
15680 ((org-clocktable-try-shift 'down arg))
15681 (org-support-shift-select
15682 (org-call-for-shift-select 'next-line))
15683 (t (org-shiftselect-error))))
15685 (defun org-shiftright (&optional arg)
15686 "Cycle the thing at point or in the current line, depending on context.
15687 Depending on context, this does one of the following:
15689 - switch a timestamp at point one day into the future
15690 - on a headline, switch to the next TODO keyword.
15691 - on an item, switch entire list to the next bullet type
15692 - on a property line, switch to the next allowed value
15693 - on a clocktable definition line, move time block into the future"
15694 (interactive "P")
15695 (cond
15696 ((and org-support-shift-select (org-region-active-p))
15697 (org-call-for-shift-select 'forward-char))
15698 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15699 ((and (not (eq org-support-shift-select 'always))
15700 (org-on-heading-p))
15701 (let ((org-inhibit-logging
15702 (not org-treat-S-cursor-todo-selection-as-state-change))
15703 (org-inhibit-blocking
15704 (not org-treat-S-cursor-todo-selection-as-state-change)))
15705 (org-call-with-arg 'org-todo 'right)))
15706 ((or (and org-support-shift-select
15707 (not (eq org-support-shift-select 'always))
15708 (org-at-item-bullet-p))
15709 (and (not org-support-shift-select) (org-at-item-p)))
15710 (org-call-with-arg 'org-cycle-list-bullet nil))
15711 ((and (not (eq org-support-shift-select 'always))
15712 (org-at-property-p))
15713 (call-interactively 'org-property-next-allowed-value))
15714 ((org-clocktable-try-shift 'right arg))
15715 (org-support-shift-select
15716 (org-call-for-shift-select 'forward-char))
15717 (t (org-shiftselect-error))))
15719 (defun org-shiftleft (&optional arg)
15720 "Cycle the thing at point or in the current line, depending on context.
15721 Depending on context, this does one of the following:
15723 - switch a timestamp at point one day into the past
15724 - on a headline, switch to the previous TODO keyword.
15725 - on an item, switch entire list to the previous bullet type
15726 - on a property line, switch to the previous allowed value
15727 - on a clocktable definition line, move time block into the past"
15728 (interactive "P")
15729 (cond
15730 ((and org-support-shift-select (org-region-active-p))
15731 (org-call-for-shift-select 'backward-char))
15732 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15733 ((and (not (eq org-support-shift-select 'always))
15734 (org-on-heading-p))
15735 (let ((org-inhibit-logging
15736 (not org-treat-S-cursor-todo-selection-as-state-change))
15737 (org-inhibit-blocking
15738 (not org-treat-S-cursor-todo-selection-as-state-change)))
15739 (org-call-with-arg 'org-todo 'left)))
15740 ((or (and org-support-shift-select
15741 (not (eq org-support-shift-select 'always))
15742 (org-at-item-bullet-p))
15743 (and (not org-support-shift-select) (org-at-item-p)))
15744 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15745 ((and (not (eq org-support-shift-select 'always))
15746 (org-at-property-p))
15747 (call-interactively 'org-property-previous-allowed-value))
15748 ((org-clocktable-try-shift 'left arg))
15749 (org-support-shift-select
15750 (org-call-for-shift-select 'backward-char))
15751 (t (org-shiftselect-error))))
15753 (defun org-shiftcontrolright ()
15754 "Switch to next TODO set."
15755 (interactive)
15756 (cond
15757 ((and org-support-shift-select (org-region-active-p))
15758 (org-call-for-shift-select 'forward-word))
15759 ((and (not (eq org-support-shift-select 'always))
15760 (org-on-heading-p))
15761 (org-call-with-arg 'org-todo 'nextset))
15762 (org-support-shift-select
15763 (org-call-for-shift-select 'forward-word))
15764 (t (org-shiftselect-error))))
15766 (defun org-shiftcontrolleft ()
15767 "Switch to previous TODO set."
15768 (interactive)
15769 (cond
15770 ((and org-support-shift-select (org-region-active-p))
15771 (org-call-for-shift-select 'backward-word))
15772 ((and (not (eq org-support-shift-select 'always))
15773 (org-on-heading-p))
15774 (org-call-with-arg 'org-todo 'previousset))
15775 (org-support-shift-select
15776 (org-call-for-shift-select 'backward-word))
15777 (t (org-shiftselect-error))))
15779 (defun org-ctrl-c-ret ()
15780 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15781 (interactive)
15782 (cond
15783 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15784 (t (call-interactively 'org-insert-heading))))
15786 (defun org-copy-special ()
15787 "Copy region in table or copy current subtree.
15788 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15789 See the individual commands for more information."
15790 (interactive)
15791 (call-interactively
15792 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15794 (defun org-cut-special ()
15795 "Cut region in table or cut current subtree.
15796 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15797 See the individual commands for more information."
15798 (interactive)
15799 (call-interactively
15800 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15802 (defun org-paste-special (arg)
15803 "Paste rectangular region into table, or past subtree relative to level.
15804 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15805 See the individual commands for more information."
15806 (interactive "P")
15807 (if (org-at-table-p)
15808 (org-table-paste-rectangle)
15809 (org-paste-subtree arg)))
15811 (defun org-edit-special ()
15812 "Call a special editor for the stuff at point.
15813 When at a table, call the formula editor with `org-table-edit-formulas'.
15814 When at the first line of an src example, call `org-edit-src-code'.
15815 When in an #+include line, visit the include file. Otherwise call
15816 `ffap' to visit the file at point."
15817 (interactive)
15818 (cond
15819 ((org-at-table-p)
15820 (call-interactively 'org-table-edit-formulas))
15821 ((save-excursion
15822 (beginning-of-line 1)
15823 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15824 (find-file (org-trim (match-string 1))))
15825 ((org-edit-src-code))
15826 ((org-edit-fixed-width-region))
15827 (t (call-interactively 'ffap))))
15830 (defun org-ctrl-c-ctrl-c (&optional arg)
15831 "Set tags in headline, or update according to changed information at point.
15833 This command does many different things, depending on context:
15835 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15836 this is what we do.
15838 - If the cursor is on a statistics cookie, update it.
15840 - If the cursor is in a headline, prompt for tags and insert them
15841 into the current line, aligned to `org-tags-column'. When called
15842 with prefix arg, realign all tags in the current buffer.
15844 - If the cursor is in one of the special #+KEYWORD lines, this
15845 triggers scanning the buffer for these lines and updating the
15846 information.
15848 - If the cursor is inside a table, realign the table. This command
15849 works even if the automatic table editor has been turned off.
15851 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15852 the entire table.
15854 - If the cursor is at a footnote reference or definition, jump to
15855 the corresponding definition or references, respectively.
15857 - If the cursor is a the beginning of a dynamic block, update it.
15859 - If the cursor is inside a table created by the table.el package,
15860 activate that table.
15862 - If the current buffer is a remember buffer, close note and file
15863 it. A prefix argument of 1 files to the default location
15864 without further interaction. A prefix argument of 2 files to
15865 the currently clocking task.
15867 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15868 links in this buffer.
15870 - If the cursor is on a numbered item in a plain list, renumber the
15871 ordered list.
15873 - If the cursor is on a checkbox, toggle it."
15874 (interactive "P")
15875 (let ((org-enable-table-editor t))
15876 (cond
15877 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15878 org-occur-highlights
15879 org-latex-fragment-image-overlays)
15880 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15881 (org-remove-occur-highlights)
15882 (org-remove-latex-fragment-image-overlays)
15883 (message "Temporary highlights/overlays removed from current buffer"))
15884 ((and (local-variable-p 'org-finish-function (current-buffer))
15885 (fboundp org-finish-function))
15886 (funcall org-finish-function))
15887 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15888 ((org-at-property-p)
15889 (call-interactively 'org-property-action))
15890 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15891 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15892 (or (org-on-heading-p) (org-at-item-p)))
15893 (call-interactively 'org-update-statistics-cookies))
15894 ((org-on-heading-p) (call-interactively 'org-set-tags))
15895 ((org-at-table.el-p)
15896 (require 'table)
15897 (beginning-of-line 1)
15898 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15899 (call-interactively 'table-recognize-table))
15900 ((org-at-table-p)
15901 (org-table-maybe-eval-formula)
15902 (if arg
15903 (call-interactively 'org-table-recalculate)
15904 (org-table-maybe-recalculate-line))
15905 (call-interactively 'org-table-align))
15906 ((or (org-footnote-at-reference-p)
15907 (org-footnote-at-definition-p))
15908 (call-interactively 'org-footnote-action))
15909 ((org-at-item-checkbox-p)
15910 (call-interactively 'org-toggle-checkbox))
15911 ((org-at-item-p)
15912 (if arg
15913 (call-interactively 'org-toggle-checkbox)
15914 (call-interactively 'org-maybe-renumber-ordered-list)))
15915 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15916 ;; Dynamic block
15917 (beginning-of-line 1)
15918 (save-excursion (org-update-dblock)))
15919 ((save-excursion
15920 (beginning-of-line 1)
15921 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15922 (cond
15923 ((equal (match-string 1) "TBLFM")
15924 ;; Recalculate the table before this line
15925 (save-excursion
15926 (beginning-of-line 1)
15927 (skip-chars-backward " \r\n\t")
15928 (if (org-at-table-p)
15929 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15931 (let ((org-inhibit-startup-visibility-stuff t)
15932 (org-startup-align-all-tables nil))
15933 (org-save-outline-visibility 'use-markers (org-mode-restart)))
15934 (message "Local setup has been refreshed"))))
15935 ((org-clock-update-time-maybe))
15936 (t (error "C-c C-c can do nothing useful at this location")))))
15938 (defun org-mode-restart ()
15939 "Restart Org-mode, to scan again for special lines.
15940 Also updates the keyword regular expressions."
15941 (interactive)
15942 (org-mode)
15943 (message "Org-mode restarted"))
15945 (defun org-kill-note-or-show-branches ()
15946 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15947 (interactive)
15948 (if (not org-finish-function)
15949 (call-interactively 'show-branches)
15950 (let ((org-note-abort t))
15951 (funcall org-finish-function))))
15953 (defun org-return (&optional indent)
15954 "Goto next table row or insert a newline.
15955 Calls `org-table-next-row' or `newline', depending on context.
15956 See the individual commands for more information."
15957 (interactive)
15958 (cond
15959 ((bobp) (if indent (newline-and-indent) (newline)))
15960 ((org-at-table-p)
15961 (org-table-justify-field-maybe)
15962 (call-interactively 'org-table-next-row))
15963 ((and org-return-follows-link
15964 (eq (get-text-property (point) 'face) 'org-link))
15965 (call-interactively 'org-open-at-point))
15966 ((and (org-at-heading-p)
15967 (looking-at
15968 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15969 (org-show-entry)
15970 (end-of-line 1)
15971 (newline))
15972 (t (if indent (newline-and-indent) (newline)))))
15974 (defun org-return-indent ()
15975 "Goto next table row or insert a newline and indent.
15976 Calls `org-table-next-row' or `newline-and-indent', depending on
15977 context. See the individual commands for more information."
15978 (interactive)
15979 (org-return t))
15981 (defun org-ctrl-c-star ()
15982 "Compute table, or change heading status of lines.
15983 Calls `org-table-recalculate' or `org-toggle-heading',
15984 depending on context."
15985 (interactive)
15986 (cond
15987 ((org-at-table-p)
15988 (call-interactively 'org-table-recalculate))
15990 ;; Convert all lines in region to list items
15991 (call-interactively 'org-toggle-heading))))
15993 (defun org-ctrl-c-minus ()
15994 "Insert separator line in table or modify bullet status of line.
15995 Also turns a plain line or a region of lines into list items.
15996 Calls `org-table-insert-hline', `org-toggle-item', or
15997 `org-cycle-list-bullet', depending on context."
15998 (interactive)
15999 (cond
16000 ((org-at-table-p)
16001 (call-interactively 'org-table-insert-hline))
16002 ((org-region-active-p)
16003 (call-interactively 'org-toggle-item))
16004 ((org-in-item-p)
16005 (call-interactively 'org-cycle-list-bullet))
16007 (call-interactively 'org-toggle-item))))
16009 (defun org-toggle-item ()
16010 "Convert headings or normal lines to items, items to normal lines.
16011 If there is no active region, only the current line is considered.
16013 If the first line in the region is a headline, convert all headlines to items.
16015 If the first line in the region is an item, convert all items to normal lines.
16017 If the first line is normal text, add an item bullet to each line."
16018 (interactive)
16019 (let (l2 l beg end)
16020 (if (org-region-active-p)
16021 (setq beg (region-beginning) end (region-end))
16022 (setq beg (point-at-bol)
16023 end (min (1+ (point-at-eol)) (point-max))))
16024 (save-excursion
16025 (goto-char end)
16026 (setq l2 (org-current-line))
16027 (goto-char beg)
16028 (beginning-of-line 1)
16029 (setq l (1- (org-current-line)))
16030 (if (org-at-item-p)
16031 ;; We already have items, de-itemize
16032 (while (< (setq l (1+ l)) l2)
16033 (when (org-at-item-p)
16034 (goto-char (match-beginning 2))
16035 (delete-region (match-beginning 2) (match-end 2))
16036 (and (looking-at "[ \t]+") (replace-match "")))
16037 (beginning-of-line 2))
16038 (if (org-on-heading-p)
16039 ;; Headings, convert to items
16040 (while (< (setq l (1+ l)) l2)
16041 (if (looking-at org-outline-regexp)
16042 (replace-match "- " t t))
16043 (beginning-of-line 2))
16044 ;; normal lines, turn them into items
16045 (while (< (setq l (1+ l)) l2)
16046 (unless (org-at-item-p)
16047 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16048 (replace-match "\\1- \\2")))
16049 (beginning-of-line 2)))))))
16051 (defun org-toggle-heading (&optional nstars)
16052 "Convert headings to normal text, or items or text to headings.
16053 If there is no active region, only the current line is considered.
16055 If the first line is a heading, remove the stars from all headlines
16056 in the region.
16058 If the first line is a plain list item, turn all plain list items
16059 into headings.
16061 If the first line is a normal line, turn each and every line in the
16062 region into a heading.
16064 When converting a line into a heading, the number of stars is chosen
16065 such that the lines become children of the current entry. However,
16066 when a prefix argument is given, its value determines the number of
16067 stars to add."
16068 (interactive "P")
16069 (let (l2 l itemp beg end)
16070 (if (org-region-active-p)
16071 (setq beg (region-beginning) end (region-end))
16072 (setq beg (point-at-bol)
16073 end (min (1+ (point-at-eol)) (point-max))))
16074 (save-excursion
16075 (goto-char end)
16076 (setq l2 (org-current-line))
16077 (goto-char beg)
16078 (beginning-of-line 1)
16079 (setq l (1- (org-current-line)))
16080 (if (org-on-heading-p)
16081 ;; We already have headlines, de-star them
16082 (while (< (setq l (1+ l)) l2)
16083 (when (org-on-heading-p t)
16084 (and (looking-at outline-regexp) (replace-match "")))
16085 (beginning-of-line 2))
16086 (setq itemp (org-at-item-p))
16087 (let* ((stars
16088 (if nstars
16089 (make-string (prefix-numeric-value current-prefix-arg)
16091 (save-excursion
16092 (if (re-search-backward org-complex-heading-regexp nil t)
16093 (match-string 1) ""))))
16094 (add-stars (cond (nstars "")
16095 ((equal stars "") "*")
16096 (org-odd-levels-only "**")
16097 (t "*")))
16098 (rpl (concat stars add-stars " ")))
16099 (while (< (setq l (1+ l)) l2)
16100 (if itemp
16101 (and (org-at-item-p) (replace-match rpl t t))
16102 (unless (org-on-heading-p)
16103 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16104 (replace-match (concat rpl (match-string 2))))))
16105 (beginning-of-line 2)))))))
16107 (defun org-meta-return (&optional arg)
16108 "Insert a new heading or wrap a region in a table.
16109 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16110 See the individual commands for more information."
16111 (interactive "P")
16112 (cond
16113 ((run-hook-with-args-until-success 'org-metareturn-hook))
16114 ((org-at-table-p)
16115 (call-interactively 'org-table-wrap-region))
16116 (t (call-interactively 'org-insert-heading))))
16118 ;;; Menu entries
16120 ;; Define the Org-mode menus
16121 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16122 '("Tbl"
16123 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16124 ["Next Field" org-cycle (org-at-table-p)]
16125 ["Previous Field" org-shifttab (org-at-table-p)]
16126 ["Next Row" org-return (org-at-table-p)]
16127 "--"
16128 ["Blank Field" org-table-blank-field (org-at-table-p)]
16129 ["Edit Field" org-table-edit-field (org-at-table-p)]
16130 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16131 "--"
16132 ("Column"
16133 ["Move Column Left" org-metaleft (org-at-table-p)]
16134 ["Move Column Right" org-metaright (org-at-table-p)]
16135 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16136 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16137 ("Row"
16138 ["Move Row Up" org-metaup (org-at-table-p)]
16139 ["Move Row Down" org-metadown (org-at-table-p)]
16140 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16141 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16142 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16143 "--"
16144 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16145 ("Rectangle"
16146 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16147 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16148 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16149 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16150 "--"
16151 ("Calculate"
16152 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16153 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16154 ["Edit Formulas" org-edit-special (org-at-table-p)]
16155 "--"
16156 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16157 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16158 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16159 "--"
16160 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16161 "--"
16162 ["Sum Column/Rectangle" org-table-sum
16163 (or (org-at-table-p) (org-region-active-p))]
16164 ["Which Column?" org-table-current-column (org-at-table-p)])
16165 ["Debug Formulas"
16166 org-table-toggle-formula-debugger
16167 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16168 ["Show Col/Row Numbers"
16169 org-table-toggle-coordinate-overlays
16170 :style toggle
16171 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16172 "--"
16173 ["Create" org-table-create (and (not (org-at-table-p))
16174 org-enable-table-editor)]
16175 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16176 ["Import from File" org-table-import (not (org-at-table-p))]
16177 ["Export to File" org-table-export (org-at-table-p)]
16178 "--"
16179 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16181 (easy-menu-define org-org-menu org-mode-map "Org menu"
16182 '("Org"
16183 ("Show/Hide"
16184 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16185 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16186 ["Sparse Tree..." org-sparse-tree t]
16187 ["Reveal Context" org-reveal t]
16188 ["Show All" show-all t]
16189 "--"
16190 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16191 "--"
16192 ["New Heading" org-insert-heading t]
16193 ("Navigate Headings"
16194 ["Up" outline-up-heading t]
16195 ["Next" outline-next-visible-heading t]
16196 ["Previous" outline-previous-visible-heading t]
16197 ["Next Same Level" outline-forward-same-level t]
16198 ["Previous Same Level" outline-backward-same-level t]
16199 "--"
16200 ["Jump" org-goto t])
16201 ("Edit Structure"
16202 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16203 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16204 "--"
16205 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16206 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16207 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16208 "--"
16209 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16210 "--"
16211 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16212 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16213 ["Demote Heading" org-metaright (not (org-at-table-p))]
16214 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16215 "--"
16216 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16217 "--"
16218 ["Convert to odd levels" org-convert-to-odd-levels t]
16219 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16220 ("Editing"
16221 ["Emphasis..." org-emphasize t]
16222 ["Edit Source Example" org-edit-special t]
16223 "--"
16224 ["Footnote new/jump" org-footnote-action t]
16225 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16226 ("Archive"
16227 ["Archive (default method)" org-archive-subtree-default t]
16228 "--"
16229 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16230 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16231 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16233 "--"
16234 ("Hyperlinks"
16235 ["Store Link (Global)" org-store-link t]
16236 ["Find existing link to here" org-occur-link-in-agenda-files t]
16237 ["Insert Link" org-insert-link t]
16238 ["Follow Link" org-open-at-point t]
16239 "--"
16240 ["Next link" org-next-link t]
16241 ["Previous link" org-previous-link t]
16242 "--"
16243 ["Descriptive Links"
16244 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16245 :style radio
16246 :selected (member '(org-link) buffer-invisibility-spec)]
16247 ["Literal Links"
16248 (progn
16249 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16250 :style radio
16251 :selected (not (member '(org-link) buffer-invisibility-spec))])
16252 "--"
16253 ("TODO Lists"
16254 ["TODO/DONE/-" org-todo t]
16255 ("Select keyword"
16256 ["Next keyword" org-shiftright (org-on-heading-p)]
16257 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16258 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16259 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16260 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16261 ["Show TODO Tree" org-show-todo-tree t]
16262 ["Global TODO list" org-todo-list t]
16263 "--"
16264 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16265 :selected org-enforce-todo-dependencies :style toggle :active t]
16266 "Settings for tree at point"
16267 ["Do Children sequentially" org-toggle-ordered-property :style radio
16268 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16269 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16270 ["Do Children parallel" org-toggle-ordered-property :style radio
16271 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16272 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16273 "--"
16274 ["Set Priority" org-priority t]
16275 ["Priority Up" org-shiftup t]
16276 ["Priority Down" org-shiftdown t]
16277 "--"
16278 ["Get news from all feeds" org-feed-update-all t]
16279 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16280 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16281 ("TAGS and Properties"
16282 ["Set Tags" org-set-tags-command t]
16283 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16284 "--"
16285 ["Set property" org-set-property t]
16286 ["Column view of properties" org-columns t]
16287 ["Insert Column View DBlock" org-insert-columns-dblock t])
16288 ("Dates and Scheduling"
16289 ["Timestamp" org-time-stamp t]
16290 ["Timestamp (inactive)" org-time-stamp-inactive t]
16291 ("Change Date"
16292 ["1 Day Later" org-shiftright t]
16293 ["1 Day Earlier" org-shiftleft t]
16294 ["1 ... Later" org-shiftup t]
16295 ["1 ... Earlier" org-shiftdown t])
16296 ["Compute Time Range" org-evaluate-time-range t]
16297 ["Schedule Item" org-schedule t]
16298 ["Deadline" org-deadline t]
16299 "--"
16300 ["Custom time format" org-toggle-time-stamp-overlays
16301 :style radio :selected org-display-custom-times]
16302 "--"
16303 ["Goto Calendar" org-goto-calendar t]
16304 ["Date from Calendar" org-date-from-calendar t]
16305 "--"
16306 ["Start/Restart Timer" org-timer-start t]
16307 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16308 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16309 ["Insert Timer String" org-timer t]
16310 ["Insert Timer Item" org-timer-item t])
16311 ("Logging work"
16312 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16313 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16314 ["Clock out" org-clock-out t]
16315 ["Clock cancel" org-clock-cancel t]
16316 "--"
16317 ["Mark as default task" org-clock-mark-default-task t]
16318 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16319 ["Goto running clock" org-clock-goto t]
16320 "--"
16321 ["Display times" org-clock-display t]
16322 ["Create clock table" org-clock-report t]
16323 "--"
16324 ["Record DONE time"
16325 (progn (setq org-log-done (not org-log-done))
16326 (message "Switching to %s will %s record a timestamp"
16327 (car org-done-keywords)
16328 (if org-log-done "automatically" "not")))
16329 :style toggle :selected org-log-done])
16330 "--"
16331 ["Agenda Command..." org-agenda t]
16332 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16333 ("File List for Agenda")
16334 ("Special views current file"
16335 ["TODO Tree" org-show-todo-tree t]
16336 ["Check Deadlines" org-check-deadlines t]
16337 ["Timeline" org-timeline t]
16338 ["Tags/Property tree" org-match-sparse-tree t])
16339 "--"
16340 ["Export/Publish..." org-export t]
16341 ("LaTeX"
16342 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16343 :selected org-cdlatex-mode]
16344 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16345 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16346 ["Modify math symbol" org-cdlatex-math-modify
16347 (org-inside-LaTeX-fragment-p)]
16348 ["Insert citation" org-reftex-citation t]
16349 "--"
16350 ["Export LaTeX fragments as images"
16351 (if (featurep 'org-exp)
16352 (setq org-export-with-LaTeX-fragments
16353 (not org-export-with-LaTeX-fragments))
16354 (require 'org-exp))
16355 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16356 org-export-with-LaTeX-fragments)]
16357 "--"
16358 ["Template for BEAMER" org-beamer-settings-template t])
16359 "--"
16360 ("MobileOrg"
16361 ["Push Files and Views" org-mobile-push t]
16362 ["Get Captured and Flagged" org-mobile-pull t]
16363 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16364 "--"
16365 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16366 "--"
16367 ("Documentation"
16368 ["Show Version" org-version t]
16369 ["Info Documentation" org-info t])
16370 ("Customize"
16371 ["Browse Org Group" org-customize t]
16372 "--"
16373 ["Expand This Menu" org-create-customize-menu
16374 (fboundp 'customize-menu-create)])
16375 ["Send bug report" org-submit-bug-report t]
16376 "--"
16377 ("Refresh/Reload"
16378 ["Refresh setup current buffer" org-mode-restart t]
16379 ["Reload Org (after update)" org-reload t]
16380 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16383 (defun org-info (&optional node)
16384 "Read documentation for Org-mode in the info system.
16385 With optional NODE, go directly to that node."
16386 (interactive)
16387 (info (format "(org)%s" (or node ""))))
16389 ;;;###autoload
16390 (defun org-submit-bug-report ()
16391 "Submit a bug report on Org-mode via mail.
16393 Don't hesitate to report any problems or inaccurate documentation.
16395 If you don't have setup sending mail from (X)Emacs, please copy the
16396 output buffer into your mail program, as it gives us important
16397 information about your Org-mode version and configuration."
16398 (interactive)
16399 (require 'reporter)
16400 (org-load-modules-maybe)
16401 (org-require-autoloaded-modules)
16402 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16403 (reporter-submit-bug-report
16404 "emacs-orgmode@gnu.org"
16405 (org-version)
16406 (let (list)
16407 (save-window-excursion
16408 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16409 (delete-other-windows)
16410 (erase-buffer)
16411 (insert "You are about to submit a bug report to the Org-mode mailing list.
16413 We would like to add your full Org-mode and Outline configuration to the
16414 bug report. This greatly simplifies the work of the maintainer and
16415 other experts on the mailing list.
16417 HOWEVER, some variables you have customized may contain private
16418 information. The names of customers, colleagues, or friends, might
16419 appear in the form of file names, tags, todo states, or search strings.
16420 If you answer yes to the prompt, you might want to check and remove
16421 such private information before sending the email.")
16422 (add-text-properties (point-min) (point-max) '(face org-warning))
16423 (when (yes-or-no-p "Include your Org-mode configuration ")
16424 (mapatoms
16425 (lambda (v)
16426 (and (boundp v)
16427 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16428 (or (and (symbol-value v)
16429 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16430 (and
16431 (get v 'custom-type) (get v 'standard-value)
16432 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16433 (push v list)))))
16434 (kill-buffer (get-buffer "*Warn about privacy*"))
16435 list))
16436 nil nil
16437 "Remember to cover the basics, that is, what you expected to happen and
16438 what in fact did happen. You don't know how to make a good report? See
16440 http://orgmode.org/manual/Feedback.html#Feedback
16442 Your bug report will be posted to the Org-mode mailing list.
16443 ------------------------------------------------------------------------")
16444 (save-excursion
16445 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16446 (replace-match "\\1Bug: \\3 [\\2]")))))
16449 (defun org-install-agenda-files-menu ()
16450 (let ((bl (buffer-list)))
16451 (save-excursion
16452 (while bl
16453 (set-buffer (pop bl))
16454 (if (org-mode-p) (setq bl nil)))
16455 (when (org-mode-p)
16456 (easy-menu-change
16457 '("Org") "File List for Agenda"
16458 (append
16459 (list
16460 ["Edit File List" (org-edit-agenda-file-list) t]
16461 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16462 ["Remove Current File from List" org-remove-file t]
16463 ["Cycle through agenda files" org-cycle-agenda-files t]
16464 ["Occur in all agenda files" org-occur-in-agenda-files t]
16465 "--")
16466 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16468 ;;;; Documentation
16470 ;;;###autoload
16471 (defun org-require-autoloaded-modules ()
16472 (interactive)
16473 (mapc 'require
16474 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16475 org-docbook org-exp org-html org-icalendar
16476 org-id org-latex
16477 org-publish org-remember org-table
16478 org-timer org-xoxo)))
16480 ;;;###autoload
16481 (defun org-reload (&optional uncompiled)
16482 "Reload all org lisp files.
16483 With prefix arg UNCOMPILED, load the uncompiled versions."
16484 (interactive "P")
16485 (require 'find-func)
16486 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16487 (dir-org (file-name-directory (org-find-library-name "org")))
16488 (dir-org-contrib (ignore-errors
16489 (file-name-directory
16490 (org-find-library-name "org-contribdir"))))
16491 (files
16492 (append (directory-files dir-org t file-re)
16493 (and dir-org-contrib
16494 (directory-files dir-org-contrib t file-re))))
16495 (remove-re (concat (if (featurep 'xemacs)
16496 "org-colview" "org-colview-xemacs")
16497 "\\'")))
16498 (setq files (mapcar 'file-name-sans-extension files))
16499 (setq files (mapcar
16500 (lambda (x) (if (string-match remove-re x) nil x))
16501 files))
16502 (setq files (delq nil files))
16503 (mapc
16504 (lambda (f)
16505 (when (featurep (intern (file-name-nondirectory f)))
16506 (if (and (not uncompiled)
16507 (file-exists-p (concat f ".elc")))
16508 (load (concat f ".elc") nil nil t)
16509 (load (concat f ".el") nil nil t))))
16510 files))
16511 (org-version))
16513 ;;;###autoload
16514 (defun org-customize ()
16515 "Call the customize function with org as argument."
16516 (interactive)
16517 (org-load-modules-maybe)
16518 (org-require-autoloaded-modules)
16519 (customize-browse 'org))
16521 (defun org-create-customize-menu ()
16522 "Create a full customization menu for Org-mode, insert it into the menu."
16523 (interactive)
16524 (org-load-modules-maybe)
16525 (org-require-autoloaded-modules)
16526 (if (fboundp 'customize-menu-create)
16527 (progn
16528 (easy-menu-change
16529 '("Org") "Customize"
16530 `(["Browse Org group" org-customize t]
16531 "--"
16532 ,(customize-menu-create 'org)
16533 ["Set" Custom-set t]
16534 ["Save" Custom-save t]
16535 ["Reset to Current" Custom-reset-current t]
16536 ["Reset to Saved" Custom-reset-saved t]
16537 ["Reset to Standard Settings" Custom-reset-standard t]))
16538 (message "\"Org\"-menu now contains full customization menu"))
16539 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16541 ;;;; Miscellaneous stuff
16543 ;;; Generally useful functions
16545 (defun org-get-at-bol (property)
16546 "Get text property PROPERTY at beginning of line."
16547 (get-text-property (point-at-bol) property))
16549 (defun org-find-text-property-in-string (prop s)
16550 "Return the first non-nil value of property PROP in string S."
16551 (or (get-text-property 0 prop s)
16552 (get-text-property (or (next-single-property-change 0 prop s) 0)
16553 prop s)))
16555 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16556 "Display the given MESSAGE as a warning."
16557 (if (fboundp 'display-warning)
16558 (display-warning 'org message
16559 (if (featurep 'xemacs)
16560 'warning
16561 :warning))
16562 (let ((buf (get-buffer-create "*Org warnings*")))
16563 (with-current-buffer buf
16564 (goto-char (point-max))
16565 (insert "Warning (Org): " message)
16566 (unless (bolp)
16567 (newline)))
16568 (display-buffer buf)
16569 (sit-for 0))))
16571 (defun org-in-commented-line ()
16572 "Is point in a line starting with `#'?"
16573 (equal (char-after (point-at-bol)) ?#))
16575 (defun org-in-verbatim-emphasis ()
16576 (save-match-data
16577 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16579 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16580 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16581 (if (and marker (marker-buffer marker)
16582 (buffer-live-p (marker-buffer marker)))
16583 (progn
16584 (switch-to-buffer (marker-buffer marker))
16585 (if (or (> marker (point-max)) (< marker (point-min)))
16586 (widen))
16587 (goto-char marker)
16588 (org-show-context 'org-goto))
16589 (if bookmark
16590 (bookmark-jump bookmark)
16591 (error "Cannot find location"))))
16593 (defun org-quote-csv-field (s)
16594 "Quote field for inclusion in CSV material."
16595 (if (string-match "[\",]" s)
16596 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16599 (defun org-plist-delete (plist property)
16600 "Delete PROPERTY from PLIST.
16601 This is in contrast to merely setting it to 0."
16602 (let (p)
16603 (while plist
16604 (if (not (eq property (car plist)))
16605 (setq p (plist-put p (car plist) (nth 1 plist))))
16606 (setq plist (cddr plist)))
16609 (defun org-force-self-insert (N)
16610 "Needed to enforce self-insert under remapping."
16611 (interactive "p")
16612 (self-insert-command N))
16614 (defun org-string-width (s)
16615 "Compute width of string, ignoring invisible characters.
16616 This ignores character with invisibility property `org-link', and also
16617 characters with property `org-cwidth', because these will become invisible
16618 upon the next fontification round."
16619 (let (b l)
16620 (when (or (eq t buffer-invisibility-spec)
16621 (assq 'org-link buffer-invisibility-spec))
16622 (while (setq b (text-property-any 0 (length s)
16623 'invisible 'org-link s))
16624 (setq s (concat (substring s 0 b)
16625 (substring s (or (next-single-property-change
16626 b 'invisible s) (length s)))))))
16627 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16628 (setq s (concat (substring s 0 b)
16629 (substring s (or (next-single-property-change
16630 b 'org-cwidth s) (length s))))))
16631 (setq l (string-width s) b -1)
16632 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16633 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16636 (defun org-get-indentation (&optional line)
16637 "Get the indentation of the current line, interpreting tabs.
16638 When LINE is given, assume it represents a line and compute its indentation."
16639 (if line
16640 (if (string-match "^ *" (org-remove-tabs line))
16641 (match-end 0))
16642 (save-excursion
16643 (beginning-of-line 1)
16644 (skip-chars-forward " \t")
16645 (current-column))))
16647 (defun org-remove-tabs (s &optional width)
16648 "Replace tabulators in S with spaces.
16649 Assumes that s is a single line, starting in column 0."
16650 (setq width (or width tab-width))
16651 (while (string-match "\t" s)
16652 (setq s (replace-match
16653 (make-string
16654 (- (* width (/ (+ (match-beginning 0) width) width))
16655 (match-beginning 0)) ?\ )
16656 t t s)))
16659 (defun org-fix-indentation (line ind)
16660 "Fix indentation in LINE.
16661 IND is a cons cell with target and minimum indentation.
16662 If the current indentation in LINE is smaller than the minimum,
16663 leave it alone. If it is larger than ind, set it to the target."
16664 (let* ((l (org-remove-tabs line))
16665 (i (org-get-indentation l))
16666 (i1 (car ind)) (i2 (cdr ind)))
16667 (if (>= i i2) (setq l (substring line i2)))
16668 (if (> i1 0)
16669 (concat (make-string i1 ?\ ) l)
16670 l)))
16672 (defun org-remove-indentation (code &optional n)
16673 "Remove the maximum common indentation from the lines in CODE.
16674 N may optionally be the number of spaces to remove."
16675 (with-temp-buffer
16676 (insert code)
16677 (org-do-remove-indentation n)
16678 (buffer-string)))
16680 (defun org-do-remove-indentation (&optional n)
16681 "Remove the maximum common indentation from the buffer."
16682 (untabify (point-min) (point-max))
16683 (let ((min 10000) re)
16684 (if n
16685 (setq min n)
16686 (goto-char (point-min))
16687 (while (re-search-forward "^ *[^ \n]" nil t)
16688 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16689 (unless (or (= min 0) (= min 10000))
16690 (setq re (format "^ \\{%d\\}" min))
16691 (goto-char (point-min))
16692 (while (re-search-forward re nil t)
16693 (replace-match "")
16694 (end-of-line 1))
16695 min)))
16697 (defun org-fill-template (template alist)
16698 "Find each %key of ALIST in TEMPLATE and replace it."
16699 (let ((case-fold-search nil)
16700 entry key value)
16701 (setq alist (sort (copy-sequence alist)
16702 (lambda (a b) (< (length (car a)) (length (car b))))))
16703 (while (setq entry (pop alist))
16704 (setq template
16705 (replace-regexp-in-string
16706 (concat "%" (regexp-quote (car entry)))
16707 (cdr entry) template t t)))
16708 template))
16710 (defun org-base-buffer (buffer)
16711 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16712 (if (not buffer)
16713 buffer
16714 (or (buffer-base-buffer buffer)
16715 buffer)))
16717 (defun org-trim (s)
16718 "Remove whitespace at beginning and end of string."
16719 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16720 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16723 (defun org-wrap (string &optional width lines)
16724 "Wrap string to either a number of lines, or a width in characters.
16725 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16726 that costs. If there is a word longer than WIDTH, the text is actually
16727 wrapped to the length of that word.
16728 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16729 many lines, whatever width that takes.
16730 The return value is a list of lines, without newlines at the end."
16731 (let* ((words (org-split-string string "[ \t\n]+"))
16732 (maxword (apply 'max (mapcar 'org-string-width words)))
16733 w ll)
16734 (cond (width
16735 (org-do-wrap words (max maxword width)))
16736 (lines
16737 (setq w maxword)
16738 (setq ll (org-do-wrap words maxword))
16739 (if (<= (length ll) lines)
16741 (setq ll words)
16742 (while (> (length ll) lines)
16743 (setq w (1+ w))
16744 (setq ll (org-do-wrap words w)))
16745 ll))
16746 (t (error "Cannot wrap this")))))
16748 (defun org-do-wrap (words width)
16749 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16750 (let (lines line)
16751 (while words
16752 (setq line (pop words))
16753 (while (and words (< (+ (length line) (length (car words))) width))
16754 (setq line (concat line " " (pop words))))
16755 (setq lines (push line lines)))
16756 (nreverse lines)))
16758 (defun org-split-string (string &optional separators)
16759 "Splits STRING into substrings at SEPARATORS.
16760 No empty strings are returned if there are matches at the beginning
16761 and end of string."
16762 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16763 (start 0)
16764 notfirst
16765 (list nil))
16766 (while (and (string-match rexp string
16767 (if (and notfirst
16768 (= start (match-beginning 0))
16769 (< start (length string)))
16770 (1+ start) start))
16771 (< (match-beginning 0) (length string)))
16772 (setq notfirst t)
16773 (or (eq (match-beginning 0) 0)
16774 (and (eq (match-beginning 0) (match-end 0))
16775 (eq (match-beginning 0) start))
16776 (setq list
16777 (cons (substring string start (match-beginning 0))
16778 list)))
16779 (setq start (match-end 0)))
16780 (or (eq start (length string))
16781 (setq list
16782 (cons (substring string start)
16783 list)))
16784 (nreverse list)))
16786 (defun org-quote-vert (s)
16787 "Replace \"|\" with \"\\vert\"."
16788 (while (string-match "|" s)
16789 (setq s (replace-match "\\vert" t t s)))
16792 (defun org-uuidgen-p (s)
16793 "Is S an ID created by UUIDGEN?"
16794 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16796 (defun org-context ()
16797 "Return a list of contexts of the current cursor position.
16798 If several contexts apply, all are returned.
16799 Each context entry is a list with a symbol naming the context, and
16800 two positions indicating start and end of the context. Possible
16801 contexts are:
16803 :headline anywhere in a headline
16804 :headline-stars on the leading stars in a headline
16805 :todo-keyword on a TODO keyword (including DONE) in a headline
16806 :tags on the TAGS in a headline
16807 :priority on the priority cookie in a headline
16808 :item on the first line of a plain list item
16809 :item-bullet on the bullet/number of a plain list item
16810 :checkbox on the checkbox in a plain list item
16811 :table in an org-mode table
16812 :table-special on a special filed in a table
16813 :table-table in a table.el table
16814 :link on a hyperlink
16815 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16816 :target on a <<target>>
16817 :radio-target on a <<<radio-target>>>
16818 :latex-fragment on a LaTeX fragment
16819 :latex-preview on a LaTeX fragment with overlayed preview image
16821 This function expects the position to be visible because it uses font-lock
16822 faces as a help to recognize the following contexts: :table-special, :link,
16823 and :keyword."
16824 (let* ((f (get-text-property (point) 'face))
16825 (faces (if (listp f) f (list f)))
16826 (p (point)) clist o)
16827 ;; First the large context
16828 (cond
16829 ((org-on-heading-p t)
16830 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16831 (when (progn
16832 (beginning-of-line 1)
16833 (looking-at org-todo-line-tags-regexp))
16834 (push (org-point-in-group p 1 :headline-stars) clist)
16835 (push (org-point-in-group p 2 :todo-keyword) clist)
16836 (push (org-point-in-group p 4 :tags) clist))
16837 (goto-char p)
16838 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16839 (if (looking-at "\\[#[A-Z0-9]\\]")
16840 (push (org-point-in-group p 0 :priority) clist)))
16842 ((org-at-item-p)
16843 (push (org-point-in-group p 2 :item-bullet) clist)
16844 (push (list :item (point-at-bol)
16845 (save-excursion (org-end-of-item) (point)))
16846 clist)
16847 (and (org-at-item-checkbox-p)
16848 (push (org-point-in-group p 0 :checkbox) clist)))
16850 ((org-at-table-p)
16851 (push (list :table (org-table-begin) (org-table-end)) clist)
16852 (if (memq 'org-formula faces)
16853 (push (list :table-special
16854 (previous-single-property-change p 'face)
16855 (next-single-property-change p 'face)) clist)))
16856 ((org-at-table-p 'any)
16857 (push (list :table-table) clist)))
16858 (goto-char p)
16860 ;; Now the small context
16861 (cond
16862 ((org-at-timestamp-p)
16863 (push (org-point-in-group p 0 :timestamp) clist))
16864 ((memq 'org-link faces)
16865 (push (list :link
16866 (previous-single-property-change p 'face)
16867 (next-single-property-change p 'face)) clist))
16868 ((memq 'org-special-keyword faces)
16869 (push (list :keyword
16870 (previous-single-property-change p 'face)
16871 (next-single-property-change p 'face)) clist))
16872 ((org-on-target-p)
16873 (push (org-point-in-group p 0 :target) clist)
16874 (goto-char (1- (match-beginning 0)))
16875 (if (looking-at org-radio-target-regexp)
16876 (push (org-point-in-group p 0 :radio-target) clist))
16877 (goto-char p))
16878 ((setq o (car (delq nil
16879 (mapcar
16880 (lambda (x)
16881 (if (memq x org-latex-fragment-image-overlays) x))
16882 (org-overlays-at (point))))))
16883 (push (list :latex-fragment
16884 (org-overlay-start o) (org-overlay-end o)) clist)
16885 (push (list :latex-preview
16886 (org-overlay-start o) (org-overlay-end o)) clist))
16887 ((org-inside-LaTeX-fragment-p)
16888 ;; FIXME: positions wrong.
16889 (push (list :latex-fragment (point) (point)) clist)))
16891 (setq clist (nreverse (delq nil clist)))
16892 clist))
16894 ;; FIXME: Compare with at-regexp-p Do we need both?
16895 (defun org-in-regexp (re &optional nlines visually)
16896 "Check if point is inside a match of regexp.
16897 Normally only the current line is checked, but you can include NLINES extra
16898 lines both before and after point into the search.
16899 If VISUALLY is set, require that the cursor is not after the match but
16900 really on, so that the block visually is on the match."
16901 (catch 'exit
16902 (let ((pos (point))
16903 (eol (point-at-eol (+ 1 (or nlines 0))))
16904 (inc (if visually 1 0)))
16905 (save-excursion
16906 (beginning-of-line (- 1 (or nlines 0)))
16907 (while (re-search-forward re eol t)
16908 (if (and (<= (match-beginning 0) pos)
16909 (>= (+ inc (match-end 0)) pos))
16910 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16912 (defun org-at-regexp-p (regexp)
16913 "Is point inside a match of REGEXP in the current line?"
16914 (catch 'exit
16915 (save-excursion
16916 (let ((pos (point)) (end (point-at-eol)))
16917 (beginning-of-line 1)
16918 (while (re-search-forward regexp end t)
16919 (if (and (<= (match-beginning 0) pos)
16920 (>= (match-end 0) pos))
16921 (throw 'exit t)))
16922 nil))))
16924 (defun org-occur-in-agenda-files (regexp &optional nlines)
16925 "Call `multi-occur' with buffers for all agenda files."
16926 (interactive "sOrg-files matching: \np")
16927 (let* ((files (org-agenda-files))
16928 (tnames (mapcar 'file-truename files))
16929 (extra org-agenda-text-search-extra-files)
16931 (when (eq (car extra) 'agenda-archives)
16932 (setq extra (cdr extra))
16933 (setq files (org-add-archive-files files)))
16934 (while (setq f (pop extra))
16935 (unless (member (file-truename f) tnames)
16936 (add-to-list 'files f 'append)
16937 (add-to-list 'tnames (file-truename f) 'append)))
16938 (multi-occur
16939 (mapcar (lambda (x)
16940 (with-current-buffer
16941 (or (get-file-buffer x) (find-file-noselect x))
16942 (widen)
16943 (current-buffer)))
16944 files)
16945 regexp)))
16947 (if (boundp 'occur-mode-find-occurrence-hook)
16948 ;; Emacs 23
16949 (add-hook 'occur-mode-find-occurrence-hook
16950 (lambda ()
16951 (when (org-mode-p)
16952 (org-reveal))))
16953 ;; Emacs 22
16954 (defadvice occur-mode-goto-occurrence
16955 (after org-occur-reveal activate)
16956 (and (org-mode-p) (org-reveal)))
16957 (defadvice occur-mode-goto-occurrence-other-window
16958 (after org-occur-reveal activate)
16959 (and (org-mode-p) (org-reveal)))
16960 (defadvice occur-mode-display-occurrence
16961 (after org-occur-reveal activate)
16962 (when (org-mode-p)
16963 (let ((pos (occur-mode-find-occurrence)))
16964 (with-current-buffer (marker-buffer pos)
16965 (save-excursion
16966 (goto-char pos)
16967 (org-reveal)))))))
16969 (defun org-occur-link-in-agenda-files ()
16970 "Create a link and search for it in the agendas.
16971 The link is not stored in `org-stored-links', it is just created
16972 for the search purpose."
16973 (interactive)
16974 (let ((link (condition-case nil
16975 (org-store-link nil)
16976 (error "Unable to create a link to here"))))
16977 (org-occur-in-agenda-files (regexp-quote link))))
16979 (defun org-uniquify (list)
16980 "Remove duplicate elements from LIST."
16981 (let (res)
16982 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16983 res))
16985 (defun org-delete-all (elts list)
16986 "Remove all elements in ELTS from LIST."
16987 (while elts
16988 (setq list (delete (pop elts) list)))
16989 list)
16991 (defun org-back-over-empty-lines ()
16992 "Move backwards over whitespace, to the beginning of the first empty line.
16993 Returns the number of empty lines passed."
16994 (let ((pos (point)))
16995 (skip-chars-backward " \t\n\r")
16996 (beginning-of-line 2)
16997 (goto-char (min (point) pos))
16998 (count-lines (point) pos)))
17000 (defun org-skip-whitespace ()
17001 (skip-chars-forward " \t\n\r"))
17003 (defun org-point-in-group (point group &optional context)
17004 "Check if POINT is in match-group GROUP.
17005 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17006 match. If the match group does ot exist or point is not inside it,
17007 return nil."
17008 (and (match-beginning group)
17009 (>= point (match-beginning group))
17010 (<= point (match-end group))
17011 (if context
17012 (list context (match-beginning group) (match-end group))
17013 t)))
17015 (defun org-switch-to-buffer-other-window (&rest args)
17016 "Switch to buffer in a second window on the current frame.
17017 In particular, do not allow pop-up frames."
17018 (let (pop-up-frames special-display-buffer-names special-display-regexps
17019 special-display-function)
17020 (apply 'switch-to-buffer-other-window args)))
17022 (defun org-combine-plists (&rest plists)
17023 "Create a single property list from all plists in PLISTS.
17024 The process starts by copying the first list, and then setting properties
17025 from the other lists. Settings in the last list are the most significant
17026 ones and overrule settings in the other lists."
17027 (let ((rtn (copy-sequence (pop plists)))
17028 p v ls)
17029 (while plists
17030 (setq ls (pop plists))
17031 (while ls
17032 (setq p (pop ls) v (pop ls))
17033 (setq rtn (plist-put rtn p v))))
17034 rtn))
17036 (defun org-move-line-down (arg)
17037 "Move the current line down. With prefix argument, move it past ARG lines."
17038 (interactive "p")
17039 (let ((col (current-column))
17040 beg end pos)
17041 (beginning-of-line 1) (setq beg (point))
17042 (beginning-of-line 2) (setq end (point))
17043 (beginning-of-line (+ 1 arg))
17044 (setq pos (move-marker (make-marker) (point)))
17045 (insert (delete-and-extract-region beg end))
17046 (goto-char pos)
17047 (org-move-to-column col)))
17049 (defun org-move-line-up (arg)
17050 "Move the current line up. With prefix argument, move it past ARG lines."
17051 (interactive "p")
17052 (let ((col (current-column))
17053 beg end pos)
17054 (beginning-of-line 1) (setq beg (point))
17055 (beginning-of-line 2) (setq end (point))
17056 (beginning-of-line (- arg))
17057 (setq pos (move-marker (make-marker) (point)))
17058 (insert (delete-and-extract-region beg end))
17059 (goto-char pos)
17060 (org-move-to-column col)))
17062 (defun org-replace-escapes (string table)
17063 "Replace %-escapes in STRING with values in TABLE.
17064 TABLE is an association list with keys like \"%a\" and string values.
17065 The sequences in STRING may contain normal field width and padding information,
17066 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17067 so values can contain further %-escapes if they are define later in TABLE."
17068 (let ((case-fold-search nil)
17069 e re rpl)
17070 (while (setq e (pop table))
17071 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17072 (while (string-match re string)
17073 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17074 (cdr e)))
17075 (setq string (replace-match rpl t t string))))
17076 string))
17079 (defun org-sublist (list start end)
17080 "Return a section of LIST, from START to END.
17081 Counting starts at 1."
17082 (let (rtn (c start))
17083 (setq list (nthcdr (1- start) list))
17084 (while (and list (<= c end))
17085 (push (pop list) rtn)
17086 (setq c (1+ c)))
17087 (nreverse rtn)))
17089 (defun org-find-base-buffer-visiting (file)
17090 "Like `find-buffer-visiting' but always return the base buffer and
17091 not an indirect buffer."
17092 (let ((buf (or (get-file-buffer file)
17093 (find-buffer-visiting file))))
17094 (if buf
17095 (or (buffer-base-buffer buf) buf)
17096 nil)))
17098 (defun org-image-file-name-regexp (&optional extensions)
17099 "Return regexp matching the file names of images.
17100 If EXTENSIONS is given, only match these."
17101 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17102 (image-file-name-regexp)
17103 (let ((image-file-name-extensions
17104 (or extensions
17105 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17106 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17107 (concat "\\."
17108 (regexp-opt (nconc (mapcar 'upcase
17109 image-file-name-extensions)
17110 image-file-name-extensions)
17112 "\\'"))))
17114 (defun org-file-image-p (file &optional extensions)
17115 "Return non-nil if FILE is an image."
17116 (save-match-data
17117 (string-match (org-image-file-name-regexp extensions) file)))
17119 (defun org-get-cursor-date ()
17120 "Return the date at cursor in as a time.
17121 This works in the calendar and in the agenda, anywhere else it just
17122 returns the current time."
17123 (let (date day defd)
17124 (cond
17125 ((eq major-mode 'calendar-mode)
17126 (setq date (calendar-cursor-to-date)
17127 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17128 ((eq major-mode 'org-agenda-mode)
17129 (setq day (get-text-property (point) 'day))
17130 (if day
17131 (setq date (calendar-gregorian-from-absolute day)
17132 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17133 (nth 2 date))))))
17134 (or defd (current-time))))
17136 (defvar org-agenda-action-marker (make-marker)
17137 "Marker pointing to the entry for the next agenda action.")
17139 (defun org-mark-entry-for-agenda-action ()
17140 "Mark the current entry as target of an agenda action.
17141 Agenda actions are actions executed from the agenda with the key `k',
17142 which make use of the date at the cursor."
17143 (interactive)
17144 (move-marker org-agenda-action-marker
17145 (save-excursion (org-back-to-heading t) (point))
17146 (current-buffer))
17147 (message
17148 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17150 ;;; Paragraph filling stuff.
17151 ;; We want this to be just right, so use the full arsenal.
17153 (defun org-indent-line-function ()
17154 "Indent line like previous, but further if previous was headline or item."
17155 (interactive)
17156 (let* ((pos (point))
17157 (itemp (org-at-item-p))
17158 (case-fold-search t)
17159 (org-drawer-regexp (or org-drawer-regexp "\000"))
17160 column bpos bcol tpos tcol bullet btype bullet-type)
17161 ;; Find the previous relevant line
17162 (beginning-of-line 1)
17163 (cond
17164 ((looking-at "#") (setq column 0))
17165 ((looking-at "\\*+ ") (setq column 0))
17166 ((and (looking-at "[ \t]*:END:")
17167 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17168 (save-excursion
17169 (goto-char (1- (match-beginning 1)))
17170 (setq column (current-column))))
17171 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17172 (save-excursion
17173 (re-search-backward
17174 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17175 (setq column (org-get-indentation (match-string 0))))
17177 (beginning-of-line 0)
17178 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17179 (not (looking-at "[ \t]*:END:"))
17180 (not (looking-at org-drawer-regexp)))
17181 (beginning-of-line 0))
17182 (cond
17183 ((looking-at "\\*+[ \t]+")
17184 (if (not org-adapt-indentation)
17185 (setq column 0)
17186 (goto-char (match-end 0))
17187 (setq column (current-column))))
17188 ((looking-at org-drawer-regexp)
17189 (goto-char (1- (match-beginning 1)))
17190 (setq column (current-column)))
17191 ((looking-at "\\([ \t]*\\):END:")
17192 (goto-char (match-end 1))
17193 (setq column (current-column)))
17194 ((org-in-item-p)
17195 (org-beginning-of-item)
17196 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17197 (setq bpos (match-beginning 1) tpos (match-end 0)
17198 bcol (progn (goto-char bpos) (current-column))
17199 tcol (progn (goto-char tpos) (current-column))
17200 bullet (match-string 1)
17201 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17202 (if (> tcol (+ bcol org-description-max-indent))
17203 (setq tcol (+ bcol 5)))
17204 (if (not itemp)
17205 (setq column tcol)
17206 (goto-char pos)
17207 (beginning-of-line 1)
17208 (if (looking-at "\\S-")
17209 (progn
17210 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17211 (setq bullet (match-string 1)
17212 btype (if (string-match "[0-9]" bullet) "n" bullet))
17213 (setq column (if (equal btype bullet-type) bcol tcol)))
17214 (setq column (org-get-indentation)))))
17215 (t (setq column (org-get-indentation))))))
17216 (goto-char pos)
17217 (if (<= (current-column) (current-indentation))
17218 (org-indent-line-to column)
17219 (save-excursion (org-indent-line-to column)))
17220 (setq column (current-column))
17221 (beginning-of-line 1)
17222 (if (looking-at
17223 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17224 (replace-match (concat (match-string 1)
17225 (format org-property-format
17226 (match-string 2) (match-string 3)))
17227 t t))
17228 (org-move-to-column column)))
17230 (defun org-set-autofill-regexps ()
17231 (interactive)
17232 ;; In the paragraph separator we include headlines, because filling
17233 ;; text in a line directly attached to a headline would otherwise
17234 ;; fill the headline as well.
17235 (org-set-local 'comment-start-skip "^#+[ \t]*")
17236 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17237 ;; The paragraph starter includes hand-formatted lists.
17238 (org-set-local
17239 'paragraph-start
17240 (concat
17241 "\f" "\\|"
17242 "[ ]*$" "\\|"
17243 "\\*+ " "\\|"
17244 "[ \t]*#" "\\|"
17245 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17246 "[ \t]*[:|]" "\\|"
17247 "\\$\\$" "\\|"
17248 "\\\\\\(begin\\|end\\|[][]\\)"))
17249 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17250 ;; But only if the user has not turned off tables or fixed-width regions
17251 (org-set-local
17252 'auto-fill-inhibit-regexp
17253 (concat "\\*+ \\|#\\+"
17254 "\\|[ \t]*" org-keyword-time-regexp
17255 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17256 (concat
17257 "\\|[ \t]*["
17258 (if org-enable-table-editor "|" "")
17259 (if org-enable-fixed-width-editor ":" "")
17260 "]"))))
17261 ;; We use our own fill-paragraph function, to make sure that tables
17262 ;; and fixed-width regions are not wrapped. That function will pass
17263 ;; through to `fill-paragraph' when appropriate.
17264 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17265 ; Adaptive filling: To get full control, first make sure that
17266 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17267 (org-set-local 'adaptive-fill-regexp "\000")
17268 (org-set-local 'adaptive-fill-function
17269 'org-adaptive-fill-function)
17270 (org-set-local
17271 'align-mode-rules-list
17272 '((org-in-buffer-settings
17273 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17274 (modes . '(org-mode))))))
17276 (defun org-fill-paragraph (&optional justify)
17277 "Re-align a table, pass through to fill-paragraph if no table."
17278 (let ((table-p (org-at-table-p))
17279 (table.el-p (org-at-table.el-p)))
17280 (cond ((and (equal (char-after (point-at-bol)) ?*)
17281 (save-excursion (goto-char (point-at-bol))
17282 (looking-at outline-regexp)))
17283 t) ; skip headlines
17284 (table.el-p t) ; skip table.el tables
17285 (table-p (org-table-align) t) ; align org-mode tables
17286 (t nil)))) ; call paragraph-fill
17288 ;; For reference, this is the default value of adaptive-fill-regexp
17289 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17291 (defun org-adaptive-fill-function ()
17292 "Return a fill prefix for org-mode files.
17293 In particular, this makes sure hanging paragraphs for hand-formatted lists
17294 work correctly."
17295 (cond ((looking-at "#[ \t]+")
17296 (match-string 0))
17297 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17298 (save-excursion
17299 (if (> (match-end 1) (+ (match-beginning 1)
17300 org-description-max-indent))
17301 (goto-char (+ (match-beginning 1) 5))
17302 (goto-char (match-end 0)))
17303 (make-string (current-column) ?\ )))
17304 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17305 (save-excursion
17306 (goto-char (match-end 0))
17307 (make-string (current-column) ?\ )))
17308 (t nil)))
17310 ;;; Other stuff.
17312 (defun org-toggle-fixed-width-section (arg)
17313 "Toggle the fixed-width export.
17314 If there is no active region, the QUOTE keyword at the current headline is
17315 inserted or removed. When present, it causes the text between this headline
17316 and the next to be exported as fixed-width text, and unmodified.
17317 If there is an active region, this command adds or removes a colon as the
17318 first character of this line. If the first character of a line is a colon,
17319 this line is also exported in fixed-width font."
17320 (interactive "P")
17321 (let* ((cc 0)
17322 (regionp (org-region-active-p))
17323 (beg (if regionp (region-beginning) (point)))
17324 (end (if regionp (region-end)))
17325 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17326 (case-fold-search nil)
17327 (re "[ \t]*\\(: \\)")
17328 off)
17329 (if regionp
17330 (save-excursion
17331 (goto-char beg)
17332 (setq cc (current-column))
17333 (beginning-of-line 1)
17334 (setq off (looking-at re))
17335 (while (> nlines 0)
17336 (setq nlines (1- nlines))
17337 (beginning-of-line 1)
17338 (cond
17339 (arg
17340 (org-move-to-column cc t)
17341 (insert ": \n")
17342 (forward-line -1))
17343 ((and off (looking-at re))
17344 (replace-match "" t t nil 1))
17345 ((not off) (org-move-to-column cc t) (insert ": ")))
17346 (forward-line 1)))
17347 (save-excursion
17348 (org-back-to-heading)
17349 (if (looking-at (concat outline-regexp
17350 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17351 (replace-match "" t t nil 1)
17352 (if (looking-at outline-regexp)
17353 (progn
17354 (goto-char (match-end 0))
17355 (insert org-quote-string " "))))))))
17357 (defun org-reftex-citation ()
17358 "Use reftex-citation to insert a citation into the buffer.
17359 This looks for a line like
17361 #+BIBLIOGRAPHY: foo plain option:-d
17363 and derives from it that foo.bib is the bibliography file relevant
17364 for this document. It then installs the necessary environment for RefTeX
17365 to work in this buffer and calls `reftex-citation' to insert a citation
17366 into the buffer.
17368 Export of such citations to both LaTeX and HTML is handled by the contributed
17369 package org-exp-bibtex by Taru Karttunen."
17370 (interactive)
17371 (let ((reftex-docstruct-symbol 'rds)
17372 (reftex-cite-format "\\cite{%l}")
17373 rds bib)
17374 (save-excursion
17375 (save-restriction
17376 (widen)
17377 (let ((case-fold-search t)
17378 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17379 (if (not (save-excursion
17380 (or (re-search-forward re nil t)
17381 (re-search-backward re nil t))))
17382 (error "No bibliography defined in file")
17383 (setq bib (concat (match-string 1) ".bib")
17384 rds (list (list 'bib bib)))))))
17385 (call-interactively 'reftex-citation)))
17387 ;;;; Functions extending outline functionality
17389 (defun org-beginning-of-line (&optional arg)
17390 "Go to the beginning of the current line. If that is invisible, continue
17391 to a visible line beginning. This makes the function of C-a more intuitive.
17392 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17393 first attempt, and only move to after the tags when the cursor is already
17394 beyond the end of the headline."
17395 (interactive "P")
17396 (let ((pos (point))
17397 (special (if (consp org-special-ctrl-a/e)
17398 (car org-special-ctrl-a/e)
17399 org-special-ctrl-a/e))
17400 refpos)
17401 (if (org-bound-and-true-p line-move-visual)
17402 (beginning-of-visual-line 1)
17403 (beginning-of-line 1))
17404 (if (and arg (fboundp 'move-beginning-of-line))
17405 (call-interactively 'move-beginning-of-line)
17406 (if (bobp)
17408 (backward-char 1)
17409 (if (org-invisible-p)
17410 (while (and (not (bobp)) (org-invisible-p))
17411 (backward-char 1)
17412 (beginning-of-line 1))
17413 (forward-char 1))))
17414 (when special
17415 (cond
17416 ((and (looking-at org-complex-heading-regexp)
17417 (= (char-after (match-end 1)) ?\ ))
17418 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17419 (point-at-eol)))
17420 (goto-char
17421 (if (eq special t)
17422 (cond ((> pos refpos) refpos)
17423 ((= pos (point)) refpos)
17424 (t (point)))
17425 (cond ((> pos (point)) (point))
17426 ((not (eq last-command this-command)) (point))
17427 (t refpos)))))
17428 ((org-at-item-p)
17429 (goto-char
17430 (if (eq special t)
17431 (cond ((> pos (match-end 4)) (match-end 4))
17432 ((= pos (point)) (match-end 4))
17433 (t (point)))
17434 (cond ((> pos (point)) (point))
17435 ((not (eq last-command this-command)) (point))
17436 (t (match-end 4))))))))
17437 (org-no-warnings
17438 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17440 (defun org-end-of-line (&optional arg)
17441 "Go to the end of the line.
17442 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17443 first attempt, and only move to after the tags when the cursor is already
17444 beyond the end of the headline."
17445 (interactive "P")
17446 (let ((special (if (consp org-special-ctrl-a/e)
17447 (cdr org-special-ctrl-a/e)
17448 org-special-ctrl-a/e)))
17449 (if (or (not special)
17450 (not (org-on-heading-p))
17451 arg)
17452 (call-interactively
17453 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17454 ((fboundp 'move-end-of-line) 'move-end-of-line)
17455 (t 'end-of-line)))
17456 (let ((pos (point)))
17457 (beginning-of-line 1)
17458 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17459 (if (eq special t)
17460 (if (or (< pos (match-beginning 1))
17461 (= pos (match-end 0)))
17462 (goto-char (match-beginning 1))
17463 (goto-char (match-end 0)))
17464 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17465 (goto-char (match-end 0))
17466 (goto-char (match-beginning 1))))
17467 (call-interactively (if (fboundp 'move-end-of-line)
17468 'move-end-of-line
17469 'end-of-line)))))
17470 (org-no-warnings
17471 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17473 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17474 (define-key org-mode-map "\C-e" 'org-end-of-line)
17475 (define-key org-mode-map [home] 'org-beginning-of-line)
17476 (define-key org-mode-map [end] 'org-end-of-line)
17478 (defun org-backward-sentence (&optional arg)
17479 "Go to beginning of sentence, or beginning of table field.
17480 This will call `backward-sentence' or `org-table-beginning-of-field',
17481 depending on context."
17482 (interactive "P")
17483 (cond
17484 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17485 (t (call-interactively 'backward-sentence))))
17487 (defun org-forward-sentence (&optional arg)
17488 "Go to end of sentence, or end of table field.
17489 This will call `forward-sentence' or `org-table-end-of-field',
17490 depending on context."
17491 (interactive "P")
17492 (cond
17493 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17494 (t (call-interactively 'forward-sentence))))
17496 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17497 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17499 (defun org-kill-line (&optional arg)
17500 "Kill line, to tags or end of line."
17501 (interactive "P")
17502 (cond
17503 ((or (not org-special-ctrl-k)
17504 (bolp)
17505 (not (org-on-heading-p)))
17506 (call-interactively 'kill-line))
17507 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17508 (kill-region (point) (match-beginning 1))
17509 (org-set-tags nil t))
17510 (t (kill-region (point) (point-at-eol)))))
17512 (define-key org-mode-map "\C-k" 'org-kill-line)
17514 (defun org-yank (&optional arg)
17515 "Yank. If the kill is a subtree, treat it specially.
17516 This command will look at the current kill and check if is a single
17517 subtree, or a series of subtrees[1]. If it passes the test, and if the
17518 cursor is at the beginning of a line or after the stars of a currently
17519 empty headline, then the yank is handled specially. How exactly depends
17520 on the value of the following variables, both set by default.
17522 org-yank-folded-subtrees
17523 When set, the subtree(s) will be folded after insertion, but only
17524 if doing so would now swallow text after the yanked text.
17526 org-yank-adjusted-subtrees
17527 When set, the subtree will be promoted or demoted in order to
17528 fit into the local outline tree structure, which means that the level
17529 will be adjusted so that it becomes the smaller one of the two
17530 *visible* surrounding headings.
17532 Any prefix to this command will cause `yank' to be called directly with
17533 no special treatment. In particular, a simple `C-u' prefix will just
17534 plainly yank the text as it is.
17536 \[1] The test checks if the first non-white line is a heading
17537 and if there are no other headings with fewer stars."
17538 (interactive "P")
17539 (org-yank-generic 'yank arg))
17541 (defun org-yank-generic (command arg)
17542 "Perform some yank-like command.
17544 This function implements the behavior described in the `org-yank'
17545 documentation. However, it has been generalized to work for any
17546 interactive command with similar behavior."
17548 ;; pretend to be command COMMAND
17549 (setq this-command command)
17551 (if arg
17552 (call-interactively command)
17554 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17555 (and (org-kill-is-subtree-p)
17556 (or (bolp)
17557 (and (looking-at "[ \t]*$")
17558 (string-match
17559 "\\`\\*+\\'"
17560 (buffer-substring (point-at-bol) (point)))))))
17561 swallowp)
17562 (cond
17563 ((and subtreep org-yank-folded-subtrees)
17564 (let ((beg (point))
17565 end)
17566 (if (and subtreep org-yank-adjusted-subtrees)
17567 (org-paste-subtree nil nil 'for-yank)
17568 (call-interactively command))
17570 (setq end (point))
17571 (goto-char beg)
17572 (when (and (bolp) subtreep
17573 (not (setq swallowp
17574 (org-yank-folding-would-swallow-text beg end))))
17575 (or (looking-at outline-regexp)
17576 (re-search-forward (concat "^" outline-regexp) end t))
17577 (while (and (< (point) end) (looking-at outline-regexp))
17578 (hide-subtree)
17579 (org-cycle-show-empty-lines 'folded)
17580 (condition-case nil
17581 (outline-forward-same-level 1)
17582 (error (goto-char end)))))
17583 (when swallowp
17584 (message
17585 "Inserted text not folded because that would swallow text"))
17587 (goto-char end)
17588 (skip-chars-forward " \t\n\r")
17589 (beginning-of-line 1)
17590 (push-mark beg 'nomsg)))
17591 ((and subtreep org-yank-adjusted-subtrees)
17592 (let ((beg (point-at-bol)))
17593 (org-paste-subtree nil nil 'for-yank)
17594 (push-mark beg 'nomsg)))
17596 (call-interactively command))))))
17598 (defun org-yank-folding-would-swallow-text (beg end)
17599 "Would hide-subtree at BEG swallow any text after END?"
17600 (let (level)
17601 (save-excursion
17602 (goto-char beg)
17603 (when (or (looking-at outline-regexp)
17604 (re-search-forward (concat "^" outline-regexp) end t))
17605 (setq level (org-outline-level)))
17606 (goto-char end)
17607 (skip-chars-forward " \t\r\n\v\f")
17608 (if (or (eobp)
17609 (and (bolp) (looking-at org-outline-regexp)
17610 (<= (org-outline-level) level)))
17611 nil ; Nothing would be swallowed
17612 t)))) ; something would swallow
17614 (define-key org-mode-map "\C-y" 'org-yank)
17616 (defun org-invisible-p ()
17617 "Check if point is at a character currently not visible."
17618 ;; Early versions of noutline don't have `outline-invisible-p'.
17619 (if (fboundp 'outline-invisible-p)
17620 (outline-invisible-p)
17621 (get-char-property (point) 'invisible)))
17623 (defun org-invisible-p2 ()
17624 "Check if point is at a character currently not visible."
17625 (save-excursion
17626 (if (and (eolp) (not (bobp))) (backward-char 1))
17627 ;; Early versions of noutline don't have `outline-invisible-p'.
17628 (if (fboundp 'outline-invisible-p)
17629 (outline-invisible-p)
17630 (get-char-property (point) 'invisible))))
17632 (defun org-back-to-heading (&optional invisible-ok)
17633 "Call `outline-back-to-heading', but provide a better error message."
17634 (condition-case nil
17635 (outline-back-to-heading invisible-ok)
17636 (error (error "Before first headline at position %d in buffer %s"
17637 (point) (current-buffer)))))
17639 (defun org-before-first-heading-p ()
17640 "Before first heading?"
17641 (save-excursion
17642 (null (re-search-backward "^\\*+ " nil t))))
17644 (defun org-on-heading-p (&optional ignored)
17645 (outline-on-heading-p t))
17646 (defun org-at-heading-p (&optional ignored)
17647 (outline-on-heading-p t))
17649 (defun org-at-heading-or-item-p ()
17650 (or (org-on-heading-p) (org-at-item-p)))
17652 (defun org-on-target-p ()
17653 (or (org-in-regexp org-radio-target-regexp)
17654 (org-in-regexp org-target-regexp)))
17656 (defun org-up-heading-all (arg)
17657 "Move to the heading line of which the present line is a subheading.
17658 This function considers both visible and invisible heading lines.
17659 With argument, move up ARG levels."
17660 (if (fboundp 'outline-up-heading-all)
17661 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17662 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17664 (defun org-up-heading-safe ()
17665 "Move to the heading line of which the present line is a subheading.
17666 This version will not throw an error. It will return the level of the
17667 headline found, or nil if no higher level is found.
17669 Also, this function will be a lot faster than `outline-up-heading',
17670 because it relies on stars being the outline starters. This can really
17671 make a significant difference in outlines with very many siblings."
17672 (let (start-level re)
17673 (org-back-to-heading t)
17674 (setq start-level (funcall outline-level))
17675 (if (equal start-level 1)
17677 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17678 (if (re-search-backward re nil t)
17679 (funcall outline-level)))))
17681 (defun org-first-sibling-p ()
17682 "Is this heading the first child of its parents?"
17683 (interactive)
17684 (let ((re (concat "^" outline-regexp))
17685 level l)
17686 (unless (org-at-heading-p t)
17687 (error "Not at a heading"))
17688 (setq level (funcall outline-level))
17689 (save-excursion
17690 (if (not (re-search-backward re nil t))
17692 (setq l (funcall outline-level))
17693 (< l level)))))
17695 (defun org-goto-sibling (&optional previous)
17696 "Goto the next sibling, even if it is invisible.
17697 When PREVIOUS is set, go to the previous sibling instead. Returns t
17698 when a sibling was found. When none is found, return nil and don't
17699 move point."
17700 (let ((fun (if previous 're-search-backward 're-search-forward))
17701 (pos (point))
17702 (re (concat "^" outline-regexp))
17703 level l)
17704 (when (condition-case nil (org-back-to-heading t) (error nil))
17705 (setq level (funcall outline-level))
17706 (catch 'exit
17707 (or previous (forward-char 1))
17708 (while (funcall fun re nil t)
17709 (setq l (funcall outline-level))
17710 (when (< l level) (goto-char pos) (throw 'exit nil))
17711 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17712 (goto-char pos)
17713 nil))))
17715 (defun org-show-siblings ()
17716 "Show all siblings of the current headline."
17717 (save-excursion
17718 (while (org-goto-sibling) (org-flag-heading nil)))
17719 (save-excursion
17720 (while (org-goto-sibling 'previous)
17721 (org-flag-heading nil))))
17723 (defun org-show-hidden-entry ()
17724 "Show an entry where even the heading is hidden."
17725 (save-excursion
17726 (org-show-entry)))
17728 (defun org-flag-heading (flag &optional entry)
17729 "Flag the current heading. FLAG non-nil means make invisible.
17730 When ENTRY is non-nil, show the entire entry."
17731 (save-excursion
17732 (org-back-to-heading t)
17733 ;; Check if we should show the entire entry
17734 (if entry
17735 (progn
17736 (org-show-entry)
17737 (save-excursion
17738 (and (outline-next-heading)
17739 (org-flag-heading nil))))
17740 (outline-flag-region (max (point-min) (1- (point)))
17741 (save-excursion (outline-end-of-heading) (point))
17742 flag))))
17744 (defun org-get-next-sibling ()
17745 "Move to next heading of the same level, and return point.
17746 If there is no such heading, return nil.
17747 This is like outline-next-sibling, but invisible headings are ok."
17748 (let ((level (funcall outline-level)))
17749 (outline-next-heading)
17750 (while (and (not (eobp)) (> (funcall outline-level) level))
17751 (outline-next-heading))
17752 (if (or (eobp) (< (funcall outline-level) level))
17754 (point))))
17756 (defun org-get-last-sibling ()
17757 "Move to previous heading of the same level, and return point.
17758 If there is no such heading, return nil."
17759 (let ((opoint (point))
17760 (level (funcall outline-level)))
17761 (outline-previous-heading)
17762 (when (and (/= (point) opoint) (outline-on-heading-p t))
17763 (while (and (> (funcall outline-level) level)
17764 (not (bobp)))
17765 (outline-previous-heading))
17766 (if (< (funcall outline-level) level)
17768 (point)))))
17770 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17771 ;; This contains an exact copy of the original function, but it uses
17772 ;; `org-back-to-heading', to make it work also in invisible
17773 ;; trees. And is uses an invisible-OK argument.
17774 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17775 ;; Furthermore, when used inside Org, finding the end of a large subtree
17776 ;; with many children and grandchildren etc, this can be much faster
17777 ;; than the outline version.
17778 (org-back-to-heading invisible-OK)
17779 (let ((first t)
17780 (level (funcall outline-level)))
17781 (if (and (org-mode-p) (< level 1000))
17782 ;; A true heading (not a plain list item), in Org-mode
17783 ;; This means we can easily find the end by looking
17784 ;; only for the right number of stars. Using a regexp to do
17785 ;; this is so much faster than using a Lisp loop.
17786 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17787 (forward-char 1)
17788 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17789 ;; something else, do it the slow way
17790 (while (and (not (eobp))
17791 (or first (> (funcall outline-level) level)))
17792 (setq first nil)
17793 (outline-next-heading)))
17794 (unless to-heading
17795 (if (memq (preceding-char) '(?\n ?\^M))
17796 (progn
17797 ;; Go to end of line before heading
17798 (forward-char -1)
17799 (if (memq (preceding-char) '(?\n ?\^M))
17800 ;; leave blank line before heading
17801 (forward-char -1))))))
17802 (point))
17804 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17805 "Use Org version in org-mode, for dramatic speed-up."
17806 (if (eq major-mode 'org-mode)
17807 (progn
17808 (org-end-of-subtree nil t)
17809 (unless (eobp) (backward-char 1)))
17810 ad-do-it))
17812 (defun org-forward-same-level (arg &optional invisible-ok)
17813 "Move forward to the arg'th subheading at same level as this one.
17814 Stop at the first and last subheadings of a superior heading."
17815 (interactive "p")
17816 (org-back-to-heading invisible-ok)
17817 (org-on-heading-p)
17818 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17819 (re (format "^\\*\\{1,%d\\} " level))
17821 (forward-char 1)
17822 (while (> arg 0)
17823 (while (and (re-search-forward re nil 'move)
17824 (setq l (- (match-end 0) (match-beginning 0) 1))
17825 (= l level)
17826 (not invisible-ok)
17827 (progn (backward-char 1) (org-invisible-p)))
17828 (if (< l level) (setq arg 1)))
17829 (setq arg (1- arg)))
17830 (beginning-of-line 1)))
17832 (defun org-backward-same-level (arg &optional invisible-ok)
17833 "Move backward to the arg'th subheading at same level as this one.
17834 Stop at the first and last subheadings of a superior heading."
17835 (interactive "p")
17836 (org-back-to-heading)
17837 (org-on-heading-p)
17838 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17839 (re (format "^\\*\\{1,%d\\} " level))
17841 (while (> arg 0)
17842 (while (and (re-search-backward re nil 'move)
17843 (setq l (- (match-end 0) (match-beginning 0) 1))
17844 (= l level)
17845 (not invisible-ok)
17846 (org-invisible-p))
17847 (if (< l level) (setq arg 1)))
17848 (setq arg (1- arg)))))
17850 (defun org-show-subtree ()
17851 "Show everything after this heading at deeper levels."
17852 (outline-flag-region
17853 (point)
17854 (save-excursion
17855 (org-end-of-subtree t t))
17856 nil))
17858 (defun org-show-entry ()
17859 "Show the body directly following this heading.
17860 Show the heading too, if it is currently invisible."
17861 (interactive)
17862 (save-excursion
17863 (condition-case nil
17864 (progn
17865 (org-back-to-heading t)
17866 (outline-flag-region
17867 (max (point-min) (1- (point)))
17868 (save-excursion
17869 (if (re-search-forward
17870 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17871 (match-beginning 1)
17872 (point-max)))
17873 nil)
17874 (org-cycle-hide-drawers 'children))
17875 (error nil))))
17877 (defun org-make-options-regexp (kwds &optional extra)
17878 "Make a regular expression for keyword lines."
17879 (concat
17881 "#?[ \t]*\\+\\("
17882 (mapconcat 'regexp-quote kwds "\\|")
17883 (if extra (concat "\\|" extra))
17884 "\\):[ \t]*"
17885 "\\(.*\\)"))
17887 ;; Make isearch reveal the necessary context
17888 (defun org-isearch-end ()
17889 "Reveal context after isearch exits."
17890 (when isearch-success ; only if search was successful
17891 (if (featurep 'xemacs)
17892 ;; Under XEmacs, the hook is run in the correct place,
17893 ;; we directly show the context.
17894 (org-show-context 'isearch)
17895 ;; In Emacs the hook runs *before* restoring the overlays.
17896 ;; So we have to use a one-time post-command-hook to do this.
17897 ;; (Emacs 22 has a special variable, see function `org-mode')
17898 (unless (and (boundp 'isearch-mode-end-hook-quit)
17899 isearch-mode-end-hook-quit)
17900 ;; Only when the isearch was not quitted.
17901 (org-add-hook 'post-command-hook 'org-isearch-post-command
17902 'append 'local)))))
17904 (defun org-isearch-post-command ()
17905 "Remove self from hook, and show context."
17906 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17907 (org-show-context 'isearch))
17910 ;;;; Integration with and fixes for other packages
17912 ;;; Imenu support
17914 (defvar org-imenu-markers nil
17915 "All markers currently used by Imenu.")
17916 (make-variable-buffer-local 'org-imenu-markers)
17918 (defun org-imenu-new-marker (&optional pos)
17919 "Return a new marker for use by Imenu, and remember the marker."
17920 (let ((m (make-marker)))
17921 (move-marker m (or pos (point)))
17922 (push m org-imenu-markers)
17925 (defun org-imenu-get-tree ()
17926 "Produce the index for Imenu."
17927 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17928 (setq org-imenu-markers nil)
17929 (let* ((n org-imenu-depth)
17930 (re (concat "^" outline-regexp))
17931 (subs (make-vector (1+ n) nil))
17932 (last-level 0)
17933 m level head)
17934 (save-excursion
17935 (save-restriction
17936 (widen)
17937 (goto-char (point-max))
17938 (while (re-search-backward re nil t)
17939 (setq level (org-reduced-level (funcall outline-level)))
17940 (when (<= level n)
17941 (looking-at org-complex-heading-regexp)
17942 (setq head (org-link-display-format
17943 (org-match-string-no-properties 4))
17944 m (org-imenu-new-marker))
17945 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17946 (if (>= level last-level)
17947 (push (cons head m) (aref subs level))
17948 (push (cons head (aref subs (1+ level))) (aref subs level))
17949 (loop for i from (1+ level) to n do (aset subs i nil)))
17950 (setq last-level level)))))
17951 (aref subs 1)))
17953 (eval-after-load "imenu"
17954 '(progn
17955 (add-hook 'imenu-after-jump-hook
17956 (lambda ()
17957 (if (eq major-mode 'org-mode)
17958 (org-show-context 'org-goto))))))
17960 (defun org-link-display-format (link)
17961 "Replace a link with either the description, or the link target
17962 if no description is present"
17963 (save-match-data
17964 (if (string-match org-bracket-link-analytic-regexp link)
17965 (replace-match (if (match-end 5)
17966 (match-string 5 link)
17967 (concat (match-string 1 link)
17968 (match-string 3 link)))
17969 nil t link)
17970 link)))
17972 ;; Speedbar support
17974 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17975 "Overlay marking the agenda restriction line in speedbar.")
17976 (org-overlay-put org-speedbar-restriction-lock-overlay
17977 'face 'org-agenda-restriction-lock)
17978 (org-overlay-put org-speedbar-restriction-lock-overlay
17979 'help-echo "Agendas are currently limited to this item.")
17980 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17982 (defun org-speedbar-set-agenda-restriction ()
17983 "Restrict future agenda commands to the location at point in speedbar.
17984 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17985 (interactive)
17986 (require 'org-agenda)
17987 (let (p m tp np dir txt)
17988 (cond
17989 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17990 'org-imenu t))
17991 (setq m (get-text-property p 'org-imenu-marker))
17992 (with-current-buffer (marker-buffer m)
17993 (goto-char m)
17994 (org-agenda-set-restriction-lock 'subtree)))
17995 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17996 'speedbar-function 'speedbar-find-file))
17997 (setq tp (previous-single-property-change
17998 (1+ p) 'speedbar-function)
17999 np (next-single-property-change
18000 tp 'speedbar-function)
18001 dir (speedbar-line-directory)
18002 txt (buffer-substring-no-properties (or tp (point-min))
18003 (or np (point-max))))
18004 (with-current-buffer (find-file-noselect
18005 (let ((default-directory dir))
18006 (expand-file-name txt)))
18007 (unless (org-mode-p)
18008 (error "Cannot restrict to non-Org-mode file"))
18009 (org-agenda-set-restriction-lock 'file)))
18010 (t (error "Don't know how to restrict Org-mode's agenda")))
18011 (org-move-overlay org-speedbar-restriction-lock-overlay
18012 (point-at-bol) (point-at-eol))
18013 (setq current-prefix-arg nil)
18014 (org-agenda-maybe-redo)))
18016 (eval-after-load "speedbar"
18017 '(progn
18018 (speedbar-add-supported-extension ".org")
18019 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18020 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18021 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18022 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18023 (add-hook 'speedbar-visiting-tag-hook
18024 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18027 ;;; Fixes and Hacks for problems with other packages
18029 ;; Make flyspell not check words in links, to not mess up our keymap
18030 (defun org-mode-flyspell-verify ()
18031 "Don't let flyspell put overlays at active buttons."
18032 (and (not (get-text-property (point) 'keymap))
18033 (not (get-text-property (point) 'org-no-flyspell))))
18035 (defun org-remove-flyspell-overlays-in (beg end)
18036 "Remove flyspell overlays in region."
18037 (and (org-bound-and-true-p flyspell-mode)
18038 (fboundp 'flyspell-delete-region-overlays)
18039 (flyspell-delete-region-overlays beg end))
18040 (add-text-properties beg end '(org-no-flyspell t)))
18042 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18043 (eval-after-load "bookmark"
18044 '(if (boundp 'bookmark-after-jump-hook)
18045 ;; We can use the hook
18046 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18047 ;; Hook not available, use advice
18048 (defadvice bookmark-jump (after org-make-visible activate)
18049 "Make the position visible."
18050 (org-bookmark-jump-unhide))))
18052 ;; Make sure saveplace shows the location if it was hidden
18053 (eval-after-load "saveplace"
18054 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18055 "Make the position visible."
18056 (org-bookmark-jump-unhide)))
18058 ;; Make sure ecb shows the location if it was hidden
18059 (eval-after-load "ecb"
18060 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18061 "Make hierarchy visible when jumping into location from ECB tree buffer."
18062 (if (eq major-mode 'org-mode)
18063 (org-show-context))))
18065 (defun org-bookmark-jump-unhide ()
18066 "Unhide the current position, to show the bookmark location."
18067 (and (org-mode-p)
18068 (or (org-invisible-p)
18069 (save-excursion (goto-char (max (point-min) (1- (point))))
18070 (org-invisible-p)))
18071 (org-show-context 'bookmark-jump)))
18073 ;; Make session.el ignore our circular variable
18074 (eval-after-load "session"
18075 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18077 ;;;; Experimental code
18079 (defun org-closed-in-range ()
18080 "Sparse tree of items closed in a certain time range.
18081 Still experimental, may disappear in the future."
18082 (interactive)
18083 ;; Get the time interval from the user.
18084 (let* ((time1 (org-float-time
18085 (org-read-date nil 'to-time nil "Starting date: ")))
18086 (time2 (org-float-time
18087 (org-read-date nil 'to-time nil "End date:")))
18088 ;; callback function
18089 (callback (lambda ()
18090 (let ((time
18091 (org-float-time
18092 (apply 'encode-time
18093 (org-parse-time-string
18094 (match-string 1))))))
18095 ;; check if time in interval
18096 (and (>= time time1) (<= time time2))))))
18097 ;; make tree, check each match with the callback
18098 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18100 ;;;; Finish up
18102 (provide 'org)
18104 (run-hooks 'org-load-hook)
18106 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18108 ;;; org.el ends here